@metamask/transaction-controller 62.0.0 → 62.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/types.mjs CHANGED
@@ -120,6 +120,10 @@ export var TransactionType;
120
120
  * A transaction that withdraws tokens from a lending contract.
121
121
  */
122
122
  TransactionType["lendingWithdraw"] = "lendingWithdraw";
123
+ /**
124
+ * A transaction that converts tokens to mUSD.
125
+ */
126
+ TransactionType["musdConversion"] = "musdConversion";
123
127
  /**
124
128
  * Deposit funds to be available for trading via Perps.
125
129
  */
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAqmBA;;;;;;;;GAQG;AACH,MAAM,CAAN,IAAY,iBAmDX;AAnDD,WAAY,iBAAiB;IAC3B;;OAEG;IACH,8CAAyB,CAAA;IAEzB;;;OAGG;IACH,0CAAqB,CAAA;IAErB;;;OAGG;IACH,sCAAiB,CAAA;IAEjB;;OAEG;IACH,4CAAuB,CAAA;IAEvB;;;OAGG;IACH,4CAAuB,CAAA;IAEvB;;;OAGG;IACH,sCAAiB,CAAA;IAEjB;;;OAGG;IACH,wCAAmB,CAAA;IAEnB;;;OAGG;IACH,0CAAqB,CAAA;IAErB;;OAEG;IACH,4CAAuB,CAAA;AACzB,CAAC,EAnDW,iBAAiB,KAAjB,iBAAiB,QAmD5B;AAED;;GAEG;AACH,MAAM,CAAN,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,6CAA6B,CAAA;IAC7B,mDAAmC,CAAA;IACnC,sCAAsB,CAAA;AACxB,CAAC,EAJW,YAAY,KAAZ,YAAY,QAIvB;AAED;;GAEG;AACH,MAAM,CAAN,IAAY,eAkNX;AAlND,WAAY,eAAe;IACzB;;;OAGG;IACH,kCAAe,CAAA;IAEf;;OAEG;IACH,oCAAiB,CAAA;IAEjB;;;;;OAKG;IACH,oDAAiC,CAAA;IAEjC;;OAEG;IACH,oCAAiB,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List } from '@ethereumjs/tx';\nimport type { AccountsController } from '@metamask/accounts-controller';\nimport type EthQuery from '@metamask/eth-query';\nimport type { GasFeeState } from '@metamask/gas-fee-controller';\nimport type { NetworkClientId, Provider } from '@metamask/network-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Operation } from 'fast-json-patch';\n\nimport type { TransactionControllerMessenger } from './TransactionController';\n\n/**\n * Given a record, ensures that each property matches the `Json` type.\n */\ntype MakeJsonCompatible<T> = T extends Json\n ? T\n : {\n [K in keyof T]: T[K] extends Json ? T[K] : never;\n };\n\n/**\n * `Json` from `@metamask/utils` is defined as a recursive type alias, but\n * `Operation` is defined as an interface, and the two are not compatible with\n * each other. Therefore, this is a variant of Operation from `fast-json-patch`\n * which is guaranteed to be type-compatible with `Json`.\n */\ntype JsonCompatibleOperation = MakeJsonCompatible<Operation>;\n\n/**\n * Information about a single transaction such as status and block number.\n */\nexport type TransactionMeta = {\n /**\n * ID of the transaction that approved the swap token transfer.\n */\n approvalTxId?: string;\n\n /**\n * The fiat value of the transaction to be used to passed metrics.\n */\n assetsFiatValues?: AssetsFiatValues;\n\n /**\n * Unique ID to prevent duplicate requests.\n */\n actionId?: string;\n\n /**\n * Base fee of the block as a hex value, introduced in EIP-1559.\n */\n baseFeePerGas?: Hex;\n\n /**\n * ID of the associated transaction batch.\n */\n batchId?: Hex;\n\n /**\n * Additional transactions that must also be submitted in a batch.\n */\n batchTransactions?: BatchTransaction[];\n\n /**\n * Optional configuration when processing `batchTransactions`.\n */\n batchTransactionsOptions?: {\n /**\n * Whether to disable batch transaction processing via an EIP-7702 upgraded account.\n * Defaults to `true` if no options object, `false` otherwise.\n */\n disable7702?: boolean;\n\n /**\n * Whether to disable batch transaction via the `publishBatch` hook.\n * Defaults to `false`.\n */\n disableHook?: boolean;\n\n /**\n * Whether to disable batch transaction via sequential transactions.\n * Defaults to `true` if no options object, `false` otherwise.\n */\n disableSequential?: boolean;\n };\n\n /**\n * Number of the block where the transaction has been included.\n */\n blockNumber?: string;\n\n /**\n * The timestamp for when the block was collated.\n */\n blockTimestamp?: string;\n\n /**\n * Network code as per EIP-155 for this transaction.\n */\n chainId: Hex;\n\n /**\n * List of container types applied to the original transaction data.\n * For example, through delegations.\n */\n containerTypes?: TransactionContainerType[];\n\n /**\n * A string representing a name of transaction contract method.\n */\n contractMethodName?: string;\n\n /**\n * The balance of the token that is being sent.\n */\n currentTokenBalance?: string;\n\n /** The optional custom nonce override as a decimal string. */\n customNonceValue?: string;\n\n /**\n * The custom token amount is the amount set by the user.\n */\n customTokenAmount?: string;\n\n /**\n * The dapp proposed token amount.\n */\n dappProposedTokenAmount?: string;\n\n /**\n * Gas values provided by the dApp.\n */\n dappSuggestedGasFees?: DappSuggestedGasFees;\n\n /**\n * The initial gas values set when the transaction was first created.\n */\n defaultGasEstimates?: DefaultGasEstimates;\n\n /**\n * Address of the sender's current contract code delegation.\n * Introduced in EIP-7702.\n */\n delegationAddress?: Hex;\n\n /**\n * String to indicate what device the transaction was confirmed on.\n */\n deviceConfirmedOn?: WalletDevice;\n\n /**\n * The Network ID as per EIP-155 of the destination chain of a bridge transaction.\n */\n destinationChainId?: Hex;\n\n /**\n * The address of the token being received of swap transaction.\n */\n destinationTokenAddress?: string;\n\n /**\n * The raw amount of the destination token\n */\n destinationTokenAmount?: string;\n\n /**\n * The decimals of the token being received of swap transaction.\n */\n destinationTokenDecimals?: number;\n\n /**\n * The symbol of the token being received with swap.\n */\n destinationTokenSymbol?: string;\n\n /**\n * Whether to disable the buffer added to gas limit estimations.\n * Defaults to adding the buffer.\n */\n disableGasBuffer?: boolean;\n\n /**\n * Error that occurred during the transaction processing.\n */\n error?: TransactionError;\n\n /**\n * The estimated base fee of the transaction.\n */\n estimatedBaseFee?: string;\n\n /**\n * Which estimate level that the API suggested.\n */\n estimateSuggested?: string;\n\n /**\n * Which estimate level was used\n */\n estimateUsed?: string;\n\n /**\n * The chosen amount which will be the same as the originally proposed token\n * amount if the user does not edit the amount or will be a custom token\n * amount set by the user.\n */\n finalApprovalAmount?: string;\n\n /**\n * The number of the latest block when the transaction submit was first retried.\n */\n firstRetryBlockNumber?: string;\n\n /** Available tokens that can be used to pay for gas. */\n gasFeeTokens?: GasFeeToken[];\n\n /**\n * Whether the transaction is active.\n */\n isActive?: boolean;\n\n /**\n * Whether the transaction is the first time interaction.\n */\n isFirstTimeInteraction?: boolean;\n\n /**\n * Whether the transaction is sponsored meaning the user does not pay the gas fee.\n */\n isGasFeeSponsored?: boolean;\n\n /** Alternate EIP-1559 gas fee estimates for multiple priority levels. */\n gasFeeEstimates?: GasFeeEstimates;\n\n /** Whether the gas fee estimates have been checked at least once. */\n gasFeeEstimatesLoaded?: boolean;\n\n /**\n * The estimated gas for the transaction without any buffer applied.\n */\n gasLimitNoBuffer?: string;\n\n /**\n * The estimated gas used by the transaction, after any refunds. Generated from transaction simulation.\n */\n gasUsed?: Hex;\n\n /**\n * A hex string of the transaction hash, used to identify the transaction on the network.\n */\n hash?: string;\n\n /**\n * A history of mutations to TransactionMeta.\n */\n history?: TransactionHistory;\n\n /**\n * Generated UUID associated with this transaction.\n */\n id: string;\n\n /**\n * Whether the transaction is signed externally.\n * No signing will be performed in the client and the `nonce` will be `undefined`.\n */\n isExternalSign?: boolean;\n\n /** Whether MetaMask will be compensated for the gas fee by the transaction. */\n isGasFeeIncluded?: boolean;\n\n /** Whether the `selectedGasFeeToken` is only used if the user has insufficient native balance. */\n isGasFeeTokenIgnoredIfBalance?: boolean;\n\n /** Whether the intent of the transaction was achieved via an alternate route or chain. */\n isIntentComplete?: boolean;\n\n /**\n * Whether the transaction is an incoming token transfer.\n */\n isTransfer?: boolean;\n\n /**\n * Whether the transaction entry is generated from a user operation.\n */\n isUserOperation?: boolean;\n\n /**\n * Additional gas fees to cover the cost of persisting data on layer 1 for layer 2 networks.\n */\n layer1GasFee?: Hex;\n\n /**\n * Data for any nested transactions.\n * For example, in an atomic batch transaction via EIP-7702.\n */\n nestedTransactions?: NestedTransactionMetadata[];\n\n /**\n * The ID of the network client used by the transaction.\n */\n networkClientId: NetworkClientId;\n\n /**\n * Network code as per EIP-155 for this transaction\n *\n * @deprecated Use `chainId` instead.\n */\n readonly networkID?: string;\n\n /**\n * Origin this transaction was sent from.\n */\n origin?: string;\n\n /**\n * The original dapp proposed token approval amount before edit by user.\n */\n originalApprovalAmount?: string;\n\n /**\n * The original gas estimation of the transaction.\n */\n originalGasEstimate?: string;\n\n /**\n * When we speed up a transaction, we set the type as Retry and we lose\n * information about type of transaction that is being set up, so we use\n * original type to track that information.\n */\n originalType?: TransactionType;\n\n /** Metadata specific to the MetaMask Pay feature. */\n metamaskPay?: MetamaskPayMetadata;\n\n /**\n * Account transaction balance after swap.\n */\n postTxBalance?: string;\n\n /**\n * Account transaction balance before swap.\n */\n preTxBalance?: string;\n\n /**\n * The previous gas properties before they were updated.\n */\n previousGas?: {\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gasLimit?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n };\n\n /**\n * The transaction's 'r' value as a hex string.\n */\n r?: string;\n\n /**\n * Hex representation of the underlying transaction.\n */\n rawTx?: string;\n\n /**\n * When the transaction is dropped, this is the replacement transaction hash.\n */\n replacedBy?: string;\n\n /**\n * When the transaction is dropped, this is the replacement transaction ID.\n */\n replacedById?: string;\n\n /**\n * IDs of any transactions that must be confirmed before this one is submitted.\n * Unlike a transaction batch, these transactions can be on alternate chains.\n */\n requiredTransactionIds?: string[];\n\n /**\n * The number of times that the transaction submit has been retried.\n */\n retryCount?: number;\n\n /**\n * The transaction's 's' value as a hex string.\n */\n s?: string;\n\n /**\n * Response from security validator.\n */\n securityAlertResponse?: SecurityAlertResponse;\n\n /**\n * Response from security provider.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n securityProviderResponse?: Record<string, any>;\n\n /**\n * The token address of the selected gas fee token.\n * Corresponds to the `gasFeeTokens` property.\n */\n selectedGasFeeToken?: Hex;\n\n /**\n * An array of entries that describe the user's journey through the send flow.\n * This is purely attached to state logs for troubleshooting and support.\n */\n sendFlowHistory?: SendFlowHistoryEntry[];\n\n /**\n * Simulation data for the transaction used to predict its outcome.\n */\n simulationData?: SimulationData;\n\n /**\n * If the gas estimation fails, an object containing error and block information.\n */\n simulationFails?: {\n reason?: string;\n errorKey?: string;\n debug: {\n blockNumber?: string;\n blockGasLimit?: string;\n };\n };\n\n /** Current status of the transaction. */\n status: TransactionStatus;\n\n /**\n * The time the transaction was submitted to the network, in Unix epoch time (ms).\n */\n submittedTime?: number;\n\n /**\n * The address of the token being swapped\n */\n sourceTokenAddress?: string;\n\n /**\n * The raw amount of the source swap token\n */\n sourceTokenAmount?: string;\n\n /**\n * The decimals of the token being swapped.\n */\n sourceTokenDecimals?: number;\n\n /**\n * The symbol of the token being swapped.\n */\n sourceTokenSymbol?: string;\n\n /**\n * The address of the swap recipient.\n */\n swapAndSendRecipient?: string;\n\n /**\n * The metadata of the swap transaction.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapMetaData?: Record<string, any>;\n\n /**\n * The value of the token being swapped.\n */\n swapTokenValue?: string;\n\n /**\n * Timestamp associated with this transaction.\n */\n time: number;\n\n /**\n * Whether transaction recipient is a smart contract.\n */\n toSmartContract?: boolean;\n\n /**\n * Additional transfer information.\n */\n transferInformation?: {\n amount?: string;\n contractAddress: string;\n decimals: number;\n symbol: string;\n };\n\n /**\n * Underlying Transaction object.\n */\n txParams: TransactionParams;\n\n /**\n * Initial transaction parameters before `afterAdd` hook was invoked.\n */\n txParamsOriginal?: TransactionParams;\n\n /**\n * Transaction receipt.\n */\n txReceipt?: TransactionReceipt;\n\n /**\n * The type of transaction such as `cancel` or `swap`.\n */\n type?: TransactionType;\n\n /**\n * The gas limit supplied by user.\n */\n userEditedGasLimit?: boolean;\n\n /**\n * Estimate level user selected.\n */\n userFeeLevel?: string;\n\n /**\n * The transaction's 'v' value as a hex string.\n */\n v?: string;\n\n /**\n * Whether the transaction is verified on the blockchain.\n */\n verifiedOnBlockchain?: boolean;\n\n /**\n * Warning information for the transaction.\n */\n warning?: {\n error: string;\n message: string;\n };\n};\n\n/**\n * Information about a batch transaction.\n */\nexport type TransactionBatchMeta = {\n /**\n * Network code as per EIP-155 for this transaction.\n */\n chainId: Hex;\n\n /**\n * Address to send this transaction from.\n */\n from: string;\n\n /** Alternate EIP-1559 gas fee estimates for multiple priority levels. */\n gasFeeEstimates?: GasFeeEstimates;\n\n /**\n * Maximum number of units of gas to use for this transaction batch.\n */\n gas?: string;\n\n /**\n * ID of the associated transaction batch.\n */\n id: string;\n\n /**\n * The ID of the network client used by the transaction.\n */\n networkClientId: NetworkClientId;\n\n /**\n * Origin this transaction was sent from.\n */\n origin?: string;\n\n /** Current status of the transaction. */\n status: TransactionStatus;\n\n /**\n * Data for any EIP-7702 transactions.\n */\n transactions?: NestedTransactionMetadata[];\n};\n\nexport type SendFlowHistoryEntry = {\n /**\n * String to indicate user interaction information.\n */\n entry: string;\n\n /**\n * Timestamp associated with this entry.\n */\n timestamp: number;\n};\n\n/**\n * Represents the status of a transaction within the wallet.\n * Each status reflects the state of the transaction internally,\n * with some statuses corresponding to the transaction's state on the network.\n *\n * The typical transaction lifecycle follows this state machine:\n * unapproved -> approved -> signed -> submitted -> FINAL_STATE\n * where FINAL_STATE is one of: confirmed, failed, dropped, or rejected.\n */\nexport enum TransactionStatus {\n /**\n * The initial state of a transaction before user approval.\n */\n unapproved = 'unapproved',\n\n /**\n * The transaction has been approved by the user but is not yet signed.\n * This status is usually brief but may be longer for scenarios like hardware wallet usage.\n */\n approved = 'approved',\n\n /**\n * The transaction is signed and in the process of being submitted to the network.\n * This status is typically short-lived but can be longer for certain cases, such as smart transactions.\n */\n signed = 'signed',\n\n /**\n * The transaction has been submitted to the network and is awaiting confirmation.\n */\n submitted = 'submitted',\n\n /**\n * The transaction has been successfully executed and confirmed on the blockchain.\n * This is a final state.\n */\n confirmed = 'confirmed',\n\n /**\n * The transaction encountered an error during execution on the blockchain and failed.\n * This is a final state.\n */\n failed = 'failed',\n\n /**\n * The transaction was superseded by another transaction, resulting in its dismissal.\n * This is a final state.\n */\n dropped = 'dropped',\n\n /**\n * The transaction was rejected by the user and not processed further.\n * This is a final state.\n */\n rejected = 'rejected',\n\n /**\n * @deprecated This status is no longer used.\n */\n cancelled = 'cancelled',\n}\n\n/**\n * Options for wallet device.\n */\nexport enum WalletDevice {\n MM_MOBILE = 'metamask_mobile',\n MM_EXTENSION = 'metamask_extension',\n OTHER = 'other_device',\n}\n\n/**\n * The type of the transaction.\n */\nexport enum TransactionType {\n /**\n * A batch transaction that includes multiple nested transactions.\n * Introduced in EIP-7702.\n */\n batch = 'batch',\n\n /**\n * A transaction that bridges tokens to a different chain through Metamask Bridge.\n */\n bridge = 'bridge',\n\n /**\n * Similar to the approve type, a bridge approval is a special case of ERC20\n * approve method that requests an allowance of the token to spend on behalf\n * of the user for the MetaMask Bridge contract. The first bridge for any token\n * will have an accompanying bridgeApproval transaction.\n */\n bridgeApproval = 'bridgeApproval',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n cancel = 'cancel',\n\n /**\n * A transaction that is interacting with a smart contract's methods that we\n * have not treated as a special case, such as approve, transfer, and\n * transferfrom.\n */\n contractInteraction = 'contractInteraction',\n\n /**\n * A transaction that deployed a smart contract.\n */\n deployContract = 'contractDeployment',\n\n /**\n * A transaction for Ethereum decryption.\n */\n ethDecrypt = 'eth_decrypt',\n\n /**\n * A transaction for getting an encryption public key.\n */\n ethGetEncryptionPublicKey = 'eth_getEncryptionPublicKey',\n\n /**\n * Transaction is a token or native transfer to MetaMask to pay for gas fees.\n */\n gasPayment = 'gas_payment',\n\n /**\n * An incoming (deposit) transaction.\n */\n incoming = 'incoming',\n\n /**\n * A transaction that deposits tokens into a lending contract.\n */\n lendingDeposit = 'lendingDeposit',\n\n /**\n * A transaction that withdraws tokens from a lending contract.\n */\n lendingWithdraw = 'lendingWithdraw',\n\n /**\n * Deposit funds to be available for trading via Perps.\n */\n perpsDeposit = 'perpsDeposit',\n\n /**\n * A transaction for personal sign.\n */\n personalSign = 'personal_sign',\n\n /**\n * Buy a position via Predict.\n *\n * @deprecated Not used.\n */\n predictBuy = 'predictBuy',\n\n /**\n * Claim winnings from a position via Predict.\n */\n predictClaim = 'predictClaim',\n\n /**\n * Deposit funds to be available for use via Predict.\n */\n predictDeposit = 'predictDeposit',\n\n /**\n * Sell a position via Predict.\n *\n * @deprecated Not used.\n */\n predictSell = 'predictSell',\n\n /**\n * Withdraw funds from Predict.\n */\n predictWithdraw = 'predictWithdraw',\n\n /**\n * When a transaction is failed it can be retried by\n * resubmitting the same transaction with a higher gas fee. This type is also used\n * to speed up pending transactions. This is accomplished by creating a new tx with\n * the same nonce and higher gas fees.\n */\n retry = 'retry',\n\n /**\n * Remove the code / delegation from an upgraded EOA.\n * Introduced in EIP-7702.\n */\n revokeDelegation = 'revokeDelegation',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n simpleSend = 'simpleSend',\n\n /**\n * A transaction that is signing typed data.\n */\n signTypedData = 'eth_signTypedData',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n smart = 'smart',\n\n /**\n * A transaction that claims staking rewards.\n */\n stakingClaim = 'stakingClaim',\n\n /**\n * A transaction that deposits tokens into a staking contract.\n */\n stakingDeposit = 'stakingDeposit',\n\n /**\n * A transaction that unstakes tokens from a staking contract.\n */\n stakingUnstake = 'stakingUnstake',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps.\n */\n swap = 'swap',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps, then sending the swapped token to a recipient.\n */\n swapAndSend = 'swapAndSend',\n\n /**\n * Similar to the approve type, a swap approval is a special case of ERC20\n * approve method that requests an allowance of the token to spend on behalf\n * of the user for the MetaMask Swaps contract. The first swap for any token\n * will have an accompanying swapApproval transaction.\n */\n swapApproval = 'swapApproval',\n\n /**\n * A token transaction requesting an allowance of the token to spend on\n * behalf of the user.\n */\n tokenMethodApprove = 'approve',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. The method is prefixed with safe because when calling\n * this method the contract checks to ensure that the receiver is an address\n * capable of handling the token being sent.\n */\n tokenMethodSafeTransferFrom = 'safetransferfrom',\n\n /**\n * A token transaction where the user is sending tokens that they own to\n * another address.\n */\n tokenMethodTransfer = 'transfer',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. For more information on allowances, see the approve\n * type.\n */\n tokenMethodTransferFrom = 'transferfrom',\n\n /**\n * A token transaction requesting an allowance of all of a user's tokens to\n * spend on behalf of the user.\n */\n tokenMethodSetApprovalForAll = 'setapprovalforall',\n\n /**\n * Increase the allowance by a given increment\n */\n tokenMethodIncreaseAllowance = 'increaseAllowance',\n\n /**\n * A token approval transaction subscribing to the shield insurance service\n */\n shieldSubscriptionApprove = 'shieldSubscriptionApprove',\n}\n\nexport enum TransactionContainerType {\n /** Transaction has been converted to a delegation including caveats to validate the simulated balance changes. */\n EnforcedSimulations = 'enforcedSimulations',\n}\n\n/**\n * Standard data concerning a transaction to be processed by the blockchain.\n */\nexport type TransactionParams = {\n /**\n * A list of addresses and storage keys that the transaction plans to access.\n */\n accessList?: AccessList;\n\n /**\n * Array of authorizations to set code on EOA accounts.\n * Only supported in `setCode` transactions.\n * Introduced in EIP-7702.\n */\n authorizationList?: AuthorizationList;\n\n /**\n * Network ID as per EIP-155.\n *\n * @deprecated Ignored.\n * Use `networkClientId` when calling `addTransaction`.\n */\n chainId?: Hex;\n\n /**\n * Data to pass with this transaction.\n */\n data?: string;\n\n /**\n * Error message for gas estimation failure.\n */\n estimateGasError?: string;\n\n /**\n * Estimated base fee for this transaction.\n */\n estimatedBaseFee?: string;\n\n /**\n * Which estimate level that the API suggested.\n */\n estimateSuggested?: string;\n\n /**\n * Which estimate level was used\n */\n estimateUsed?: string;\n\n /**\n * Address to send this transaction from.\n */\n from: string;\n\n /**\n * Maximum number of units of gas to use for this transaction.\n */\n gas?: string;\n\n /**\n * Maximum number of units of gas to use for this transaction.\n *\n * @deprecated Use `gas` instead.\n */\n gasLimit?: string;\n\n /**\n * Price per gas for legacy txs\n */\n gasPrice?: string;\n\n /**\n * Gas used in the transaction.\n */\n gasUsed?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority\n * fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n\n /**\n * Unique number to prevent replay attacks.\n */\n nonce?: string;\n\n /**\n * Address to send this transaction to.\n */\n to?: string;\n\n /**\n * Value associated with this transaction.\n */\n value?: string;\n\n /**\n * Type of transaction.\n * 0x0 indicates a legacy transaction.\n */\n type?: string;\n};\n\n/**\n * Standard data concerning a transaction processed by the blockchain.\n */\nexport type TransactionReceipt = {\n /**\n * The block hash of the block that this transaction was included in.\n */\n blockHash?: string;\n\n /**\n * The block number of the block that this transaction was included in.\n */\n blockNumber?: string;\n\n /**\n * Effective gas price the transaction was charged at.\n */\n effectiveGasPrice?: string;\n\n /**\n * Gas used in the transaction.\n */\n gasUsed?: string;\n\n /**\n * Total used gas in hex.\n */\n l1Fee?: string;\n\n /**\n * All the logs emitted by this transaction.\n */\n logs?: Log[];\n\n /**\n * The status of the transaction.\n */\n status?: string;\n\n /** Hash of the associated transaction. */\n transactionHash?: Hex;\n\n /**\n * The hexadecimal index of this transaction in the list of transactions included in the block this transaction was mined in.\n */\n transactionIndex?: string;\n};\n\n/**\n * Represents an event that has been included in a transaction using the EVM `LOG` opcode.\n */\nexport type Log = {\n /**\n * Address of the contract that generated log.\n */\n address?: string;\n\n /** Data for the log. */\n data?: Hex;\n\n /**\n * List of topics for log.\n */\n topics?: string;\n};\n\n/**\n * The configuration required to fetch transaction data from a RemoteTransactionSource.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface RemoteTransactionSourceRequest {\n /**\n * The address of the account to fetch transactions for.\n */\n address: Hex;\n\n /**\n * Whether to also include incoming token transfers.\n */\n includeTokenTransfers: boolean;\n\n /**\n * Additional tags to identify the source of the request.\n */\n tags?: string[];\n\n /**\n * Whether to also retrieve outgoing transactions.\n */\n updateTransactions: boolean;\n}\n\n/**\n * An object capable of fetching transaction data from a remote source.\n * Used by the IncomingTransactionHelper to retrieve remote transaction data.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface RemoteTransactionSource {\n /**\n * @returns Array of chain IDs supported by the remote source.\n */\n getSupportedChains: () => Hex[];\n\n /**\n * @param request - A request object containing data such as the address and chain ID.\n * @returns An array of transaction metadata for the retrieved transactions.\n */\n fetchTransactions: (\n request: RemoteTransactionSourceRequest,\n ) => Promise<TransactionMeta[]>;\n}\n\n/**\n * Gas values initially suggested by the dApp.\n */\nexport type DappSuggestedGasFees = {\n gas?: string;\n gasPrice?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Gas values saved by the user for a specific chain.\n */\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SavedGasFees {\n maxBaseFee: string;\n priorityFee: string;\n}\n\n/**\n * A transaction history operation that includes a note and timestamp.\n */\ntype ExtendedHistoryOperation = JsonCompatibleOperation & {\n note?: string;\n timestamp?: number;\n};\n\n/**\n * A transaction history entry that includes the ExtendedHistoryOperation as the first element.\n */\nexport type TransactionHistoryEntry = [\n ExtendedHistoryOperation,\n ...JsonCompatibleOperation[],\n];\n\n/**\n * A transaction history that includes the transaction meta as the first element.\n * And the rest of the elements are the operation arrays that were applied to the transaction meta.\n */\nexport type TransactionHistory = [\n TransactionMeta,\n ...TransactionHistoryEntry[],\n];\n\n/**\n * Result of inferring the transaction type.\n */\nexport type InferTransactionTypeResult = {\n /**\n * The contract code, in hex format if it exists. '0x0' or\n * '0x' are also indicators of non-existent contract code.\n */\n getCodeResponse?: string | null;\n\n /**\n * The type of transaction\n */\n type: TransactionType;\n};\n\n/**\n * A function for verifying a transaction, whether it is malicious or not.\n */\nexport type SecurityProviderRequest = (\n requestData: TransactionMeta,\n messageType: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\n/**\n * Specifies the shape of the base transaction parameters.\n * Added in EIP-2718.\n */\nexport enum TransactionEnvelopeType {\n /**\n * A legacy transaction, the very first type.\n */\n legacy = '0x0',\n\n /**\n * EIP-2930 defined the access list transaction type that allowed for\n * specifying the state that a transaction would act upon in advance and\n * theoretically save on gas fees.\n */\n accessList = '0x1',\n\n /**\n * The type introduced comes from EIP-1559, Fee Market describes the addition\n * of a baseFee to blocks that will be burned instead of distributed to\n * miners. Transactions of this type have both a maxFeePerGas (maximum total\n * amount in gwei per gas to spend on the transaction) which is inclusive of\n * the maxPriorityFeePerGas (maximum amount of gwei per gas from the\n * transaction fee to distribute to miner).\n */\n feeMarket = '0x2',\n\n /**\n * Adds code to externally owned accounts according to the signed authorizations\n * in the new `authorizationList` parameter.\n * Introduced in EIP-7702.\n */\n setCode = '0x4',\n}\n\n/**\n * The source of the gas fee parameters on a transaction.\n */\nexport enum UserFeeLevel {\n CUSTOM = 'custom',\n DAPP_SUGGESTED = 'dappSuggested',\n MEDIUM = 'medium',\n}\n\n/**\n * Initial gas values set when the transaction was first created.\n */\nexport type DefaultGasEstimates = {\n /**\n * Source of the gas fee values, such as `dappSuggested` or `medium`.\n */\n estimateType?: string;\n\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gas?: string;\n\n /**\n * Price per gas for legacy transactions.\n */\n gasPrice?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Data concerning an error while processing a transaction.\n */\nexport type TransactionError = {\n /**\n * A descriptive error name.\n */\n name: string;\n\n /**\n * A descriptive error message providing details about the encountered error.\n */\n message: string;\n\n /**\n * The stack trace associated with the error, if available.\n */\n stack?: string;\n\n /**\n * An optional error code associated with the error.\n */\n code?: string;\n\n /**\n * The rpc property holds additional information related to the error.\n */\n // We are intentionally using `any` here instead of `Json` because it causes\n // `WritableDraft<TransactionMeta>` from Immer to cause TypeScript to error\n // with \"Type instantiation is excessively deep and possibly infinite\". See:\n // <https://github.com/immerjs/immer/issues/839>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc?: any;\n};\n\n/**\n * Type for security alert response from transaction validator.\n */\nexport type SecurityAlertResponse = {\n features?: string[];\n providerRequestsCount?: Record<string, number>;\n reason: string;\n result_type: string;\n securityAlertId?: string;\n};\n\n/** Alternate priority levels for which values are provided in gas fee estimates. */\nexport enum GasFeeEstimateLevel {\n Low = 'low',\n Medium = 'medium',\n High = 'high',\n}\n\n/** Type of gas fee estimate generated by a GasFeeFlow. */\nexport enum GasFeeEstimateType {\n FeeMarket = 'fee-market',\n Legacy = 'legacy',\n GasPrice = 'eth_gasPrice',\n}\n\n/** Gas fee estimates for a specific priority level. */\nexport type FeeMarketGasFeeEstimateForLevel = {\n /** Maximum amount to pay per gas. */\n maxFeePerGas: Hex;\n\n /** Maximum amount per gas to give to the validator as an incentive. */\n maxPriorityFeePerGas: Hex;\n};\n\n/** Gas fee estimates for a EIP-1559 transaction. */\nexport type FeeMarketGasFeeEstimates = {\n type: GasFeeEstimateType.FeeMarket;\n [GasFeeEstimateLevel.Low]: FeeMarketGasFeeEstimateForLevel;\n [GasFeeEstimateLevel.Medium]: FeeMarketGasFeeEstimateForLevel;\n [GasFeeEstimateLevel.High]: FeeMarketGasFeeEstimateForLevel;\n};\n\n/** Gas fee estimates for a legacy transaction. */\nexport type LegacyGasFeeEstimates = {\n type: GasFeeEstimateType.Legacy;\n [GasFeeEstimateLevel.Low]: Hex;\n [GasFeeEstimateLevel.Medium]: Hex;\n [GasFeeEstimateLevel.High]: Hex;\n};\n\n/** Gas fee estimates for a transaction retrieved with the eth_gasPrice method. */\nexport type GasPriceGasFeeEstimates = {\n type: GasFeeEstimateType.GasPrice;\n gasPrice: Hex;\n};\n\n/** Gas fee estimates for a transaction. */\nexport type GasFeeEstimates =\n | FeeMarketGasFeeEstimates\n | LegacyGasFeeEstimates\n | GasPriceGasFeeEstimates;\n\n/** Request to a gas fee flow to obtain gas fee estimates. */\nexport type GasFeeFlowRequest = {\n /** An EthQuery instance to enable queries to the associated RPC provider. */\n ethQuery: EthQuery;\n\n /** Gas fee controller data matching the chain ID of the transaction. */\n gasFeeControllerData: GasFeeState;\n\n /** The messenger instance. */\n messenger: TransactionControllerMessenger;\n\n /** The metadata of the transaction to obtain estimates for. */\n transactionMeta: TransactionMeta;\n};\n\n/** Response from a gas fee flow containing gas fee estimates. */\nexport type GasFeeFlowResponse = {\n /** The gas fee estimates for the transaction. */\n estimates: GasFeeEstimates;\n};\n\n/** A method of obtaining gas fee estimates for a specific transaction. */\nexport type GasFeeFlow = {\n /**\n * Determine if the gas fee flow supports the specified transaction.\n *\n * @param args - The arguments for the matcher function.\n * @param args.transactionMeta - The transaction metadata.\n * @param args.messenger - The messenger instance.\n * @returns Whether the gas fee flow supports the transaction.\n */\n matchesTransaction({\n transactionMeta,\n messenger,\n }: {\n transactionMeta: TransactionMeta;\n messenger: TransactionControllerMessenger;\n }): boolean;\n\n /**\n * Get gas fee estimates for a specific transaction.\n *\n * @param request - The gas fee flow request.\n * @returns The gas fee flow response containing the gas fee estimates.\n */\n getGasFees: (request: GasFeeFlowRequest) => Promise<GasFeeFlowResponse>;\n};\n\n/** Request to a layer 1 gas fee flow to obtain layer 1 fee estimate. */\nexport type Layer1GasFeeFlowRequest = {\n /** RPC Provider instance. */\n provider: Provider;\n\n /** The metadata of the transaction to obtain estimates for. */\n transactionMeta: TransactionMeta;\n};\n\n/** Response from a layer 1 gas fee flow containing layer 1 fee estimate. */\nexport type Layer1GasFeeFlowResponse = {\n /** The gas fee estimates for the transaction. */\n layer1Fee: Hex;\n};\n\n/** A method of obtaining layer 1 gas fee estimates for a specific transaction. */\nexport type Layer1GasFeeFlow = {\n /**\n * Determine if the gas fee flow supports the specified transaction.\n *\n * @param args - The arguments for the matcher function.\n * @param args.transactionMeta - The transaction metadata.\n * @param args.messenger - The messenger instance.\n * @returns A promise that resolves to whether the gas fee flow supports the transaction.\n */\n matchesTransaction({\n transactionMeta,\n messenger,\n }: {\n transactionMeta: TransactionMeta;\n messenger: TransactionControllerMessenger;\n }): Promise<boolean>;\n\n /**\n * Get layer 1 gas fee estimates for a specific transaction.\n *\n * @param request - The gas fee flow request.\n * @returns The gas fee flow response containing the layer 1 gas fee estimate.\n */\n getLayer1Fee: (\n request: Layer1GasFeeFlowRequest,\n ) => Promise<Layer1GasFeeFlowResponse>;\n};\n\n/** Simulation data concerning an update to a native or token balance. */\nexport type SimulationBalanceChange = {\n /** The balance before the transaction. */\n previousBalance: Hex;\n\n /** The balance after the transaction. */\n newBalance: Hex;\n\n /** The difference in balance. */\n difference: Hex;\n\n /** Whether the balance is increasing or decreasing. */\n isDecrease: boolean;\n};\n\n/** Token standards supported by simulation. */\nexport enum SimulationTokenStandard {\n erc20 = 'erc20',\n erc721 = 'erc721',\n erc1155 = 'erc1155',\n}\n\n/** Simulation data concerning an updated token. */\nexport type SimulationToken = {\n /** The token's contract address. */\n address: Hex;\n\n /** The standard of the token. */\n standard: SimulationTokenStandard;\n\n /** The ID of the token if supported by the standard. */\n id?: Hex;\n};\n\n/** Simulation data concerning a change to the a token balance. */\nexport type SimulationTokenBalanceChange = SimulationToken &\n SimulationBalanceChange;\n\nexport enum SimulationErrorCode {\n ChainNotSupported = 'chain-not-supported',\n Disabled = 'disabled',\n InvalidResponse = 'invalid-response',\n Reverted = 'reverted',\n}\n\n/** Error data for a failed simulation. */\nexport type SimulationError = {\n /** Error code to identify the error type. */\n code?: string | number;\n\n /** Error message to describe the error. */\n message?: string;\n};\n\n/** Simulation data for a transaction. */\nexport type SimulationData = {\n /** Error data if the simulation failed or the transaction reverted. */\n error?: SimulationError;\n\n /** Whether the simulation response changed after a security check triggered a re-simulation. */\n isUpdatedAfterSecurityCheck?: boolean;\n\n /** Data concerning a change to the user's native balance. */\n nativeBalanceChange?: SimulationBalanceChange;\n\n /** Data concerning a change to the user's token balances. */\n tokenBalanceChanges: SimulationTokenBalanceChange[];\n};\n\n/** Gas fee properties for a legacy transaction. */\nexport type GasPriceValue = {\n /** Price per gas for legacy transactions. */\n gasPrice: string;\n};\n\n/** Gas fee properties for an EIP-1559 transaction. */\nexport type FeeMarketEIP1559Values = {\n /** Maximum amount to pay per gas. */\n maxFeePerGas: string;\n\n /** Maximum amount per gas to give to the validator as an incentive. */\n maxPriorityFeePerGas: string;\n};\n\n/**\n * Data concerning a successfully submitted transaction.\n * Used for debugging purposes.\n */\nexport type SubmitHistoryEntry = {\n /** The chain ID of the transaction as a hexadecimal string. */\n chainId?: Hex;\n\n /** The hash of the transaction returned from the RPC provider. */\n hash: string;\n\n /** True if the entry was generated using the migration and existing transaction metadata. */\n migration?: boolean;\n\n /** The type of the network where the transaction was submitted. */\n networkType?: string;\n\n /**\n * The URL of the network the transaction was submitted to.\n * A single network URL if it was recorded when submitted.\n * An array of potential network URLs if it cannot be confirmed since the migration was used.\n */\n networkUrl?: string | string[];\n\n /** The origin of the transaction. */\n origin?: string;\n\n /** The raw transaction data that was submitted. */\n rawTransaction: string;\n\n /** When the transaction was submitted. */\n time: number;\n\n /** The transaction parameters that were submitted. */\n transaction: TransactionParams;\n};\n\nexport type InternalAccount = ReturnType<\n AccountsController['getSelectedAccount']\n>;\n\n/**\n * An authorization to be included in a `setCode` transaction.\n * Specifies code to be added to the authorization signer's EOA account.\n * Introduced in EIP-7702.\n */\nexport type Authorization = {\n /** Address of a smart contract that contains the code to be set. */\n address: Hex;\n\n /**\n * Specific chain the authorization applies to.\n * If not provided, defaults to the chain ID of the transaction.\n */\n chainId?: Hex;\n\n /**\n * Nonce at which the authorization will be valid.\n * If not provided, defaults to the nonce following the transaction's nonce.\n */\n nonce?: Hex;\n\n /** R component of the signature. */\n r?: Hex;\n\n /** S component of the signature. */\n s?: Hex;\n\n /** Y parity generated from the signature. */\n yParity?: Hex;\n};\n\n/**\n * An array of authorizations to be included in a `setCode` transaction.\n * Introduced in EIP-7702.\n */\nexport type AuthorizationList = Authorization[];\n\n/**\n * The parameters of a transaction within an atomic batch.\n */\nexport type BatchTransactionParams = {\n /** Data used to invoke a function on the target smart contract or EOA. */\n data?: Hex;\n\n /**\n * Maximum number of units of gas to use for the transaction.\n * Not supported in EIP-7702 batches.\n */\n gas?: Hex;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n * Not supported in EIP-7702 batches.\n */\n maxFeePerGas?: Hex;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n * Not supported in EIP-7702 batches.\n */\n maxPriorityFeePerGas?: Hex;\n\n /** Address of the target contract or EOA. */\n to?: Hex;\n\n /** Native balance to transfer with the transaction. */\n value?: Hex;\n};\n\n/** Metadata for a nested transaction within a standard transaction. */\nexport type NestedTransactionMetadata = BatchTransactionParams & {\n /** Type of the nested transaction. */\n type?: TransactionType;\n};\n\n/**\n * An additional transaction dynamically added to a standard single transaction to form a batch.\n */\nexport type BatchTransaction = BatchTransactionParams & {\n /**\n * Whether the transaction is executed after the main transaction.\n * Defaults to `true`.\n */\n isAfter?: boolean;\n\n /** Type of the batch transaction. */\n type?: TransactionType;\n};\n\n/**\n * Specification for a single transaction within a batch request.\n */\nexport type TransactionBatchSingleRequest = {\n /** The total fiat values of the transaction, to support client metrics. */\n assetsFiatValues?: AssetsFiatValues;\n\n /** Data if the transaction already exists. */\n existingTransaction?: {\n /** ID of the existing transaction. */\n id: string;\n\n /** Optional callback to be invoked once the transaction is published. */\n onPublish?: (request: {\n /** Updated signature for the transaction, if applicable. */\n newSignature?: Hex;\n\n /** Hash of the transaction on the network. */\n transactionHash?: string;\n }) => void;\n\n /** Signed transaction data. */\n signedTransaction: Hex;\n };\n\n /** Parameters of the single transaction. */\n params: BatchTransactionParams;\n\n /** Type of the transaction. */\n type?: TransactionType;\n};\n\n/**\n * Request to submit a batch of transactions.\n * Currently only atomic batches are supported via EIP-7702.\n */\nexport type TransactionBatchRequest = {\n batchId?: Hex;\n\n /** Whether to disable batch transaction processing via an EIP-7702 upgraded account. */\n disable7702?: boolean;\n\n /** Whether to disable batch transaction via the `publishBatch` hook. */\n disableHook?: boolean;\n\n /** Whether to disable batch transaction via sequential transactions. */\n disableSequential?: boolean;\n\n /** Address of the account to submit the transaction batch. */\n from: Hex;\n\n /** Address of an ERC-20 token to pay for the gas fee, if the user has insufficient native balance. */\n gasFeeToken?: Hex;\n\n /** Whether MetaMask will be compensated for the gas fee by the transaction. */\n isGasFeeIncluded?: boolean;\n\n /** Whether MetaMask will sponsor the gas fee for the transaction. */\n isGasFeeSponsored?: boolean;\n\n /** ID of the network client to submit the transaction. */\n networkClientId: NetworkClientId;\n\n /** Origin of the request, such as a dApp hostname or `ORIGIN_METAMASK` if internal. */\n origin?: string;\n\n /** Whether an approval request should be created to require confirmation from the user. */\n requireApproval?: boolean;\n\n /** Security alert ID to persist on the transaction. */\n securityAlertId?: string;\n\n /** Transactions to be submitted as part of the batch. */\n transactions: TransactionBatchSingleRequest[];\n\n /**\n * Whether to use the publish batch hook to submit the batch.\n * Defaults to false.\n *\n * @deprecated This is no longer used and will be removed in a future version.\n * Use `disableHook`, `disable7702` and `disableSequential`.\n */\n useHook?: boolean;\n\n /**\n * Callback to trigger security validation in the client.\n *\n * @param request - The JSON-RPC request to validate.\n * @param chainId - The chain ID of the transaction batch.\n */\n validateSecurity?: (\n request: ValidateSecurityRequest,\n chainId: Hex,\n ) => Promise<void>;\n};\n\n/**\n * Result from submitting a transaction batch.\n */\nexport type TransactionBatchResult = {\n /** ID of the batch to locate related transactions. */\n batchId: Hex;\n};\n\n/**\n * Request parameters for updating a custodial transaction.\n */\nexport type UpdateCustodialTransactionRequest = {\n /** The ID of the transaction to update. */\n transactionId: string;\n\n /** The error message to be assigned in case transaction status update to failed. */\n errorMessage?: string;\n\n /** The new hash value to be assigned. */\n hash?: string;\n\n /** The new status value to be assigned. */\n status?: TransactionStatus;\n\n /** The new gas limit value to be assigned. */\n gasLimit?: string;\n\n /** The new gas price value to be assigned. */\n gasPrice?: string;\n\n /** The new max fee per gas value to be assigned. */\n maxFeePerGas?: string;\n\n /** The new max priority fee per gas value to be assigned. */\n maxPriorityFeePerGas?: string;\n\n /** The new nonce value to be assigned. */\n nonce?: string;\n\n /** The new transaction type (hardfork) to be assigned. */\n type?: TransactionEnvelopeType;\n};\n\n/**\n * Data returned from custom logic to publish a transaction.\n */\nexport type PublishHookResult = {\n /**\n * The hash of the transaction on the network.\n */\n transactionHash?: string;\n};\n\n/**\n * Custom logic to publish a transaction.\n *\n * @param transactionMeta - The metadata of the transaction to publish.\n * @param signedTx - The signed transaction data to publish.\n * @returns The result of the publish operation.\n */\nexport type PublishHook = (\n transactionMeta: TransactionMeta,\n signedTx: string,\n) => Promise<PublishHookResult>;\n\n/** Single transaction in a publish batch hook request. */\nexport type PublishBatchHookTransaction = {\n /** ID of the transaction. */\n id?: string;\n\n /** Parameters of the nested transaction. */\n params: BatchTransactionParams;\n\n /** Signed transaction data to publish. */\n signedTx: Hex;\n};\n\n/**\n * Data required to call a publish batch hook.\n */\nexport type PublishBatchHookRequest = {\n /** Address of the account to submit the transaction batch. */\n from: Hex;\n\n /** ID of the network client associated with the transaction batch. */\n networkClientId: string;\n\n /** Nested transactions to be submitted as part of the batch. */\n transactions: PublishBatchHookTransaction[];\n};\n\n/** Result of calling a publish batch hook. */\nexport type PublishBatchHookResult =\n | {\n /** Result data for each transaction in the batch. */\n results: {\n /** Hash of the transaction on the network. */\n transactionHash: Hex;\n }[];\n }\n | undefined;\n\n/** Custom logic to publish a transaction batch. */\nexport type PublishBatchHook = (\n /** Data required to call the hook. */\n request: PublishBatchHookRequest,\n) => Promise<PublishBatchHookResult>;\n\n/**\n * Request to validate security of a transaction in the client.\n */\nexport type ValidateSecurityRequest = {\n /** JSON-RPC method to validate. */\n method: string;\n\n /** Parameters of the JSON-RPC method to validate. */\n params: unknown[];\n\n /** Optional EIP-7702 delegation to mock for the transaction sender. */\n delegationMock?: Hex;\n\n /** Origin of the request, such as a dApp hostname or `ORIGIN_METAMASK` if internal. */\n origin?: string;\n};\n\n/** Data required to pay for transaction gas using an ERC-20 token. */\nexport type GasFeeToken = {\n /** Amount needed for the gas fee. */\n amount: Hex;\n\n /** Current token balance of the sender. */\n balance: Hex;\n\n /** Decimals of the token. */\n decimals: number;\n\n /** Portion of the amount that is the fee paid to MetaMask. */\n fee?: Hex;\n\n /** Estimated gas limit required for original transaction. */\n gas: Hex;\n\n /** Estimated gas limit required for fee transfer. */\n gasTransfer?: Hex;\n\n /** The corresponding maxFeePerGas this token fee would equal. */\n maxFeePerGas: Hex;\n\n /** The corresponding maxPriorityFeePerGas this token fee would equal. */\n maxPriorityFeePerGas: Hex;\n\n /** Conversion rate of 1 token to native WEI. */\n rateWei: Hex;\n\n /** Account address to send the token to. */\n recipient: Hex;\n\n /** Symbol of the token. */\n symbol: string;\n\n /** Address of the token contract. */\n tokenAddress: Hex;\n};\n\n/** Request to check if atomic batch is supported for an account. */\nexport type IsAtomicBatchSupportedRequest = {\n /** Address of the account to check. */\n address: Hex;\n\n /**\n * IDs of specific chains to check.\n * If not provided, all supported chains will be checked.\n */\n chainIds?: Hex[];\n};\n\n/** Result of checking if atomic batch is supported for an account. */\nexport type IsAtomicBatchSupportedResult = IsAtomicBatchSupportedResultEntry[];\n\n/** Info about atomic batch support for a single chain. */\nexport type IsAtomicBatchSupportedResultEntry = {\n /** ID of the chain. */\n chainId: Hex;\n\n /** Address of the contract that the account was upgraded to. */\n delegationAddress?: Hex;\n\n /** Whether the upgraded contract is supported. */\n isSupported: boolean;\n\n /** Address of the contract that the account would be upgraded to. */\n upgradeContractAddress?: Hex;\n};\n\n/**\n * Custom logic to be executed after a transaction is added.\n * Can optionally update the transaction by returning the `updateTransaction` callback.\n */\nexport type AfterAddHook = (request: {\n transactionMeta: TransactionMeta;\n}) => Promise<{\n updateTransaction?: (transaction: TransactionMeta) => void;\n}>;\n\n/**\n * Custom logic to be executed after a transaction is simulated.\n * Can optionally update the transaction by returning the `updateTransaction` callback.\n */\nexport type AfterSimulateHook = (request: {\n transactionMeta: TransactionMeta;\n}) => Promise<\n | {\n skipSimulation?: boolean;\n updateTransaction?: (transaction: TransactionMeta) => void;\n }\n | undefined\n>;\n\n/**\n * Custom logic to be executed before a transaction is signed.\n * Can optionally update the transaction by returning the `updateTransaction` callback.\n */\nexport type BeforeSignHook = (request: {\n transactionMeta: TransactionMeta;\n}) => Promise<\n | {\n updateTransaction?: (transaction: TransactionMeta) => void;\n }\n | undefined\n>;\n\n/**\n * The total fiat values of the transaction, to support client metrics.\n */\nexport type AssetsFiatValues = {\n /**\n * The fiat value of the receiving assets.\n */\n receiving?: string;\n\n /**\n * The fiat value of the sending assets.\n */\n sending?: string;\n};\n\n/** Metadata specific to the MetaMask Pay feature. */\nexport type MetamaskPayMetadata = {\n /** Total fee from any bridge transactions, in fiat currency. */\n bridgeFeeFiat?: string;\n\n /** Chain ID of the payment token. */\n chainId?: Hex;\n\n /** Total network fee in fiat currency, including the original and bridge transactions. */\n networkFeeFiat?: string;\n\n /** Address of the payment token that the transaction funds were sourced from. */\n tokenAddress?: Hex;\n\n /** Total cost of the transaction in fiat currency, including gas, fees, and the funds themselves. */\n totalFiat?: string;\n};\n\n/**\n * Parameters for the transaction simulation API.\n */\nexport type GetSimulationConfig = (\n url: string,\n opts?: {\n txMeta?: TransactionMeta;\n },\n) => Promise<{\n newUrl?: string;\n authorization?: string;\n}>;\n\n/**\n * Options for adding a transaction.\n */\nexport type AddTransactionOptions = {\n /** Unique ID to prevent duplicate requests. */\n actionId?: string;\n\n /** Fiat values of the assets being sent and received. */\n assetsFiatValues?: AssetsFiatValues;\n\n /** Custom ID for the batch this transaction belongs to. */\n batchId?: Hex;\n\n /** Enum to indicate what device confirmed the transaction. */\n deviceConfirmedOn?: WalletDevice;\n\n /** Whether to disable the gas estimation buffer. */\n disableGasBuffer?: boolean;\n\n /** Address of an ERC-20 token to pay for the gas fee, if the user has insufficient native balance. */\n gasFeeToken?: Hex;\n\n /** Whether MetaMask will be compensated for the gas fee by the transaction. */\n isGasFeeIncluded?: boolean;\n\n /** Whether MetaMask will sponsor the gas fee for the transaction. */\n isGasFeeSponsored?: boolean;\n\n /** RPC method that requested the transaction. */\n method?: string;\n\n /** Params for any nested transactions encoded in the data. */\n nestedTransactions?: NestedTransactionMetadata[];\n\n /** ID of the network client for this transaction. */\n networkClientId: NetworkClientId;\n\n /** Origin of the transaction request, such as a dApp hostname. */\n origin?: string;\n\n /** Custom logic to publish the transaction. */\n publishHook?: PublishHook;\n\n /** Whether the transaction requires approval by the user, defaults to true unless explicitly disabled. */\n requireApproval?: boolean | undefined;\n\n /** Response from security validator. */\n securityAlertResponse?: SecurityAlertResponse;\n\n /** Entries to add to the `sendFlowHistory`. */\n sendFlowHistory?: SendFlowHistoryEntry[];\n\n /** Options for swaps transactions. */\n swaps?: {\n /** Whether the transaction has an approval transaction. */\n hasApproveTx?: boolean;\n\n /** Metadata for swap transaction. */\n meta?: Partial<TransactionMeta>;\n };\n\n /** Parent context for any new traces. */\n traceContext?: unknown;\n\n /** Type of transaction to add, such as 'cancel' or 'swap'. */\n type?: TransactionType;\n};\n\n/**\n * Request to get gas fee tokens.\n */\nexport type GetGasFeeTokensRequest = {\n /** ID of the chain. */\n chainId: Hex;\n\n /** Data of the transaction. */\n data?: Hex;\n\n /** Address of the sender. */\n from: Hex;\n\n /** Address of the recipient. */\n to: Hex;\n\n /** Value of the transaction. */\n value?: Hex;\n};\n"]}
1
+ {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/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AY,YAAY;IACtB,iCAAiB,CAAA;IACjB,gDAAgC,CAAA;IAChC,iCAAiB,CAAA;AACnB,CAAC,EAJW,YAAY,KAAZ,YAAY,QAIvB;AA8ED,oFAAoF;AACpF,MAAM,CAAN,IAAY,mBAIX;AAJD,WAAY,mBAAmB;IAC7B,kCAAW,CAAA;IACX,wCAAiB,CAAA;IACjB,oCAAa,CAAA;AACf,CAAC,EAJW,mBAAmB,KAAnB,mBAAmB,QAI9B;AAED,0DAA0D;AAC1D,MAAM,CAAN,IAAY,kBAIX;AAJD,WAAY,kBAAkB;IAC5B,8CAAwB,CAAA;IACxB,uCAAiB,CAAA;IACjB,+CAAyB,CAAA;AAC3B,CAAC,EAJW,kBAAkB,KAAlB,kBAAkB,QAI7B;AAkJD,+CAA+C;AAC/C,MAAM,CAAN,IAAY,uBAIX;AAJD,WAAY,uBAAuB;IACjC,0CAAe,CAAA;IACf,4CAAiB,CAAA;IACjB,8CAAmB,CAAA;AACrB,CAAC,EAJW,uBAAuB,KAAvB,uBAAuB,QAIlC;AAkBD,MAAM,CAAN,IAAY,mBAKX;AALD,WAAY,mBAAmB;IAC7B,gEAAyC,CAAA;IACzC,4CAAqB,CAAA;IACrB,2DAAoC,CAAA;IACpC,4CAAqB,CAAA;AACvB,CAAC,EALW,mBAAmB,KAAnB,mBAAmB,QAK9B","sourcesContent":["import type { AccessList } from '@ethereumjs/tx';\nimport type { AccountsController } from '@metamask/accounts-controller';\nimport type EthQuery from '@metamask/eth-query';\nimport type { GasFeeState } from '@metamask/gas-fee-controller';\nimport type { NetworkClientId, Provider } from '@metamask/network-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Operation } from 'fast-json-patch';\n\nimport type { TransactionControllerMessenger } from './TransactionController';\n\n/**\n * Given a record, ensures that each property matches the `Json` type.\n */\ntype MakeJsonCompatible<T> = T extends Json\n ? T\n : {\n [K in keyof T]: T[K] extends Json ? T[K] : never;\n };\n\n/**\n * `Json` from `@metamask/utils` is defined as a recursive type alias, but\n * `Operation` is defined as an interface, and the two are not compatible with\n * each other. Therefore, this is a variant of Operation from `fast-json-patch`\n * which is guaranteed to be type-compatible with `Json`.\n */\ntype JsonCompatibleOperation = MakeJsonCompatible<Operation>;\n\n/**\n * Information about a single transaction such as status and block number.\n */\nexport type TransactionMeta = {\n /**\n * ID of the transaction that approved the swap token transfer.\n */\n approvalTxId?: string;\n\n /**\n * The fiat value of the transaction to be used to passed metrics.\n */\n assetsFiatValues?: AssetsFiatValues;\n\n /**\n * Unique ID to prevent duplicate requests.\n */\n actionId?: string;\n\n /**\n * Base fee of the block as a hex value, introduced in EIP-1559.\n */\n baseFeePerGas?: Hex;\n\n /**\n * ID of the associated transaction batch.\n */\n batchId?: Hex;\n\n /**\n * Additional transactions that must also be submitted in a batch.\n */\n batchTransactions?: BatchTransaction[];\n\n /**\n * Optional configuration when processing `batchTransactions`.\n */\n batchTransactionsOptions?: {\n /**\n * Whether to disable batch transaction processing via an EIP-7702 upgraded account.\n * Defaults to `true` if no options object, `false` otherwise.\n */\n disable7702?: boolean;\n\n /**\n * Whether to disable batch transaction via the `publishBatch` hook.\n * Defaults to `false`.\n */\n disableHook?: boolean;\n\n /**\n * Whether to disable batch transaction via sequential transactions.\n * Defaults to `true` if no options object, `false` otherwise.\n */\n disableSequential?: boolean;\n };\n\n /**\n * Number of the block where the transaction has been included.\n */\n blockNumber?: string;\n\n /**\n * The timestamp for when the block was collated.\n */\n blockTimestamp?: string;\n\n /**\n * Network code as per EIP-155 for this transaction.\n */\n chainId: Hex;\n\n /**\n * List of container types applied to the original transaction data.\n * For example, through delegations.\n */\n containerTypes?: TransactionContainerType[];\n\n /**\n * A string representing a name of transaction contract method.\n */\n contractMethodName?: string;\n\n /**\n * The balance of the token that is being sent.\n */\n currentTokenBalance?: string;\n\n /** The optional custom nonce override as a decimal string. */\n customNonceValue?: string;\n\n /**\n * The custom token amount is the amount set by the user.\n */\n customTokenAmount?: string;\n\n /**\n * The dapp proposed token amount.\n */\n dappProposedTokenAmount?: string;\n\n /**\n * Gas values provided by the dApp.\n */\n dappSuggestedGasFees?: DappSuggestedGasFees;\n\n /**\n * The initial gas values set when the transaction was first created.\n */\n defaultGasEstimates?: DefaultGasEstimates;\n\n /**\n * Address of the sender's current contract code delegation.\n * Introduced in EIP-7702.\n */\n delegationAddress?: Hex;\n\n /**\n * String to indicate what device the transaction was confirmed on.\n */\n deviceConfirmedOn?: WalletDevice;\n\n /**\n * The Network ID as per EIP-155 of the destination chain of a bridge transaction.\n */\n destinationChainId?: Hex;\n\n /**\n * The address of the token being received of swap transaction.\n */\n destinationTokenAddress?: string;\n\n /**\n * The raw amount of the destination token\n */\n destinationTokenAmount?: string;\n\n /**\n * The decimals of the token being received of swap transaction.\n */\n destinationTokenDecimals?: number;\n\n /**\n * The symbol of the token being received with swap.\n */\n destinationTokenSymbol?: string;\n\n /**\n * Whether to disable the buffer added to gas limit estimations.\n * Defaults to adding the buffer.\n */\n disableGasBuffer?: boolean;\n\n /**\n * Error that occurred during the transaction processing.\n */\n error?: TransactionError;\n\n /**\n * The estimated base fee of the transaction.\n */\n estimatedBaseFee?: string;\n\n /**\n * Which estimate level that the API suggested.\n */\n estimateSuggested?: string;\n\n /**\n * Which estimate level was used\n */\n estimateUsed?: string;\n\n /**\n * The chosen amount which will be the same as the originally proposed token\n * amount if the user does not edit the amount or will be a custom token\n * amount set by the user.\n */\n finalApprovalAmount?: string;\n\n /**\n * The number of the latest block when the transaction submit was first retried.\n */\n firstRetryBlockNumber?: string;\n\n /** Available tokens that can be used to pay for gas. */\n gasFeeTokens?: GasFeeToken[];\n\n /**\n * Whether the transaction is active.\n */\n isActive?: boolean;\n\n /**\n * Whether the transaction is the first time interaction.\n */\n isFirstTimeInteraction?: boolean;\n\n /**\n * Whether the transaction is sponsored meaning the user does not pay the gas fee.\n */\n isGasFeeSponsored?: boolean;\n\n /** Alternate EIP-1559 gas fee estimates for multiple priority levels. */\n gasFeeEstimates?: GasFeeEstimates;\n\n /** Whether the gas fee estimates have been checked at least once. */\n gasFeeEstimatesLoaded?: boolean;\n\n /**\n * The estimated gas for the transaction without any buffer applied.\n */\n gasLimitNoBuffer?: string;\n\n /**\n * The estimated gas used by the transaction, after any refunds. Generated from transaction simulation.\n */\n gasUsed?: Hex;\n\n /**\n * A hex string of the transaction hash, used to identify the transaction on the network.\n */\n hash?: string;\n\n /**\n * A history of mutations to TransactionMeta.\n */\n history?: TransactionHistory;\n\n /**\n * Generated UUID associated with this transaction.\n */\n id: string;\n\n /**\n * Whether the transaction is signed externally.\n * No signing will be performed in the client and the `nonce` will be `undefined`.\n */\n isExternalSign?: boolean;\n\n /** Whether MetaMask will be compensated for the gas fee by the transaction. */\n isGasFeeIncluded?: boolean;\n\n /** Whether the `selectedGasFeeToken` is only used if the user has insufficient native balance. */\n isGasFeeTokenIgnoredIfBalance?: boolean;\n\n /** Whether the intent of the transaction was achieved via an alternate route or chain. */\n isIntentComplete?: boolean;\n\n /**\n * Whether the transaction is an incoming token transfer.\n */\n isTransfer?: boolean;\n\n /**\n * Whether the transaction entry is generated from a user operation.\n */\n isUserOperation?: boolean;\n\n /**\n * Additional gas fees to cover the cost of persisting data on layer 1 for layer 2 networks.\n */\n layer1GasFee?: Hex;\n\n /**\n * Data for any nested transactions.\n * For example, in an atomic batch transaction via EIP-7702.\n */\n nestedTransactions?: NestedTransactionMetadata[];\n\n /**\n * The ID of the network client used by the transaction.\n */\n networkClientId: NetworkClientId;\n\n /**\n * Network code as per EIP-155 for this transaction\n *\n * @deprecated Use `chainId` instead.\n */\n readonly networkID?: string;\n\n /**\n * Origin this transaction was sent from.\n */\n origin?: string;\n\n /**\n * The original dapp proposed token approval amount before edit by user.\n */\n originalApprovalAmount?: string;\n\n /**\n * The original gas estimation of the transaction.\n */\n originalGasEstimate?: string;\n\n /**\n * When we speed up a transaction, we set the type as Retry and we lose\n * information about type of transaction that is being set up, so we use\n * original type to track that information.\n */\n originalType?: TransactionType;\n\n /** Metadata specific to the MetaMask Pay feature. */\n metamaskPay?: MetamaskPayMetadata;\n\n /**\n * Account transaction balance after swap.\n */\n postTxBalance?: string;\n\n /**\n * Account transaction balance before swap.\n */\n preTxBalance?: string;\n\n /**\n * The previous gas properties before they were updated.\n */\n previousGas?: {\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gasLimit?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n };\n\n /**\n * The transaction's 'r' value as a hex string.\n */\n r?: string;\n\n /**\n * Hex representation of the underlying transaction.\n */\n rawTx?: string;\n\n /**\n * When the transaction is dropped, this is the replacement transaction hash.\n */\n replacedBy?: string;\n\n /**\n * When the transaction is dropped, this is the replacement transaction ID.\n */\n replacedById?: string;\n\n /**\n * IDs of any transactions that must be confirmed before this one is submitted.\n * Unlike a transaction batch, these transactions can be on alternate chains.\n */\n requiredTransactionIds?: string[];\n\n /**\n * The number of times that the transaction submit has been retried.\n */\n retryCount?: number;\n\n /**\n * The transaction's 's' value as a hex string.\n */\n s?: string;\n\n /**\n * Response from security validator.\n */\n securityAlertResponse?: SecurityAlertResponse;\n\n /**\n * Response from security provider.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n securityProviderResponse?: Record<string, any>;\n\n /**\n * The token address of the selected gas fee token.\n * Corresponds to the `gasFeeTokens` property.\n */\n selectedGasFeeToken?: Hex;\n\n /**\n * An array of entries that describe the user's journey through the send flow.\n * This is purely attached to state logs for troubleshooting and support.\n */\n sendFlowHistory?: SendFlowHistoryEntry[];\n\n /**\n * Simulation data for the transaction used to predict its outcome.\n */\n simulationData?: SimulationData;\n\n /**\n * If the gas estimation fails, an object containing error and block information.\n */\n simulationFails?: {\n reason?: string;\n errorKey?: string;\n debug: {\n blockNumber?: string;\n blockGasLimit?: string;\n };\n };\n\n /** Current status of the transaction. */\n status: TransactionStatus;\n\n /**\n * The time the transaction was submitted to the network, in Unix epoch time (ms).\n */\n submittedTime?: number;\n\n /**\n * The address of the token being swapped\n */\n sourceTokenAddress?: string;\n\n /**\n * The raw amount of the source swap token\n */\n sourceTokenAmount?: string;\n\n /**\n * The decimals of the token being swapped.\n */\n sourceTokenDecimals?: number;\n\n /**\n * The symbol of the token being swapped.\n */\n sourceTokenSymbol?: string;\n\n /**\n * The address of the swap recipient.\n */\n swapAndSendRecipient?: string;\n\n /**\n * The metadata of the swap transaction.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapMetaData?: Record<string, any>;\n\n /**\n * The value of the token being swapped.\n */\n swapTokenValue?: string;\n\n /**\n * Timestamp associated with this transaction.\n */\n time: number;\n\n /**\n * Whether transaction recipient is a smart contract.\n */\n toSmartContract?: boolean;\n\n /**\n * Additional transfer information.\n */\n transferInformation?: {\n amount?: string;\n contractAddress: string;\n decimals: number;\n symbol: string;\n };\n\n /**\n * Underlying Transaction object.\n */\n txParams: TransactionParams;\n\n /**\n * Initial transaction parameters before `afterAdd` hook was invoked.\n */\n txParamsOriginal?: TransactionParams;\n\n /**\n * Transaction receipt.\n */\n txReceipt?: TransactionReceipt;\n\n /**\n * The type of transaction such as `cancel` or `swap`.\n */\n type?: TransactionType;\n\n /**\n * The gas limit supplied by user.\n */\n userEditedGasLimit?: boolean;\n\n /**\n * Estimate level user selected.\n */\n userFeeLevel?: string;\n\n /**\n * The transaction's 'v' value as a hex string.\n */\n v?: string;\n\n /**\n * Whether the transaction is verified on the blockchain.\n */\n verifiedOnBlockchain?: boolean;\n\n /**\n * Warning information for the transaction.\n */\n warning?: {\n error: string;\n message: string;\n };\n};\n\n/**\n * Information about a batch transaction.\n */\nexport type TransactionBatchMeta = {\n /**\n * Network code as per EIP-155 for this transaction.\n */\n chainId: Hex;\n\n /**\n * Address to send this transaction from.\n */\n from: string;\n\n /** Alternate EIP-1559 gas fee estimates for multiple priority levels. */\n gasFeeEstimates?: GasFeeEstimates;\n\n /**\n * Maximum number of units of gas to use for this transaction batch.\n */\n gas?: string;\n\n /**\n * ID of the associated transaction batch.\n */\n id: string;\n\n /**\n * The ID of the network client used by the transaction.\n */\n networkClientId: NetworkClientId;\n\n /**\n * Origin this transaction was sent from.\n */\n origin?: string;\n\n /** Current status of the transaction. */\n status: TransactionStatus;\n\n /**\n * Data for any EIP-7702 transactions.\n */\n transactions?: NestedTransactionMetadata[];\n};\n\nexport type SendFlowHistoryEntry = {\n /**\n * String to indicate user interaction information.\n */\n entry: string;\n\n /**\n * Timestamp associated with this entry.\n */\n timestamp: number;\n};\n\n/**\n * Represents the status of a transaction within the wallet.\n * Each status reflects the state of the transaction internally,\n * with some statuses corresponding to the transaction's state on the network.\n *\n * The typical transaction lifecycle follows this state machine:\n * unapproved -> approved -> signed -> submitted -> FINAL_STATE\n * where FINAL_STATE is one of: confirmed, failed, dropped, or rejected.\n */\nexport enum TransactionStatus {\n /**\n * The initial state of a transaction before user approval.\n */\n unapproved = 'unapproved',\n\n /**\n * The transaction has been approved by the user but is not yet signed.\n * This status is usually brief but may be longer for scenarios like hardware wallet usage.\n */\n approved = 'approved',\n\n /**\n * The transaction is signed and in the process of being submitted to the network.\n * This status is typically short-lived but can be longer for certain cases, such as smart transactions.\n */\n signed = 'signed',\n\n /**\n * The transaction has been submitted to the network and is awaiting confirmation.\n */\n submitted = 'submitted',\n\n /**\n * The transaction has been successfully executed and confirmed on the blockchain.\n * This is a final state.\n */\n confirmed = 'confirmed',\n\n /**\n * The transaction encountered an error during execution on the blockchain and failed.\n * This is a final state.\n */\n failed = 'failed',\n\n /**\n * The transaction was superseded by another transaction, resulting in its dismissal.\n * This is a final state.\n */\n dropped = 'dropped',\n\n /**\n * The transaction was rejected by the user and not processed further.\n * This is a final state.\n */\n rejected = 'rejected',\n\n /**\n * @deprecated This status is no longer used.\n */\n cancelled = 'cancelled',\n}\n\n/**\n * Options for wallet device.\n */\nexport enum WalletDevice {\n MM_MOBILE = 'metamask_mobile',\n MM_EXTENSION = 'metamask_extension',\n OTHER = 'other_device',\n}\n\n/**\n * The type of the transaction.\n */\nexport enum TransactionType {\n /**\n * A batch transaction that includes multiple nested transactions.\n * Introduced in EIP-7702.\n */\n batch = 'batch',\n\n /**\n * A transaction that bridges tokens to a different chain through Metamask Bridge.\n */\n bridge = 'bridge',\n\n /**\n * Similar to the approve type, a bridge approval is a special case of ERC20\n * approve method that requests an allowance of the token to spend on behalf\n * of the user for the MetaMask Bridge contract. The first bridge for any token\n * will have an accompanying bridgeApproval transaction.\n */\n bridgeApproval = 'bridgeApproval',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n cancel = 'cancel',\n\n /**\n * A transaction that is interacting with a smart contract's methods that we\n * have not treated as a special case, such as approve, transfer, and\n * transferfrom.\n */\n contractInteraction = 'contractInteraction',\n\n /**\n * A transaction that deployed a smart contract.\n */\n deployContract = 'contractDeployment',\n\n /**\n * A transaction for Ethereum decryption.\n */\n ethDecrypt = 'eth_decrypt',\n\n /**\n * A transaction for getting an encryption public key.\n */\n ethGetEncryptionPublicKey = 'eth_getEncryptionPublicKey',\n\n /**\n * Transaction is a token or native transfer to MetaMask to pay for gas fees.\n */\n gasPayment = 'gas_payment',\n\n /**\n * An incoming (deposit) transaction.\n */\n incoming = 'incoming',\n\n /**\n * A transaction that deposits tokens into a lending contract.\n */\n lendingDeposit = 'lendingDeposit',\n\n /**\n * A transaction that withdraws tokens from a lending contract.\n */\n lendingWithdraw = 'lendingWithdraw',\n\n /**\n * A transaction that converts tokens to mUSD.\n */\n musdConversion = 'musdConversion',\n\n /**\n * Deposit funds to be available for trading via Perps.\n */\n perpsDeposit = 'perpsDeposit',\n\n /**\n * A transaction for personal sign.\n */\n personalSign = 'personal_sign',\n\n /**\n * Buy a position via Predict.\n *\n * @deprecated Not used.\n */\n predictBuy = 'predictBuy',\n\n /**\n * Claim winnings from a position via Predict.\n */\n predictClaim = 'predictClaim',\n\n /**\n * Deposit funds to be available for use via Predict.\n */\n predictDeposit = 'predictDeposit',\n\n /**\n * Sell a position via Predict.\n *\n * @deprecated Not used.\n */\n predictSell = 'predictSell',\n\n /**\n * Withdraw funds from Predict.\n */\n predictWithdraw = 'predictWithdraw',\n\n /**\n * When a transaction is failed it can be retried by\n * resubmitting the same transaction with a higher gas fee. This type is also used\n * to speed up pending transactions. This is accomplished by creating a new tx with\n * the same nonce and higher gas fees.\n */\n retry = 'retry',\n\n /**\n * Remove the code / delegation from an upgraded EOA.\n * Introduced in EIP-7702.\n */\n revokeDelegation = 'revokeDelegation',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n simpleSend = 'simpleSend',\n\n /**\n * A transaction that is signing typed data.\n */\n signTypedData = 'eth_signTypedData',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n smart = 'smart',\n\n /**\n * A transaction that claims staking rewards.\n */\n stakingClaim = 'stakingClaim',\n\n /**\n * A transaction that deposits tokens into a staking contract.\n */\n stakingDeposit = 'stakingDeposit',\n\n /**\n * A transaction that unstakes tokens from a staking contract.\n */\n stakingUnstake = 'stakingUnstake',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps.\n */\n swap = 'swap',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps, then sending the swapped token to a recipient.\n */\n swapAndSend = 'swapAndSend',\n\n /**\n * Similar to the approve type, a swap approval is a special case of ERC20\n * approve method that requests an allowance of the token to spend on behalf\n * of the user for the MetaMask Swaps contract. The first swap for any token\n * will have an accompanying swapApproval transaction.\n */\n swapApproval = 'swapApproval',\n\n /**\n * A token transaction requesting an allowance of the token to spend on\n * behalf of the user.\n */\n tokenMethodApprove = 'approve',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. The method is prefixed with safe because when calling\n * this method the contract checks to ensure that the receiver is an address\n * capable of handling the token being sent.\n */\n tokenMethodSafeTransferFrom = 'safetransferfrom',\n\n /**\n * A token transaction where the user is sending tokens that they own to\n * another address.\n */\n tokenMethodTransfer = 'transfer',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. For more information on allowances, see the approve\n * type.\n */\n tokenMethodTransferFrom = 'transferfrom',\n\n /**\n * A token transaction requesting an allowance of all of a user's tokens to\n * spend on behalf of the user.\n */\n tokenMethodSetApprovalForAll = 'setapprovalforall',\n\n /**\n * Increase the allowance by a given increment\n */\n tokenMethodIncreaseAllowance = 'increaseAllowance',\n\n /**\n * A token approval transaction subscribing to the shield insurance service\n */\n shieldSubscriptionApprove = 'shieldSubscriptionApprove',\n}\n\nexport enum TransactionContainerType {\n /** Transaction has been converted to a delegation including caveats to validate the simulated balance changes. */\n EnforcedSimulations = 'enforcedSimulations',\n}\n\n/**\n * Standard data concerning a transaction to be processed by the blockchain.\n */\nexport type TransactionParams = {\n /**\n * A list of addresses and storage keys that the transaction plans to access.\n */\n accessList?: AccessList;\n\n /**\n * Array of authorizations to set code on EOA accounts.\n * Only supported in `setCode` transactions.\n * Introduced in EIP-7702.\n */\n authorizationList?: AuthorizationList;\n\n /**\n * Network ID as per EIP-155.\n *\n * @deprecated Ignored.\n * Use `networkClientId` when calling `addTransaction`.\n */\n chainId?: Hex;\n\n /**\n * Data to pass with this transaction.\n */\n data?: string;\n\n /**\n * Error message for gas estimation failure.\n */\n estimateGasError?: string;\n\n /**\n * Estimated base fee for this transaction.\n */\n estimatedBaseFee?: string;\n\n /**\n * Which estimate level that the API suggested.\n */\n estimateSuggested?: string;\n\n /**\n * Which estimate level was used\n */\n estimateUsed?: string;\n\n /**\n * Address to send this transaction from.\n */\n from: string;\n\n /**\n * Maximum number of units of gas to use for this transaction.\n */\n gas?: string;\n\n /**\n * Maximum number of units of gas to use for this transaction.\n *\n * @deprecated Use `gas` instead.\n */\n gasLimit?: string;\n\n /**\n * Price per gas for legacy txs\n */\n gasPrice?: string;\n\n /**\n * Gas used in the transaction.\n */\n gasUsed?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority\n * fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n\n /**\n * Unique number to prevent replay attacks.\n */\n nonce?: string;\n\n /**\n * Address to send this transaction to.\n */\n to?: string;\n\n /**\n * Value associated with this transaction.\n */\n value?: string;\n\n /**\n * Type of transaction.\n * 0x0 indicates a legacy transaction.\n */\n type?: string;\n};\n\n/**\n * Standard data concerning a transaction processed by the blockchain.\n */\nexport type TransactionReceipt = {\n /**\n * The block hash of the block that this transaction was included in.\n */\n blockHash?: string;\n\n /**\n * The block number of the block that this transaction was included in.\n */\n blockNumber?: string;\n\n /**\n * Effective gas price the transaction was charged at.\n */\n effectiveGasPrice?: string;\n\n /**\n * Gas used in the transaction.\n */\n gasUsed?: string;\n\n /**\n * Total used gas in hex.\n */\n l1Fee?: string;\n\n /**\n * All the logs emitted by this transaction.\n */\n logs?: Log[];\n\n /**\n * The status of the transaction.\n */\n status?: string;\n\n /** Hash of the associated transaction. */\n transactionHash?: Hex;\n\n /**\n * The hexadecimal index of this transaction in the list of transactions included in the block this transaction was mined in.\n */\n transactionIndex?: string;\n};\n\n/**\n * Represents an event that has been included in a transaction using the EVM `LOG` opcode.\n */\nexport type Log = {\n /**\n * Address of the contract that generated log.\n */\n address?: string;\n\n /** Data for the log. */\n data?: Hex;\n\n /**\n * List of topics for log.\n */\n topics?: string;\n};\n\n/**\n * The configuration required to fetch transaction data from a RemoteTransactionSource.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface RemoteTransactionSourceRequest {\n /**\n * The address of the account to fetch transactions for.\n */\n address: Hex;\n\n /**\n * Whether to also include incoming token transfers.\n */\n includeTokenTransfers: boolean;\n\n /**\n * Additional tags to identify the source of the request.\n */\n tags?: string[];\n\n /**\n * Whether to also retrieve outgoing transactions.\n */\n updateTransactions: boolean;\n}\n\n/**\n * An object capable of fetching transaction data from a remote source.\n * Used by the IncomingTransactionHelper to retrieve remote transaction data.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface RemoteTransactionSource {\n /**\n * @returns Array of chain IDs supported by the remote source.\n */\n getSupportedChains: () => Hex[];\n\n /**\n * @param request - A request object containing data such as the address and chain ID.\n * @returns An array of transaction metadata for the retrieved transactions.\n */\n fetchTransactions: (\n request: RemoteTransactionSourceRequest,\n ) => Promise<TransactionMeta[]>;\n}\n\n/**\n * Gas values initially suggested by the dApp.\n */\nexport type DappSuggestedGasFees = {\n gas?: string;\n gasPrice?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Gas values saved by the user for a specific chain.\n */\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SavedGasFees {\n maxBaseFee: string;\n priorityFee: string;\n}\n\n/**\n * A transaction history operation that includes a note and timestamp.\n */\ntype ExtendedHistoryOperation = JsonCompatibleOperation & {\n note?: string;\n timestamp?: number;\n};\n\n/**\n * A transaction history entry that includes the ExtendedHistoryOperation as the first element.\n */\nexport type TransactionHistoryEntry = [\n ExtendedHistoryOperation,\n ...JsonCompatibleOperation[],\n];\n\n/**\n * A transaction history that includes the transaction meta as the first element.\n * And the rest of the elements are the operation arrays that were applied to the transaction meta.\n */\nexport type TransactionHistory = [\n TransactionMeta,\n ...TransactionHistoryEntry[],\n];\n\n/**\n * Result of inferring the transaction type.\n */\nexport type InferTransactionTypeResult = {\n /**\n * The contract code, in hex format if it exists. '0x0' or\n * '0x' are also indicators of non-existent contract code.\n */\n getCodeResponse?: string | null;\n\n /**\n * The type of transaction\n */\n type: TransactionType;\n};\n\n/**\n * A function for verifying a transaction, whether it is malicious or not.\n */\nexport type SecurityProviderRequest = (\n requestData: TransactionMeta,\n messageType: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\n/**\n * Specifies the shape of the base transaction parameters.\n * Added in EIP-2718.\n */\nexport enum TransactionEnvelopeType {\n /**\n * A legacy transaction, the very first type.\n */\n legacy = '0x0',\n\n /**\n * EIP-2930 defined the access list transaction type that allowed for\n * specifying the state that a transaction would act upon in advance and\n * theoretically save on gas fees.\n */\n accessList = '0x1',\n\n /**\n * The type introduced comes from EIP-1559, Fee Market describes the addition\n * of a baseFee to blocks that will be burned instead of distributed to\n * miners. Transactions of this type have both a maxFeePerGas (maximum total\n * amount in gwei per gas to spend on the transaction) which is inclusive of\n * the maxPriorityFeePerGas (maximum amount of gwei per gas from the\n * transaction fee to distribute to miner).\n */\n feeMarket = '0x2',\n\n /**\n * Adds code to externally owned accounts according to the signed authorizations\n * in the new `authorizationList` parameter.\n * Introduced in EIP-7702.\n */\n setCode = '0x4',\n}\n\n/**\n * The source of the gas fee parameters on a transaction.\n */\nexport enum UserFeeLevel {\n CUSTOM = 'custom',\n DAPP_SUGGESTED = 'dappSuggested',\n MEDIUM = 'medium',\n}\n\n/**\n * Initial gas values set when the transaction was first created.\n */\nexport type DefaultGasEstimates = {\n /**\n * Source of the gas fee values, such as `dappSuggested` or `medium`.\n */\n estimateType?: string;\n\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gas?: string;\n\n /**\n * Price per gas for legacy transactions.\n */\n gasPrice?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Data concerning an error while processing a transaction.\n */\nexport type TransactionError = {\n /**\n * A descriptive error name.\n */\n name: string;\n\n /**\n * A descriptive error message providing details about the encountered error.\n */\n message: string;\n\n /**\n * The stack trace associated with the error, if available.\n */\n stack?: string;\n\n /**\n * An optional error code associated with the error.\n */\n code?: string;\n\n /**\n * The rpc property holds additional information related to the error.\n */\n // We are intentionally using `any` here instead of `Json` because it causes\n // `WritableDraft<TransactionMeta>` from Immer to cause TypeScript to error\n // with \"Type instantiation is excessively deep and possibly infinite\". See:\n // <https://github.com/immerjs/immer/issues/839>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc?: any;\n};\n\n/**\n * Type for security alert response from transaction validator.\n */\nexport type SecurityAlertResponse = {\n features?: string[];\n providerRequestsCount?: Record<string, number>;\n reason: string;\n result_type: string;\n securityAlertId?: string;\n};\n\n/** Alternate priority levels for which values are provided in gas fee estimates. */\nexport enum GasFeeEstimateLevel {\n Low = 'low',\n Medium = 'medium',\n High = 'high',\n}\n\n/** Type of gas fee estimate generated by a GasFeeFlow. */\nexport enum GasFeeEstimateType {\n FeeMarket = 'fee-market',\n Legacy = 'legacy',\n GasPrice = 'eth_gasPrice',\n}\n\n/** Gas fee estimates for a specific priority level. */\nexport type FeeMarketGasFeeEstimateForLevel = {\n /** Maximum amount to pay per gas. */\n maxFeePerGas: Hex;\n\n /** Maximum amount per gas to give to the validator as an incentive. */\n maxPriorityFeePerGas: Hex;\n};\n\n/** Gas fee estimates for a EIP-1559 transaction. */\nexport type FeeMarketGasFeeEstimates = {\n type: GasFeeEstimateType.FeeMarket;\n [GasFeeEstimateLevel.Low]: FeeMarketGasFeeEstimateForLevel;\n [GasFeeEstimateLevel.Medium]: FeeMarketGasFeeEstimateForLevel;\n [GasFeeEstimateLevel.High]: FeeMarketGasFeeEstimateForLevel;\n};\n\n/** Gas fee estimates for a legacy transaction. */\nexport type LegacyGasFeeEstimates = {\n type: GasFeeEstimateType.Legacy;\n [GasFeeEstimateLevel.Low]: Hex;\n [GasFeeEstimateLevel.Medium]: Hex;\n [GasFeeEstimateLevel.High]: Hex;\n};\n\n/** Gas fee estimates for a transaction retrieved with the eth_gasPrice method. */\nexport type GasPriceGasFeeEstimates = {\n type: GasFeeEstimateType.GasPrice;\n gasPrice: Hex;\n};\n\n/** Gas fee estimates for a transaction. */\nexport type GasFeeEstimates =\n | FeeMarketGasFeeEstimates\n | LegacyGasFeeEstimates\n | GasPriceGasFeeEstimates;\n\n/** Request to a gas fee flow to obtain gas fee estimates. */\nexport type GasFeeFlowRequest = {\n /** An EthQuery instance to enable queries to the associated RPC provider. */\n ethQuery: EthQuery;\n\n /** Gas fee controller data matching the chain ID of the transaction. */\n gasFeeControllerData: GasFeeState;\n\n /** The messenger instance. */\n messenger: TransactionControllerMessenger;\n\n /** The metadata of the transaction to obtain estimates for. */\n transactionMeta: TransactionMeta;\n};\n\n/** Response from a gas fee flow containing gas fee estimates. */\nexport type GasFeeFlowResponse = {\n /** The gas fee estimates for the transaction. */\n estimates: GasFeeEstimates;\n};\n\n/** A method of obtaining gas fee estimates for a specific transaction. */\nexport type GasFeeFlow = {\n /**\n * Determine if the gas fee flow supports the specified transaction.\n *\n * @param args - The arguments for the matcher function.\n * @param args.transactionMeta - The transaction metadata.\n * @param args.messenger - The messenger instance.\n * @returns Whether the gas fee flow supports the transaction.\n */\n matchesTransaction({\n transactionMeta,\n messenger,\n }: {\n transactionMeta: TransactionMeta;\n messenger: TransactionControllerMessenger;\n }): boolean;\n\n /**\n * Get gas fee estimates for a specific transaction.\n *\n * @param request - The gas fee flow request.\n * @returns The gas fee flow response containing the gas fee estimates.\n */\n getGasFees: (request: GasFeeFlowRequest) => Promise<GasFeeFlowResponse>;\n};\n\n/** Request to a layer 1 gas fee flow to obtain layer 1 fee estimate. */\nexport type Layer1GasFeeFlowRequest = {\n /** RPC Provider instance. */\n provider: Provider;\n\n /** The metadata of the transaction to obtain estimates for. */\n transactionMeta: TransactionMeta;\n};\n\n/** Response from a layer 1 gas fee flow containing layer 1 fee estimate. */\nexport type Layer1GasFeeFlowResponse = {\n /** The gas fee estimates for the transaction. */\n layer1Fee: Hex;\n};\n\n/** A method of obtaining layer 1 gas fee estimates for a specific transaction. */\nexport type Layer1GasFeeFlow = {\n /**\n * Determine if the gas fee flow supports the specified transaction.\n *\n * @param args - The arguments for the matcher function.\n * @param args.transactionMeta - The transaction metadata.\n * @param args.messenger - The messenger instance.\n * @returns A promise that resolves to whether the gas fee flow supports the transaction.\n */\n matchesTransaction({\n transactionMeta,\n messenger,\n }: {\n transactionMeta: TransactionMeta;\n messenger: TransactionControllerMessenger;\n }): Promise<boolean>;\n\n /**\n * Get layer 1 gas fee estimates for a specific transaction.\n *\n * @param request - The gas fee flow request.\n * @returns The gas fee flow response containing the layer 1 gas fee estimate.\n */\n getLayer1Fee: (\n request: Layer1GasFeeFlowRequest,\n ) => Promise<Layer1GasFeeFlowResponse>;\n};\n\n/** Simulation data concerning an update to a native or token balance. */\nexport type SimulationBalanceChange = {\n /** The balance before the transaction. */\n previousBalance: Hex;\n\n /** The balance after the transaction. */\n newBalance: Hex;\n\n /** The difference in balance. */\n difference: Hex;\n\n /** Whether the balance is increasing or decreasing. */\n isDecrease: boolean;\n};\n\n/** Token standards supported by simulation. */\nexport enum SimulationTokenStandard {\n erc20 = 'erc20',\n erc721 = 'erc721',\n erc1155 = 'erc1155',\n}\n\n/** Simulation data concerning an updated token. */\nexport type SimulationToken = {\n /** The token's contract address. */\n address: Hex;\n\n /** The standard of the token. */\n standard: SimulationTokenStandard;\n\n /** The ID of the token if supported by the standard. */\n id?: Hex;\n};\n\n/** Simulation data concerning a change to the a token balance. */\nexport type SimulationTokenBalanceChange = SimulationToken &\n SimulationBalanceChange;\n\nexport enum SimulationErrorCode {\n ChainNotSupported = 'chain-not-supported',\n Disabled = 'disabled',\n InvalidResponse = 'invalid-response',\n Reverted = 'reverted',\n}\n\n/** Error data for a failed simulation. */\nexport type SimulationError = {\n /** Error code to identify the error type. */\n code?: string | number;\n\n /** Error message to describe the error. */\n message?: string;\n};\n\n/** Simulation data for a transaction. */\nexport type SimulationData = {\n /** Error data if the simulation failed or the transaction reverted. */\n error?: SimulationError;\n\n /** Whether the simulation response changed after a security check triggered a re-simulation. */\n isUpdatedAfterSecurityCheck?: boolean;\n\n /** Data concerning a change to the user's native balance. */\n nativeBalanceChange?: SimulationBalanceChange;\n\n /** Data concerning a change to the user's token balances. */\n tokenBalanceChanges: SimulationTokenBalanceChange[];\n};\n\n/** Gas fee properties for a legacy transaction. */\nexport type GasPriceValue = {\n /** Price per gas for legacy transactions. */\n gasPrice: string;\n};\n\n/** Gas fee properties for an EIP-1559 transaction. */\nexport type FeeMarketEIP1559Values = {\n /** Maximum amount to pay per gas. */\n maxFeePerGas: string;\n\n /** Maximum amount per gas to give to the validator as an incentive. */\n maxPriorityFeePerGas: string;\n};\n\n/**\n * Data concerning a successfully submitted transaction.\n * Used for debugging purposes.\n */\nexport type SubmitHistoryEntry = {\n /** The chain ID of the transaction as a hexadecimal string. */\n chainId?: Hex;\n\n /** The hash of the transaction returned from the RPC provider. */\n hash: string;\n\n /** True if the entry was generated using the migration and existing transaction metadata. */\n migration?: boolean;\n\n /** The type of the network where the transaction was submitted. */\n networkType?: string;\n\n /**\n * The URL of the network the transaction was submitted to.\n * A single network URL if it was recorded when submitted.\n * An array of potential network URLs if it cannot be confirmed since the migration was used.\n */\n networkUrl?: string | string[];\n\n /** The origin of the transaction. */\n origin?: string;\n\n /** The raw transaction data that was submitted. */\n rawTransaction: string;\n\n /** When the transaction was submitted. */\n time: number;\n\n /** The transaction parameters that were submitted. */\n transaction: TransactionParams;\n};\n\nexport type InternalAccount = ReturnType<\n AccountsController['getSelectedAccount']\n>;\n\n/**\n * An authorization to be included in a `setCode` transaction.\n * Specifies code to be added to the authorization signer's EOA account.\n * Introduced in EIP-7702.\n */\nexport type Authorization = {\n /** Address of a smart contract that contains the code to be set. */\n address: Hex;\n\n /**\n * Specific chain the authorization applies to.\n * If not provided, defaults to the chain ID of the transaction.\n */\n chainId?: Hex;\n\n /**\n * Nonce at which the authorization will be valid.\n * If not provided, defaults to the nonce following the transaction's nonce.\n */\n nonce?: Hex;\n\n /** R component of the signature. */\n r?: Hex;\n\n /** S component of the signature. */\n s?: Hex;\n\n /** Y parity generated from the signature. */\n yParity?: Hex;\n};\n\n/**\n * An array of authorizations to be included in a `setCode` transaction.\n * Introduced in EIP-7702.\n */\nexport type AuthorizationList = Authorization[];\n\n/**\n * The parameters of a transaction within an atomic batch.\n */\nexport type BatchTransactionParams = {\n /** Data used to invoke a function on the target smart contract or EOA. */\n data?: Hex;\n\n /**\n * Maximum number of units of gas to use for the transaction.\n * Not supported in EIP-7702 batches.\n */\n gas?: Hex;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n * Not supported in EIP-7702 batches.\n */\n maxFeePerGas?: Hex;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n * Not supported in EIP-7702 batches.\n */\n maxPriorityFeePerGas?: Hex;\n\n /** Address of the target contract or EOA. */\n to?: Hex;\n\n /** Native balance to transfer with the transaction. */\n value?: Hex;\n};\n\n/** Metadata for a nested transaction within a standard transaction. */\nexport type NestedTransactionMetadata = BatchTransactionParams & {\n /** Type of the nested transaction. */\n type?: TransactionType;\n};\n\n/**\n * An additional transaction dynamically added to a standard single transaction to form a batch.\n */\nexport type BatchTransaction = BatchTransactionParams & {\n /**\n * Whether the transaction is executed after the main transaction.\n * Defaults to `true`.\n */\n isAfter?: boolean;\n\n /** Type of the batch transaction. */\n type?: TransactionType;\n};\n\n/**\n * Specification for a single transaction within a batch request.\n */\nexport type TransactionBatchSingleRequest = {\n /** The total fiat values of the transaction, to support client metrics. */\n assetsFiatValues?: AssetsFiatValues;\n\n /** Data if the transaction already exists. */\n existingTransaction?: {\n /** ID of the existing transaction. */\n id: string;\n\n /** Optional callback to be invoked once the transaction is published. */\n onPublish?: (request: {\n /** Updated signature for the transaction, if applicable. */\n newSignature?: Hex;\n\n /** Hash of the transaction on the network. */\n transactionHash?: string;\n }) => void;\n\n /** Signed transaction data. */\n signedTransaction: Hex;\n };\n\n /** Parameters of the single transaction. */\n params: BatchTransactionParams;\n\n /** Type of the transaction. */\n type?: TransactionType;\n};\n\n/**\n * Request to submit a batch of transactions.\n * Currently only atomic batches are supported via EIP-7702.\n */\nexport type TransactionBatchRequest = {\n batchId?: Hex;\n\n /** Whether to disable batch transaction processing via an EIP-7702 upgraded account. */\n disable7702?: boolean;\n\n /** Whether to disable batch transaction via the `publishBatch` hook. */\n disableHook?: boolean;\n\n /** Whether to disable batch transaction via sequential transactions. */\n disableSequential?: boolean;\n\n /** Whether to disable upgrading the account to an EIP-7702. */\n disableUpgrade?: boolean;\n\n /** Address of the account to submit the transaction batch. */\n from: Hex;\n\n /** Address of an ERC-20 token to pay for the gas fee, if the user has insufficient native balance. */\n gasFeeToken?: Hex;\n\n /** Whether MetaMask will be compensated for the gas fee by the transaction. */\n isGasFeeIncluded?: boolean;\n\n /** Whether MetaMask will sponsor the gas fee for the transaction. */\n isGasFeeSponsored?: boolean;\n\n /** ID of the network client to submit the transaction. */\n networkClientId: NetworkClientId;\n\n /** Origin of the request, such as a dApp hostname or `ORIGIN_METAMASK` if internal. */\n origin?: string;\n\n /** Whether an approval request should be created to require confirmation from the user. */\n requireApproval?: boolean;\n\n /** Security alert ID to persist on the transaction. */\n securityAlertId?: string;\n\n /** Whether to skip the initial gas calculation and rely only on the polling. */\n skipInitialGasEstimate?: boolean;\n\n /** Transactions to be submitted as part of the batch. */\n transactions: TransactionBatchSingleRequest[];\n\n /**\n * Whether to use the publish batch hook to submit the batch.\n * Defaults to false.\n *\n * @deprecated This is no longer used and will be removed in a future version.\n * Use `disableHook`, `disable7702` and `disableSequential`.\n */\n useHook?: boolean;\n\n /**\n * Callback to trigger security validation in the client.\n *\n * @param request - The JSON-RPC request to validate.\n * @param chainId - The chain ID of the transaction batch.\n */\n validateSecurity?: (\n request: ValidateSecurityRequest,\n chainId: Hex,\n ) => Promise<void>;\n};\n\n/**\n * Result from submitting a transaction batch.\n */\nexport type TransactionBatchResult = {\n /** ID of the batch to locate related transactions. */\n batchId: Hex;\n};\n\n/**\n * Request parameters for updating a custodial transaction.\n */\nexport type UpdateCustodialTransactionRequest = {\n /** The ID of the transaction to update. */\n transactionId: string;\n\n /** The error message to be assigned in case transaction status update to failed. */\n errorMessage?: string;\n\n /** The new hash value to be assigned. */\n hash?: string;\n\n /** The new status value to be assigned. */\n status?: TransactionStatus;\n\n /** The new gas limit value to be assigned. */\n gasLimit?: string;\n\n /** The new gas price value to be assigned. */\n gasPrice?: string;\n\n /** The new max fee per gas value to be assigned. */\n maxFeePerGas?: string;\n\n /** The new max priority fee per gas value to be assigned. */\n maxPriorityFeePerGas?: string;\n\n /** The new nonce value to be assigned. */\n nonce?: string;\n\n /** The new transaction type (hardfork) to be assigned. */\n type?: TransactionEnvelopeType;\n};\n\n/**\n * Data returned from custom logic to publish a transaction.\n */\nexport type PublishHookResult = {\n /**\n * The hash of the transaction on the network.\n */\n transactionHash?: string;\n};\n\n/**\n * Custom logic to publish a transaction.\n *\n * @param transactionMeta - The metadata of the transaction to publish.\n * @param signedTx - The signed transaction data to publish.\n * @returns The result of the publish operation.\n */\nexport type PublishHook = (\n transactionMeta: TransactionMeta,\n signedTx: string,\n) => Promise<PublishHookResult>;\n\n/** Single transaction in a publish batch hook request. */\nexport type PublishBatchHookTransaction = {\n /** ID of the transaction. */\n id?: string;\n\n /** Parameters of the nested transaction. */\n params: BatchTransactionParams;\n\n /** Signed transaction data to publish. */\n signedTx: Hex;\n};\n\n/**\n * Data required to call a publish batch hook.\n */\nexport type PublishBatchHookRequest = {\n /** Address of the account to submit the transaction batch. */\n from: Hex;\n\n /** ID of the network client associated with the transaction batch. */\n networkClientId: string;\n\n /** Nested transactions to be submitted as part of the batch. */\n transactions: PublishBatchHookTransaction[];\n};\n\n/** Result of calling a publish batch hook. */\nexport type PublishBatchHookResult =\n | {\n /** Result data for each transaction in the batch. */\n results: {\n /** Hash of the transaction on the network. */\n transactionHash: Hex;\n }[];\n }\n | undefined;\n\n/** Custom logic to publish a transaction batch. */\nexport type PublishBatchHook = (\n /** Data required to call the hook. */\n request: PublishBatchHookRequest,\n) => Promise<PublishBatchHookResult>;\n\n/**\n * Request to validate security of a transaction in the client.\n */\nexport type ValidateSecurityRequest = {\n /** JSON-RPC method to validate. */\n method: string;\n\n /** Parameters of the JSON-RPC method to validate. */\n params: unknown[];\n\n /** Optional EIP-7702 delegation to mock for the transaction sender. */\n delegationMock?: Hex;\n\n /** Origin of the request, such as a dApp hostname or `ORIGIN_METAMASK` if internal. */\n origin?: string;\n};\n\n/** Data required to pay for transaction gas using an ERC-20 token. */\nexport type GasFeeToken = {\n /** Amount needed for the gas fee. */\n amount: Hex;\n\n /** Current token balance of the sender. */\n balance: Hex;\n\n /** Decimals of the token. */\n decimals: number;\n\n /** Portion of the amount that is the fee paid to MetaMask. */\n fee?: Hex;\n\n /** Estimated gas limit required for original transaction. */\n gas: Hex;\n\n /** Estimated gas limit required for fee transfer. */\n gasTransfer?: Hex;\n\n /** The corresponding maxFeePerGas this token fee would equal. */\n maxFeePerGas: Hex;\n\n /** The corresponding maxPriorityFeePerGas this token fee would equal. */\n maxPriorityFeePerGas: Hex;\n\n /** Conversion rate of 1 token to native WEI. */\n rateWei: Hex;\n\n /** Account address to send the token to. */\n recipient: Hex;\n\n /** Symbol of the token. */\n symbol: string;\n\n /** Address of the token contract. */\n tokenAddress: Hex;\n};\n\n/** Request to check if atomic batch is supported for an account. */\nexport type IsAtomicBatchSupportedRequest = {\n /** Address of the account to check. */\n address: Hex;\n\n /**\n * IDs of specific chains to check.\n * If not provided, all supported chains will be checked.\n */\n chainIds?: Hex[];\n};\n\n/** Result of checking if atomic batch is supported for an account. */\nexport type IsAtomicBatchSupportedResult = IsAtomicBatchSupportedResultEntry[];\n\n/** Info about atomic batch support for a single chain. */\nexport type IsAtomicBatchSupportedResultEntry = {\n /** ID of the chain. */\n chainId: Hex;\n\n /** Address of the contract that the account was upgraded to. */\n delegationAddress?: Hex;\n\n /** Whether the upgraded contract is supported. */\n isSupported: boolean;\n\n /** Address of the contract that the account would be upgraded to. */\n upgradeContractAddress?: Hex;\n};\n\n/**\n * Custom logic to be executed after a transaction is added.\n * Can optionally update the transaction by returning the `updateTransaction` callback.\n */\nexport type AfterAddHook = (request: {\n transactionMeta: TransactionMeta;\n}) => Promise<{\n updateTransaction?: (transaction: TransactionMeta) => void;\n}>;\n\n/**\n * Custom logic to be executed after a transaction is simulated.\n * Can optionally update the transaction by returning the `updateTransaction` callback.\n */\nexport type AfterSimulateHook = (request: {\n transactionMeta: TransactionMeta;\n}) => Promise<\n | {\n skipSimulation?: boolean;\n updateTransaction?: (transaction: TransactionMeta) => void;\n }\n | undefined\n>;\n\n/**\n * Custom logic to be executed before a transaction is signed.\n * Can optionally update the transaction by returning the `updateTransaction` callback.\n */\nexport type BeforeSignHook = (request: {\n transactionMeta: TransactionMeta;\n}) => Promise<\n | {\n updateTransaction?: (transaction: TransactionMeta) => void;\n }\n | undefined\n>;\n\n/**\n * The total fiat values of the transaction, to support client metrics.\n */\nexport type AssetsFiatValues = {\n /**\n * The fiat value of the receiving assets.\n */\n receiving?: string;\n\n /**\n * The fiat value of the sending assets.\n */\n sending?: string;\n};\n\n/** Metadata specific to the MetaMask Pay feature. */\nexport type MetamaskPayMetadata = {\n /** Total fee from any bridge transactions, in fiat currency. */\n bridgeFeeFiat?: string;\n\n /** Chain ID of the payment token. */\n chainId?: Hex;\n\n /** Total network fee in fiat currency, including the original and bridge transactions. */\n networkFeeFiat?: string;\n\n /** Address of the payment token that the transaction funds were sourced from. */\n tokenAddress?: Hex;\n\n /** Total cost of the transaction in fiat currency, including gas, fees, and the funds themselves. */\n totalFiat?: string;\n};\n\n/**\n * Parameters for the transaction simulation API.\n */\nexport type GetSimulationConfig = (\n url: string,\n opts?: {\n txMeta?: TransactionMeta;\n },\n) => Promise<{\n newUrl?: string;\n authorization?: string;\n}>;\n\n/**\n * Options for adding a transaction.\n */\nexport type AddTransactionOptions = {\n /** Unique ID to prevent duplicate requests. */\n actionId?: string;\n\n /** Fiat values of the assets being sent and received. */\n assetsFiatValues?: AssetsFiatValues;\n\n /** Custom ID for the batch this transaction belongs to. */\n batchId?: Hex;\n\n /** Enum to indicate what device confirmed the transaction. */\n deviceConfirmedOn?: WalletDevice;\n\n /** Whether to disable the gas estimation buffer. */\n disableGasBuffer?: boolean;\n\n /** Address of an ERC-20 token to pay for the gas fee, if the user has insufficient native balance. */\n gasFeeToken?: Hex;\n\n /** Whether MetaMask will be compensated for the gas fee by the transaction. */\n isGasFeeIncluded?: boolean;\n\n /** Whether MetaMask will sponsor the gas fee for the transaction. */\n isGasFeeSponsored?: boolean;\n\n /** RPC method that requested the transaction. */\n method?: string;\n\n /** Params for any nested transactions encoded in the data. */\n nestedTransactions?: NestedTransactionMetadata[];\n\n /** ID of the network client for this transaction. */\n networkClientId: NetworkClientId;\n\n /** Origin of the transaction request, such as a dApp hostname. */\n origin?: string;\n\n /** Custom logic to publish the transaction. */\n publishHook?: PublishHook;\n\n /** Whether the transaction requires approval by the user, defaults to true unless explicitly disabled. */\n requireApproval?: boolean | undefined;\n\n /** Response from security validator. */\n securityAlertResponse?: SecurityAlertResponse;\n\n /** Entries to add to the `sendFlowHistory`. */\n sendFlowHistory?: SendFlowHistoryEntry[];\n\n /** Whether to skip the initial gas calculation and rely only on the polling. */\n skipInitialGasEstimate?: boolean;\n\n /** Options for swaps transactions. */\n swaps?: {\n /** Whether the transaction has an approval transaction. */\n hasApproveTx?: boolean;\n\n /** Metadata for swap transaction. */\n meta?: Partial<TransactionMeta>;\n };\n\n /** Parent context for any new traces. */\n traceContext?: unknown;\n\n /** Type of transaction to add, such as 'cancel' or 'swap'. */\n type?: TransactionType;\n};\n\n/**\n * Request to get gas fee tokens.\n */\nexport type GetGasFeeTokensRequest = {\n /** ID of the chain. */\n chainId: Hex;\n\n /** Data of the transaction. */\n data?: Hex;\n\n /** Address of the sender. */\n from: Hex;\n\n /** Address of the recipient. */\n to: Hex;\n\n /** Value of the transaction. */\n value?: Hex;\n};\n"]}
@@ -104,11 +104,16 @@ function generateBatchId() {
104
104
  async function getNestedTransactionMeta(request, singleRequest, ethQuery) {
105
105
  const { from } = request;
106
106
  const { params, type: requestedType } = singleRequest;
107
+ if (requestedType) {
108
+ return {
109
+ ...params,
110
+ type: requestedType,
111
+ };
112
+ }
107
113
  const { type: determinedType } = await (0, __1.determineTransactionType)({ from, ...params }, ethQuery);
108
- const type = requestedType ?? determinedType;
109
114
  return {
110
115
  ...params,
111
- type,
116
+ type: determinedType,
112
117
  };
113
118
  }
114
119
  /**
@@ -119,7 +124,7 @@ async function getNestedTransactionMeta(request, singleRequest, ethQuery) {
119
124
  */
120
125
  async function addTransactionBatchWith7702(request) {
121
126
  const { addTransaction, getChainId, messenger, publicKeyEIP7702, request: userRequest, } = request;
122
- const { batchId: batchIdOverride, from, gasFeeToken, networkClientId, origin, requireApproval, securityAlertId, transactions, validateSecurity, } = userRequest;
127
+ const { batchId: batchIdOverride, disableUpgrade, from, gasFeeToken, networkClientId, origin, requireApproval, securityAlertId, skipInitialGasEstimate, transactions, validateSecurity, } = userRequest;
123
128
  const chainId = getChainId(networkClientId);
124
129
  const ethQuery = request.getEthQuery(networkClientId);
125
130
  const isChainSupported = (0, eip7702_1.doesChainSupportEIP7702)(chainId, messenger);
@@ -130,11 +135,15 @@ async function addTransactionBatchWith7702(request) {
130
135
  if (!publicKeyEIP7702) {
131
136
  throw rpc_errors_1.rpcErrors.internal(eip7702_1.ERROR_MESSGE_PUBLIC_KEY);
132
137
  }
133
- const { delegationAddress, isSupported } = await (0, eip7702_1.isAccountUpgradedToEIP7702)(from, chainId, publicKeyEIP7702, messenger, ethQuery);
134
- log('Account', { delegationAddress, isSupported });
135
- if (!isSupported && delegationAddress) {
136
- log('Account upgraded to unsupported contract', from, delegationAddress);
137
- throw rpc_errors_1.rpcErrors.internal('Account upgraded to unsupported contract');
138
+ let requiresUpgrade = false;
139
+ if (!disableUpgrade) {
140
+ const { delegationAddress, isSupported } = await (0, eip7702_1.isAccountUpgradedToEIP7702)(from, chainId, publicKeyEIP7702, messenger, ethQuery);
141
+ log('Account', { delegationAddress, isSupported });
142
+ if (!isSupported && delegationAddress) {
143
+ log('Account upgraded to unsupported contract', from, delegationAddress);
144
+ throw rpc_errors_1.rpcErrors.internal('Account upgraded to unsupported contract');
145
+ }
146
+ requiresUpgrade = !isSupported;
138
147
  }
139
148
  const nestedTransactions = await Promise.all(transactions.map((tx) => getNestedTransactionMeta(userRequest, tx, ethQuery)));
140
149
  const batchParams = (0, eip7702_1.generateEIP7702BatchTransaction)(from, nestedTransactions);
@@ -142,7 +151,7 @@ async function addTransactionBatchWith7702(request) {
142
151
  from,
143
152
  ...batchParams,
144
153
  };
145
- if (!isSupported) {
154
+ if (requiresUpgrade) {
146
155
  const upgradeContractAddress = (0, feature_flags_1.getEIP7702UpgradeContractAddress)(chainId, messenger, publicKeyEIP7702);
147
156
  if (!upgradeContractAddress) {
148
157
  throw rpc_errors_1.rpcErrors.internal(exports.ERROR_MESSAGE_NO_UPGRADE_CONTRACT);
@@ -194,6 +203,7 @@ async function addTransactionBatchWith7702(request) {
194
203
  origin,
195
204
  requireApproval,
196
205
  securityAlertResponse,
206
+ skipInitialGasEstimate,
197
207
  type: types_1.TransactionType.batch,
198
208
  });
199
209
  const transactionHash = await result;
@@ -1 +1 @@
1
- {"version":3,"file":"batch.cjs","sourceRoot":"","sources":["../../src/utils/batch.ts"],"names":[],"mappings":";;;AAIA,iEAIoC;AAMpC,qDAA+D;AAE/D,2CAAiE;AAEjE,+BAAiC;AAEjC,2CAKmB;AACnB,uDAIyB;AACzB,mCAAyC;AACzC,iDAAoD;AAEpD,oCAQY;AACZ,0EAAmE;AACnE,8DAAwE;AAExE,wEAAiE;AACjE,wFAAiF;AACjF,0CAA0C;AAc1C,wCAKkB;AAiDlB,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,OAAO,CAAC,CAAC;AAE1C,QAAA,iCAAiC,GAC5C,oCAAoC,CAAC;AAEvC;;;;;GAKG;AACI,KAAK,UAAU,mBAAmB,CACvC,OAAmC;IAEnC,MAAM,EACJ,mBAAmB,EACnB,SAAS,EACT,OAAO,EAAE,uBAAuB,GACjC,GAAG,OAAO,CAAC;IACZ,MAAM,SAAS,GAAG,IAAA,iCAAiB,EAAC,SAAS,CAAC,CAAC;IAE/C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EAAE,GAAG,OAAO,CAAC;IACpD,MAAM,cAAc,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;IAErD,GAAG,CAAC,iCAAiC,EAAE;QACrC,aAAa;QACb,QAAQ,EAAE,cAAc,CAAC,QAAQ;KAClC,CAAC,CAAC;IAEH,MAAM,YAAY,GAAG,CAAC,MAAM,eAAe,CAAC,cAAc,CAAC,CAE9C,CAAC;IAEd,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACnD,CAAC;IAED,MAAM,eAAe,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;IAEtD,GAAG,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC;IAEnC,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,CAAC;AAC3C,CAAC","sourcesContent":["import type {\n AcceptResultCallbacks,\n AddResult,\n} from '@metamask/approval-controller';\nimport {\n ApprovalType,\n ORIGIN_METAMASK,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport { JsonRpcError, rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { bytesToHex, createModuleLogger } from '@metamask/utils';\nimport type { WritableDraft } from 'immer/dist/internal.js';\nimport { parse, v4 } from 'uuid';\n\nimport {\n ERROR_MESSGE_PUBLIC_KEY,\n doesChainSupportEIP7702,\n generateEIP7702BatchTransaction,\n isAccountUpgradedToEIP7702,\n} from './eip7702';\nimport {\n getBatchSizeLimit,\n getEIP7702SupportedChains,\n getEIP7702UpgradeContractAddress,\n} from './feature-flags';\nimport { simulateGasBatch } from './gas';\nimport { validateBatchRequest } from './validation';\nimport type { GetSimulationConfig, TransactionControllerState } from '..';\nimport {\n determineTransactionType,\n GasFeeEstimateLevel,\n TransactionStatus,\n type BatchTransactionParams,\n type TransactionController,\n type TransactionControllerMessenger,\n type TransactionMeta,\n} from '..';\nimport { DefaultGasFeeFlow } from '../gas-flows/DefaultGasFeeFlow';\nimport { updateTransactionGasEstimates } from '../helpers/GasFeePoller';\nimport type { PendingTransactionTracker } from '../helpers/PendingTransactionTracker';\nimport { CollectPublishHook } from '../hooks/CollectPublishHook';\nimport { SequentialPublishBatchHook } from '../hooks/SequentialPublishBatchHook';\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 TransactionBatchMeta,\n} from '../types';\nimport {\n TransactionEnvelopeType,\n type TransactionBatchResult,\n type TransactionParams,\n TransactionType,\n} from '../types';\n\ntype UpdateStateCallback = (\n callback: (\n state: WritableDraft<TransactionControllerState>,\n ) => void | TransactionControllerState,\n) => void;\n\ntype AddTransactionBatchRequest = {\n addTransaction: TransactionController['addTransaction'];\n estimateGas: TransactionController['estimateGas'];\n getChainId: (networkClientId: string) => Hex;\n getEthQuery: (networkClientId: string) => EthQuery;\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getInternalAccounts: () => Hex[];\n getPendingTransactionTracker: (\n networkClientId: string,\n ) => PendingTransactionTracker;\n getSimulationConfig: GetSimulationConfig;\n getTransaction: (id: string) => TransactionMeta;\n isSimulationEnabled: () => boolean;\n messenger: TransactionControllerMessenger;\n publishBatchHook?: PublishBatchHook;\n publishTransaction: (\n _ethQuery: EthQuery,\n transactionMeta: TransactionMeta,\n ) => Promise<Hex>;\n publicKeyEIP7702?: Hex;\n request: TransactionBatchRequest;\n signTransaction: (\n transactionMeta: TransactionMeta,\n ) => Promise<string | undefined>;\n update: UpdateStateCallback;\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\nexport const ERROR_MESSAGE_NO_UPGRADE_CONTRACT =\n 'Upgrade contract address not found';\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 getInternalAccounts,\n messenger,\n request: transactionBatchRequest,\n } = request;\n const sizeLimit = getBatchSizeLimit(messenger);\n\n validateBatchRequest({\n internalAccounts: getInternalAccounts(),\n request: transactionBatchRequest,\n sizeLimit,\n });\n\n log('Adding', transactionBatchRequest);\n\n if (!transactionBatchRequest.disable7702) {\n try {\n return await addTransactionBatchWith7702(request);\n } catch (error: unknown) {\n const isEIP7702NotSupportedError =\n error instanceof JsonRpcError &&\n error.message === 'Chain does not support EIP-7702';\n\n if (!isEIP7702NotSupportedError) {\n throw error;\n }\n }\n }\n\n return await addTransactionBatchWithHook(request);\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(ERROR_MESSGE_PUBLIC_KEY);\n }\n\n const chainIds7702 = getEIP7702SupportedChains(messenger);\n\n const filteredChainIds = chainIds7702.filter(\n (chainId) => !chainIds || chainIds.includes(chainId),\n );\n\n const resultsRaw: (IsAtomicBatchSupportedResultEntry | undefined)[] =\n await Promise.all(\n filteredChainIds.map(async (chainId) => {\n try {\n const ethQuery = getEthQuery(chainId);\n\n const { isSupported, delegationAddress } =\n 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 return {\n chainId,\n delegationAddress,\n isSupported,\n upgradeContractAddress,\n };\n } catch (error) {\n log('Error checking atomic batch support', chainId, error);\n return undefined;\n }\n }),\n );\n\n const results = resultsRaw.filter(\n (result): result is IsAtomicBatchSupportedResultEntry => Boolean(result),\n );\n\n log('Atomic batch supported results', results);\n\n return results;\n}\n\n/**\n * Generate a transaction 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, type: requestedType } = singleRequest;\n\n const { type: determinedType } = await determineTransactionType(\n { from, ...params },\n ethQuery,\n );\n\n const type = requestedType ?? determinedType;\n return {\n ...params,\n type,\n };\n}\n\n/**\n * Process a batch transaction using an EIP-7702 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 */\nasync function addTransactionBatchWith7702(\n request: AddTransactionBatchRequest,\n) {\n const {\n addTransaction,\n getChainId,\n messenger,\n publicKeyEIP7702,\n request: userRequest,\n } = request;\n\n const {\n batchId: batchIdOverride,\n from,\n gasFeeToken,\n networkClientId,\n origin,\n requireApproval,\n securityAlertId,\n transactions,\n validateSecurity,\n } = userRequest;\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(ERROR_MESSGE_PUBLIC_KEY);\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(ERROR_MESSAGE_NO_UPGRADE_CONTRACT);\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 origin,\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 existingTransaction = transactions.find(\n (tx) => tx.existingTransaction,\n )?.existingTransaction;\n\n if (existingTransaction) {\n await convertTransactionToEIP7702({\n batchId,\n existingTransaction,\n nestedTransactions,\n request,\n txParams,\n });\n\n return { batchId };\n }\n\n const { result } = await addTransaction(txParams, {\n batchId,\n gasFeeToken,\n isGasFeeIncluded: userRequest.isGasFeeIncluded,\n isGasFeeSponsored: userRequest.isGasFeeSponsored,\n nestedTransactions,\n networkClientId,\n origin,\n requireApproval,\n securityAlertResponse,\n type: TransactionType.batch,\n });\n\n const transactionHash = await result;\n\n log('Batch transaction added', { batchId, transactionHash });\n\n return {\n batchId,\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 {\n messenger,\n publishBatchHook: requestPublishBatchHook,\n request: userRequest,\n update,\n } = request;\n\n const {\n from,\n networkClientId,\n origin,\n requireApproval,\n transactions: requestedTransactions,\n } = userRequest;\n\n let resultCallbacks: AcceptResultCallbacks | undefined;\n let isSequentialBatchHook = false;\n\n log('Adding transaction batch using hook', userRequest);\n\n const sequentialPublishBatchHook = new SequentialPublishBatchHook({\n publishTransaction: request.publishTransaction,\n getTransaction: request.getTransaction,\n getEthQuery: request.getEthQuery,\n getPendingTransactionTracker: request.getPendingTransactionTracker,\n });\n\n let { disable7702, disableSequential } = userRequest;\n const { disableHook, useHook } = userRequest;\n\n // use hook is a temporary alias for disable7702 and disableSequential\n if (useHook) {\n disable7702 = true;\n disableSequential = true;\n }\n\n let publishBatchHook = null;\n\n if (!disableHook && requestPublishBatchHook) {\n publishBatchHook = requestPublishBatchHook;\n } else if (!disableSequential) {\n publishBatchHook = sequentialPublishBatchHook.getHook();\n isSequentialBatchHook = true;\n }\n\n if (!publishBatchHook) {\n log(`No supported batch methods found`, {\n disable7702,\n disableHook,\n disableSequential,\n });\n throw rpcErrors.internal(`Can't process batch`);\n }\n\n let txBatchMeta: TransactionBatchMeta | undefined;\n const batchId = generateBatchId();\n\n const nestedTransactions = requestedTransactions.map((tx) => ({\n ...tx,\n origin,\n }));\n\n const transactionCount = nestedTransactions.length;\n const collectHook = new CollectPublishHook(transactionCount);\n\n try {\n if (requireApproval) {\n txBatchMeta = await prepareApprovalData({\n batchId,\n request,\n });\n\n resultCallbacks = (await requestApproval(txBatchMeta, messenger))\n .resultCallbacks;\n }\n\n const publishHook = collectHook.getHook();\n const hookTransactions: Omit<PublishBatchHookTransaction, 'signedTx'>[] =\n [];\n\n let index = 0;\n\n for (const nestedTransaction of nestedTransactions) {\n const hookTransaction = await processTransactionWithHook(\n batchId,\n nestedTransaction,\n publishHook,\n request,\n txBatchMeta,\n index,\n );\n\n hookTransactions.push(hookTransaction);\n index += 1;\n }\n\n const { signedTransactions } = await collectHook.ready();\n\n const transactions = hookTransactions.map((transaction, i) => ({\n ...transaction,\n signedTx: signedTransactions[i],\n }));\n\n const hookParams = { from, networkClientId, transactions };\n\n log('Calling publish batch hook', hookParams);\n\n let result = await publishBatchHook(hookParams);\n\n log('Publish batch hook result', result);\n\n if (!result && !isSequentialBatchHook && !disableSequential) {\n log('Fallback to sequential publish batch hook due to empty results');\n const sequentialBatchHook = sequentialPublishBatchHook.getHook();\n result = await sequentialBatchHook(hookParams);\n }\n\n if (!result?.results?.length) {\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 resultCallbacks?.success();\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 resultCallbacks?.error(error as Error);\n\n throw error;\n } finally {\n log('Cleaning up publish batch hook', batchId);\n wipeTransactionBatchById(update, batchId);\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 * @param txBatchMeta - Metadata for the transaction batch.\n * @param index - The index of the transaction in the batch.\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 txBatchMeta: TransactionBatchMeta | undefined,\n index: number,\n) {\n const { assetsFiatValues, existingTransaction, params, type } =\n nestedTransaction;\n\n const {\n addTransaction,\n getTransaction,\n request: userRequest,\n updateTransaction,\n } = request;\n\n const { from, networkClientId, origin } = userRequest;\n\n if (existingTransaction) {\n const { id, onPublish } = existingTransaction;\n let transactionMeta = getTransaction(id);\n const currentNonceHex = transactionMeta.txParams.nonce;\n let { signedTransaction } = existingTransaction;\n\n const currentNonceNum = currentNonceHex\n ? parseInt(currentNonceHex, 16)\n : undefined;\n\n const newNonce =\n index > 0 && currentNonceNum !== undefined\n ? currentNonceNum + index\n : undefined;\n\n updateTransaction({ transactionId: id }, (_transactionMeta) => {\n _transactionMeta.batchId = batchId;\n\n if (newNonce) {\n _transactionMeta.txParams.nonce = toHex(newNonce);\n }\n });\n\n if (newNonce) {\n const signResult = await updateTransactionSignature({\n transactionId: id,\n request,\n });\n\n signedTransaction = signResult.newSignature;\n transactionMeta = signResult.transactionMeta;\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 transactionMetaForGasEstimates = {\n ...txBatchMeta,\n txParams: { ...params, from, gas: txBatchMeta?.gas ?? params.gas },\n };\n\n if (txBatchMeta) {\n updateTransactionGasEstimates({\n txMeta: transactionMetaForGasEstimates as TransactionMeta,\n userFeeLevel: GasFeeEstimateLevel.Medium,\n });\n }\n\n const { transactionMeta } = await addTransaction(\n transactionMetaForGasEstimates.txParams,\n {\n assetsFiatValues,\n batchId,\n disableGasBuffer: true,\n networkClientId,\n origin,\n publishHook,\n requireApproval: false,\n type,\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', {\n id,\n params: newParams,\n type,\n });\n\n return {\n id,\n params: newParams,\n type,\n };\n}\n\n/**\n * Requests approval for a transaction batch by interacting with the ApprovalController.\n *\n * @param txBatchMeta - Metadata for the transaction batch, including its ID and origin.\n * @param messenger - The messenger instance used to communicate with the ApprovalController.\n * @returns A promise that resolves to the result of adding the approval request.\n */\nasync function requestApproval(\n txBatchMeta: TransactionBatchMeta,\n messenger: TransactionControllerMessenger,\n): Promise<AddResult> {\n const id = String(txBatchMeta.id);\n const { origin } = txBatchMeta;\n const type = ApprovalType.TransactionBatch;\n const requestData = { txBatchId: id };\n\n log('Requesting approval for transaction batch', id);\n return (await messenger.call(\n 'ApprovalController:addRequest',\n {\n id,\n origin: origin || ORIGIN_METAMASK,\n requestData,\n expectsResult: true,\n type,\n },\n true,\n )) as Promise<AddResult>;\n}\n\n/**\n * Adds batch metadata to the transaction controller state.\n *\n * @param transactionBatchMeta - The transaction batch metadata to be added.\n * @param update - The update function to modify the transaction controller state.\n */\nfunction addBatchMetadata(\n transactionBatchMeta: TransactionBatchMeta,\n update: UpdateStateCallback,\n) {\n update((state) => {\n state.transactionBatches = [\n ...state.transactionBatches,\n transactionBatchMeta,\n ];\n });\n}\n\n/**\n * Wipes a specific transaction batch from the transaction controller state by its ID.\n *\n * @param update - The update function to modify the transaction controller state.\n * @param id - The ID of the transaction batch to be wiped.\n */\nfunction wipeTransactionBatchById(\n update: UpdateStateCallback,\n id: string,\n): void {\n update((state) => {\n state.transactionBatches = state.transactionBatches.filter(\n (batch) => batch.id !== id,\n );\n });\n}\n\n/**\n * Create a new batch metadata object.\n *\n * @param transactionBatchMeta - The transaction batch metadata object to be created.\n * @returns A new TransactionBatchMeta object.\n */\nfunction newBatchMetadata(\n transactionBatchMeta: Omit<TransactionBatchMeta, 'status'>,\n): TransactionBatchMeta {\n return {\n ...transactionBatchMeta,\n status: TransactionStatus.unapproved,\n };\n}\n\n/**\n * Prepares the approval data for a transaction batch.\n *\n * @param options - The options object containing necessary parameters.\n * @param options.batchId - The batch ID for the transaction batch.\n * @param options.request - The request object including the user request and necessary callbacks.\n * @returns The prepared transaction batch metadata.\n */\nasync function prepareApprovalData({\n batchId,\n request,\n}: {\n batchId: Hex;\n request: AddTransactionBatchRequest;\n}): Promise<TransactionBatchMeta> {\n const {\n messenger,\n request: userRequest,\n isSimulationEnabled,\n getChainId,\n getEthQuery,\n getGasFeeEstimates,\n getSimulationConfig,\n update,\n } = request;\n\n const {\n from,\n origin,\n networkClientId,\n transactions: nestedTransactions,\n } = userRequest;\n\n const ethQuery = getEthQuery(networkClientId);\n\n if (!isSimulationEnabled()) {\n throw new Error(\n 'Cannot create transaction batch as simulation not supported',\n );\n }\n log('Preparing approval data for batch');\n const chainId = getChainId(networkClientId);\n\n const { gasLimit } = await simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions: nestedTransactions,\n });\n\n const txBatchMeta: TransactionBatchMeta = newBatchMetadata({\n chainId,\n from,\n gas: gasLimit,\n id: batchId,\n networkClientId,\n origin,\n transactions: nestedTransactions,\n });\n\n const defaultGasFeeFlow = new DefaultGasFeeFlow();\n const gasFeeControllerData = await getGasFeeEstimates({\n networkClientId,\n });\n\n const gasFeeResponse = await defaultGasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: {\n ...txBatchMeta,\n txParams: {\n from,\n gas: gasLimit,\n },\n time: Date.now(),\n },\n });\n\n txBatchMeta.gasFeeEstimates = gasFeeResponse.estimates;\n\n log('Saving transaction batch metadata', txBatchMeta);\n addBatchMetadata(txBatchMeta, update);\n\n return txBatchMeta;\n}\n\n/**\n * Convert an existing transaction to an EIP-7702 batch transaction.\n *\n * @param options - Options object.\n * @param options.batchId - Batch ID for the transaction batch.\n * @param options.existingTransaction - Existing transaction to be converted.\n * @param options.nestedTransactions - Nested transactions to be included in the batch.\n * @param options.request - Request object including the user request and necessary callbacks.\n * @param options.txParams - Transaction parameters for the new EIP-7702 transaction.\n * @param options.existingTransaction.id - ID of the existing transaction.\n * @param options.existingTransaction.onPublish - Callback for when the transaction is published.\n * @returns Promise that resolves after the publish callback has been invoked.\n */\nasync function convertTransactionToEIP7702({\n batchId,\n existingTransaction,\n nestedTransactions,\n request,\n txParams,\n}: {\n batchId: Hex;\n request: AddTransactionBatchRequest;\n existingTransaction: {\n id: string;\n onPublish?: ({\n transactionHash,\n newSignature,\n }: {\n transactionHash: string | undefined;\n newSignature: Hex;\n }) => void;\n };\n nestedTransactions: NestedTransactionMetadata[];\n txParams: TransactionParams;\n}) {\n const { getTransaction, estimateGas, updateTransaction } = request;\n const existingTransactionMeta = getTransaction(existingTransaction.id);\n\n if (!existingTransactionMeta) {\n throw new Error('Existing transaction not found');\n }\n\n log('Converting existing transaction to 7702', { batchId, txParams });\n\n const { networkClientId } = existingTransactionMeta;\n const newGasResult = await estimateGas(txParams, networkClientId);\n\n log('Estimated gas for converted EIP-7702 transaction', newGasResult);\n\n updateTransaction(\n { transactionId: existingTransactionMeta.id },\n (transactionMeta) => {\n transactionMeta.batchId = batchId;\n transactionMeta.nestedTransactions = nestedTransactions;\n transactionMeta.txParams = txParams;\n transactionMeta.txParams.gas = newGasResult.gas;\n transactionMeta.txParams.gasLimit = newGasResult.gas;\n transactionMeta.txParams.maxFeePerGas =\n existingTransactionMeta.txParams.maxFeePerGas;\n transactionMeta.txParams.maxPriorityFeePerGas =\n existingTransactionMeta.txParams.maxPriorityFeePerGas;\n transactionMeta.txParams.nonce = existingTransactionMeta.txParams.nonce;\n transactionMeta.txParams.type ??= TransactionEnvelopeType.feeMarket;\n },\n );\n\n const { newSignature } = await updateTransactionSignature({\n request,\n transactionId: existingTransactionMeta.id,\n });\n\n existingTransaction.onPublish?.({\n transactionHash: undefined,\n newSignature,\n });\n\n log('Transaction updated to EIP-7702', { batchId, txParams, newSignature });\n}\n\n/**\n * Update the signature of an existing transaction.\n *\n * @param options - Options object.\n * @param options.request - The request object including the user request and necessary callbacks.\n * @param options.transactionId - The ID of the transaction to update.\n * @returns An object containing the new signature and updated transaction metadata.\n */\nasync function updateTransactionSignature({\n request,\n transactionId,\n}: {\n request: AddTransactionBatchRequest;\n transactionId: string;\n}): Promise<{\n newSignature: Hex;\n transactionMeta: TransactionMeta;\n}> {\n const { getTransaction, signTransaction } = request;\n const metadataToSign = getTransaction(transactionId);\n\n log('Re-signing existing transaction', {\n transactionId,\n txParams: metadataToSign.txParams,\n });\n\n const newSignature = (await signTransaction(metadataToSign)) as\n | Hex\n | undefined;\n\n if (!newSignature) {\n throw new Error('Failed to re-sign transaction');\n }\n\n const transactionMeta = getTransaction(transactionId);\n\n log('New signature', newSignature);\n\n return { newSignature, transactionMeta };\n}\n"]}
1
+ {"version":3,"file":"batch.cjs","sourceRoot":"","sources":["../../src/utils/batch.ts"],"names":[],"mappings":";;;AAIA,iEAIoC;AAMpC,qDAA+D;AAE/D,2CAAiE;AAEjE,+BAAiC;AAEjC,2CAKmB;AACnB,uDAIyB;AACzB,mCAAyC;AACzC,iDAAoD;AAEpD,oCAQY;AACZ,0EAAmE;AACnE,8DAAwE;AAExE,wEAAiE;AACjE,wFAAiF;AACjF,0CAA0C;AAc1C,wCAKkB;AAiDlB,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,OAAO,CAAC,CAAC;AAE1C,QAAA,iCAAiC,GAC5C,oCAAoC,CAAC;A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C;IAEF,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,0BAA0B,CAAC;QACxD,OAAO;QACP,aAAa,EAAE,uBAAuB,CAAC,EAAE;KAC1C,CAAC,CAAC;IAEH,mBAAmB,CAAC,SAAS,EAAE,CAAC;QAC9B,eAAe,EAAE,SAAS;QAC1B,YAAY;KACb,CAAC,CAAC;IAEH,GAAG,CAAC,iCAAiC,EAAE,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC,CAAC;AAC9E,CAAC;AAED;;;;;;;GAOG;AACH,KAAK,UAAU,0BAA0B,CAAC,EACxC,OAAO,EACP,aAAa,GAId;IAIC,MAAM,EAAE,cAAc,EAAE,eAAe,EAAE,GAAG,OAAO,CAAC;IACpD,MAAM,cAAc,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;IAErD,GAAG,CAAC,iCAAiC,EAAE;QACrC,aAAa;QACb,QAAQ,EAAE,cAAc,CAAC,QAAQ;KAClC,CAAC,CAAC;IAEH,MAAM,YAAY,GAAG,CAAC,MAAM,eAAe,CAAC,cAAc,CAAC,CAE9C,CAAC;IAEd,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;IACnD,CAAC;IAED,MAAM,eAAe,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;IAEtD,GAAG,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC;IAEnC,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,CAAC;AAC3C,CAAC","sourcesContent":["import type {\n AcceptResultCallbacks,\n AddResult,\n} from '@metamask/approval-controller';\nimport {\n ApprovalType,\n ORIGIN_METAMASK,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport { JsonRpcError, rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { bytesToHex, createModuleLogger } from '@metamask/utils';\nimport type { WritableDraft } from 'immer/dist/internal.js';\nimport { parse, v4 } from 'uuid';\n\nimport {\n ERROR_MESSGE_PUBLIC_KEY,\n doesChainSupportEIP7702,\n generateEIP7702BatchTransaction,\n isAccountUpgradedToEIP7702,\n} from './eip7702';\nimport {\n getBatchSizeLimit,\n getEIP7702SupportedChains,\n getEIP7702UpgradeContractAddress,\n} from './feature-flags';\nimport { simulateGasBatch } from './gas';\nimport { validateBatchRequest } from './validation';\nimport type { GetSimulationConfig, TransactionControllerState } from '..';\nimport {\n determineTransactionType,\n GasFeeEstimateLevel,\n TransactionStatus,\n type BatchTransactionParams,\n type TransactionController,\n type TransactionControllerMessenger,\n type TransactionMeta,\n} from '..';\nimport { DefaultGasFeeFlow } from '../gas-flows/DefaultGasFeeFlow';\nimport { updateTransactionGasEstimates } from '../helpers/GasFeePoller';\nimport type { PendingTransactionTracker } from '../helpers/PendingTransactionTracker';\nimport { CollectPublishHook } from '../hooks/CollectPublishHook';\nimport { SequentialPublishBatchHook } from '../hooks/SequentialPublishBatchHook';\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 TransactionBatchMeta,\n} from '../types';\nimport {\n TransactionEnvelopeType,\n type TransactionBatchResult,\n type TransactionParams,\n TransactionType,\n} from '../types';\n\ntype UpdateStateCallback = (\n callback: (\n state: WritableDraft<TransactionControllerState>,\n ) => void | TransactionControllerState,\n) => void;\n\ntype AddTransactionBatchRequest = {\n addTransaction: TransactionController['addTransaction'];\n estimateGas: TransactionController['estimateGas'];\n getChainId: (networkClientId: string) => Hex;\n getEthQuery: (networkClientId: string) => EthQuery;\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getInternalAccounts: () => Hex[];\n getPendingTransactionTracker: (\n networkClientId: string,\n ) => PendingTransactionTracker;\n getSimulationConfig: GetSimulationConfig;\n getTransaction: (id: string) => TransactionMeta;\n isSimulationEnabled: () => boolean;\n messenger: TransactionControllerMessenger;\n publishBatchHook?: PublishBatchHook;\n publishTransaction: (\n _ethQuery: EthQuery,\n transactionMeta: TransactionMeta,\n ) => Promise<Hex>;\n publicKeyEIP7702?: Hex;\n request: TransactionBatchRequest;\n signTransaction: (\n transactionMeta: TransactionMeta,\n ) => Promise<string | undefined>;\n update: UpdateStateCallback;\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\nexport const ERROR_MESSAGE_NO_UPGRADE_CONTRACT =\n 'Upgrade contract address not found';\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 getInternalAccounts,\n messenger,\n request: transactionBatchRequest,\n } = request;\n const sizeLimit = getBatchSizeLimit(messenger);\n\n validateBatchRequest({\n internalAccounts: getInternalAccounts(),\n request: transactionBatchRequest,\n sizeLimit,\n });\n\n log('Adding', transactionBatchRequest);\n\n if (!transactionBatchRequest.disable7702) {\n try {\n return await addTransactionBatchWith7702(request);\n } catch (error: unknown) {\n const isEIP7702NotSupportedError =\n error instanceof JsonRpcError &&\n error.message === 'Chain does not support EIP-7702';\n\n if (!isEIP7702NotSupportedError) {\n throw error;\n }\n }\n }\n\n return await addTransactionBatchWithHook(request);\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(ERROR_MESSGE_PUBLIC_KEY);\n }\n\n const chainIds7702 = getEIP7702SupportedChains(messenger);\n\n const filteredChainIds = chainIds7702.filter(\n (chainId) => !chainIds || chainIds.includes(chainId),\n );\n\n const resultsRaw: (IsAtomicBatchSupportedResultEntry | undefined)[] =\n await Promise.all(\n filteredChainIds.map(async (chainId) => {\n try {\n const ethQuery = getEthQuery(chainId);\n\n const { isSupported, delegationAddress } =\n 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 return {\n chainId,\n delegationAddress,\n isSupported,\n upgradeContractAddress,\n };\n } catch (error) {\n log('Error checking atomic batch support', chainId, error);\n return undefined;\n }\n }),\n );\n\n const results = resultsRaw.filter(\n (result): result is IsAtomicBatchSupportedResultEntry => Boolean(result),\n );\n\n log('Atomic batch supported results', results);\n\n return results;\n}\n\n/**\n * Generate a transaction 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, type: requestedType } = singleRequest;\n\n if (requestedType) {\n return {\n ...params,\n type: requestedType,\n };\n }\n\n const { type: determinedType } = await determineTransactionType(\n { from, ...params },\n ethQuery,\n );\n\n return {\n ...params,\n type: determinedType,\n };\n}\n\n/**\n * Process a batch transaction using an EIP-7702 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 */\nasync function addTransactionBatchWith7702(\n request: AddTransactionBatchRequest,\n) {\n const {\n addTransaction,\n getChainId,\n messenger,\n publicKeyEIP7702,\n request: userRequest,\n } = request;\n\n const {\n batchId: batchIdOverride,\n disableUpgrade,\n from,\n gasFeeToken,\n networkClientId,\n origin,\n requireApproval,\n securityAlertId,\n skipInitialGasEstimate,\n transactions,\n validateSecurity,\n } = userRequest;\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(ERROR_MESSGE_PUBLIC_KEY);\n }\n\n let requiresUpgrade = false;\n\n if (!disableUpgrade) {\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 requiresUpgrade = !isSupported;\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 (requiresUpgrade) {\n const upgradeContractAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKeyEIP7702,\n );\n\n if (!upgradeContractAddress) {\n throw rpcErrors.internal(ERROR_MESSAGE_NO_UPGRADE_CONTRACT);\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 origin,\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 existingTransaction = transactions.find(\n (tx) => tx.existingTransaction,\n )?.existingTransaction;\n\n if (existingTransaction) {\n await convertTransactionToEIP7702({\n batchId,\n existingTransaction,\n nestedTransactions,\n request,\n txParams,\n });\n\n return { batchId };\n }\n\n const { result } = await addTransaction(txParams, {\n batchId,\n gasFeeToken,\n isGasFeeIncluded: userRequest.isGasFeeIncluded,\n isGasFeeSponsored: userRequest.isGasFeeSponsored,\n nestedTransactions,\n networkClientId,\n origin,\n requireApproval,\n securityAlertResponse,\n skipInitialGasEstimate,\n type: TransactionType.batch,\n });\n\n const transactionHash = await result;\n\n log('Batch transaction added', { batchId, transactionHash });\n\n return {\n batchId,\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 {\n messenger,\n publishBatchHook: requestPublishBatchHook,\n request: userRequest,\n update,\n } = request;\n\n const {\n from,\n networkClientId,\n origin,\n requireApproval,\n transactions: requestedTransactions,\n } = userRequest;\n\n let resultCallbacks: AcceptResultCallbacks | undefined;\n let isSequentialBatchHook = false;\n\n log('Adding transaction batch using hook', userRequest);\n\n const sequentialPublishBatchHook = new SequentialPublishBatchHook({\n publishTransaction: request.publishTransaction,\n getTransaction: request.getTransaction,\n getEthQuery: request.getEthQuery,\n getPendingTransactionTracker: request.getPendingTransactionTracker,\n });\n\n let { disable7702, disableSequential } = userRequest;\n const { disableHook, useHook } = userRequest;\n\n // use hook is a temporary alias for disable7702 and disableSequential\n if (useHook) {\n disable7702 = true;\n disableSequential = true;\n }\n\n let publishBatchHook = null;\n\n if (!disableHook && requestPublishBatchHook) {\n publishBatchHook = requestPublishBatchHook;\n } else if (!disableSequential) {\n publishBatchHook = sequentialPublishBatchHook.getHook();\n isSequentialBatchHook = true;\n }\n\n if (!publishBatchHook) {\n log(`No supported batch methods found`, {\n disable7702,\n disableHook,\n disableSequential,\n });\n throw rpcErrors.internal(`Can't process batch`);\n }\n\n let txBatchMeta: TransactionBatchMeta | undefined;\n const batchId = generateBatchId();\n\n const nestedTransactions = requestedTransactions.map((tx) => ({\n ...tx,\n origin,\n }));\n\n const transactionCount = nestedTransactions.length;\n const collectHook = new CollectPublishHook(transactionCount);\n\n try {\n if (requireApproval) {\n txBatchMeta = await prepareApprovalData({\n batchId,\n request,\n });\n\n resultCallbacks = (await requestApproval(txBatchMeta, messenger))\n .resultCallbacks;\n }\n\n const publishHook = collectHook.getHook();\n const hookTransactions: Omit<PublishBatchHookTransaction, 'signedTx'>[] =\n [];\n\n let index = 0;\n\n for (const nestedTransaction of nestedTransactions) {\n const hookTransaction = await processTransactionWithHook(\n batchId,\n nestedTransaction,\n publishHook,\n request,\n txBatchMeta,\n index,\n );\n\n hookTransactions.push(hookTransaction);\n index += 1;\n }\n\n const { signedTransactions } = await collectHook.ready();\n\n const transactions = hookTransactions.map((transaction, i) => ({\n ...transaction,\n signedTx: signedTransactions[i],\n }));\n\n const hookParams = { from, networkClientId, transactions };\n\n log('Calling publish batch hook', hookParams);\n\n let result = await publishBatchHook(hookParams);\n\n log('Publish batch hook result', result);\n\n if (!result && !isSequentialBatchHook && !disableSequential) {\n log('Fallback to sequential publish batch hook due to empty results');\n const sequentialBatchHook = sequentialPublishBatchHook.getHook();\n result = await sequentialBatchHook(hookParams);\n }\n\n if (!result?.results?.length) {\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 resultCallbacks?.success();\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 resultCallbacks?.error(error as Error);\n\n throw error;\n } finally {\n log('Cleaning up publish batch hook', batchId);\n wipeTransactionBatchById(update, batchId);\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 * @param txBatchMeta - Metadata for the transaction batch.\n * @param index - The index of the transaction in the batch.\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 txBatchMeta: TransactionBatchMeta | undefined,\n index: number,\n) {\n const { assetsFiatValues, existingTransaction, params, type } =\n nestedTransaction;\n\n const {\n addTransaction,\n getTransaction,\n request: userRequest,\n updateTransaction,\n } = request;\n\n const { from, networkClientId, origin } = userRequest;\n\n if (existingTransaction) {\n const { id, onPublish } = existingTransaction;\n let transactionMeta = getTransaction(id);\n const currentNonceHex = transactionMeta.txParams.nonce;\n let { signedTransaction } = existingTransaction;\n\n const currentNonceNum = currentNonceHex\n ? parseInt(currentNonceHex, 16)\n : undefined;\n\n const newNonce =\n index > 0 && currentNonceNum !== undefined\n ? currentNonceNum + index\n : undefined;\n\n updateTransaction({ transactionId: id }, (_transactionMeta) => {\n _transactionMeta.batchId = batchId;\n\n if (newNonce) {\n _transactionMeta.txParams.nonce = toHex(newNonce);\n }\n });\n\n if (newNonce) {\n const signResult = await updateTransactionSignature({\n transactionId: id,\n request,\n });\n\n signedTransaction = signResult.newSignature;\n transactionMeta = signResult.transactionMeta;\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 transactionMetaForGasEstimates = {\n ...txBatchMeta,\n txParams: { ...params, from, gas: txBatchMeta?.gas ?? params.gas },\n };\n\n if (txBatchMeta) {\n updateTransactionGasEstimates({\n txMeta: transactionMetaForGasEstimates as TransactionMeta,\n userFeeLevel: GasFeeEstimateLevel.Medium,\n });\n }\n\n const { transactionMeta } = await addTransaction(\n transactionMetaForGasEstimates.txParams,\n {\n assetsFiatValues,\n batchId,\n disableGasBuffer: true,\n networkClientId,\n origin,\n publishHook,\n requireApproval: false,\n type,\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', {\n id,\n params: newParams,\n type,\n });\n\n return {\n id,\n params: newParams,\n type,\n };\n}\n\n/**\n * Requests approval for a transaction batch by interacting with the ApprovalController.\n *\n * @param txBatchMeta - Metadata for the transaction batch, including its ID and origin.\n * @param messenger - The messenger instance used to communicate with the ApprovalController.\n * @returns A promise that resolves to the result of adding the approval request.\n */\nasync function requestApproval(\n txBatchMeta: TransactionBatchMeta,\n messenger: TransactionControllerMessenger,\n): Promise<AddResult> {\n const id = String(txBatchMeta.id);\n const { origin } = txBatchMeta;\n const type = ApprovalType.TransactionBatch;\n const requestData = { txBatchId: id };\n\n log('Requesting approval for transaction batch', id);\n return (await messenger.call(\n 'ApprovalController:addRequest',\n {\n id,\n origin: origin || ORIGIN_METAMASK,\n requestData,\n expectsResult: true,\n type,\n },\n true,\n )) as Promise<AddResult>;\n}\n\n/**\n * Adds batch metadata to the transaction controller state.\n *\n * @param transactionBatchMeta - The transaction batch metadata to be added.\n * @param update - The update function to modify the transaction controller state.\n */\nfunction addBatchMetadata(\n transactionBatchMeta: TransactionBatchMeta,\n update: UpdateStateCallback,\n) {\n update((state) => {\n state.transactionBatches = [\n ...state.transactionBatches,\n transactionBatchMeta,\n ];\n });\n}\n\n/**\n * Wipes a specific transaction batch from the transaction controller state by its ID.\n *\n * @param update - The update function to modify the transaction controller state.\n * @param id - The ID of the transaction batch to be wiped.\n */\nfunction wipeTransactionBatchById(\n update: UpdateStateCallback,\n id: string,\n): void {\n update((state) => {\n state.transactionBatches = state.transactionBatches.filter(\n (batch) => batch.id !== id,\n );\n });\n}\n\n/**\n * Create a new batch metadata object.\n *\n * @param transactionBatchMeta - The transaction batch metadata object to be created.\n * @returns A new TransactionBatchMeta object.\n */\nfunction newBatchMetadata(\n transactionBatchMeta: Omit<TransactionBatchMeta, 'status'>,\n): TransactionBatchMeta {\n return {\n ...transactionBatchMeta,\n status: TransactionStatus.unapproved,\n };\n}\n\n/**\n * Prepares the approval data for a transaction batch.\n *\n * @param options - The options object containing necessary parameters.\n * @param options.batchId - The batch ID for the transaction batch.\n * @param options.request - The request object including the user request and necessary callbacks.\n * @returns The prepared transaction batch metadata.\n */\nasync function prepareApprovalData({\n batchId,\n request,\n}: {\n batchId: Hex;\n request: AddTransactionBatchRequest;\n}): Promise<TransactionBatchMeta> {\n const {\n messenger,\n request: userRequest,\n isSimulationEnabled,\n getChainId,\n getEthQuery,\n getGasFeeEstimates,\n getSimulationConfig,\n update,\n } = request;\n\n const {\n from,\n origin,\n networkClientId,\n transactions: nestedTransactions,\n } = userRequest;\n\n const ethQuery = getEthQuery(networkClientId);\n\n if (!isSimulationEnabled()) {\n throw new Error(\n 'Cannot create transaction batch as simulation not supported',\n );\n }\n log('Preparing approval data for batch');\n const chainId = getChainId(networkClientId);\n\n const { gasLimit } = await simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions: nestedTransactions,\n });\n\n const txBatchMeta: TransactionBatchMeta = newBatchMetadata({\n chainId,\n from,\n gas: gasLimit,\n id: batchId,\n networkClientId,\n origin,\n transactions: nestedTransactions,\n });\n\n const defaultGasFeeFlow = new DefaultGasFeeFlow();\n const gasFeeControllerData = await getGasFeeEstimates({\n networkClientId,\n });\n\n const gasFeeResponse = await defaultGasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: {\n ...txBatchMeta,\n txParams: {\n from,\n gas: gasLimit,\n },\n time: Date.now(),\n },\n });\n\n txBatchMeta.gasFeeEstimates = gasFeeResponse.estimates;\n\n log('Saving transaction batch metadata', txBatchMeta);\n addBatchMetadata(txBatchMeta, update);\n\n return txBatchMeta;\n}\n\n/**\n * Convert an existing transaction to an EIP-7702 batch transaction.\n *\n * @param options - Options object.\n * @param options.batchId - Batch ID for the transaction batch.\n * @param options.existingTransaction - Existing transaction to be converted.\n * @param options.nestedTransactions - Nested transactions to be included in the batch.\n * @param options.request - Request object including the user request and necessary callbacks.\n * @param options.txParams - Transaction parameters for the new EIP-7702 transaction.\n * @param options.existingTransaction.id - ID of the existing transaction.\n * @param options.existingTransaction.onPublish - Callback for when the transaction is published.\n * @returns Promise that resolves after the publish callback has been invoked.\n */\nasync function convertTransactionToEIP7702({\n batchId,\n existingTransaction,\n nestedTransactions,\n request,\n txParams,\n}: {\n batchId: Hex;\n request: AddTransactionBatchRequest;\n existingTransaction: {\n id: string;\n onPublish?: ({\n transactionHash,\n newSignature,\n }: {\n transactionHash: string | undefined;\n newSignature: Hex;\n }) => void;\n };\n nestedTransactions: NestedTransactionMetadata[];\n txParams: TransactionParams;\n}) {\n const { getTransaction, estimateGas, updateTransaction } = request;\n const existingTransactionMeta = getTransaction(existingTransaction.id);\n\n if (!existingTransactionMeta) {\n throw new Error('Existing transaction not found');\n }\n\n log('Converting existing transaction to 7702', { batchId, txParams });\n\n const { networkClientId } = existingTransactionMeta;\n const newGasResult = await estimateGas(txParams, networkClientId);\n\n log('Estimated gas for converted EIP-7702 transaction', newGasResult);\n\n updateTransaction(\n { transactionId: existingTransactionMeta.id },\n (transactionMeta) => {\n transactionMeta.batchId = batchId;\n transactionMeta.nestedTransactions = nestedTransactions;\n transactionMeta.txParams = txParams;\n transactionMeta.txParams.gas = newGasResult.gas;\n transactionMeta.txParams.gasLimit = newGasResult.gas;\n transactionMeta.txParams.maxFeePerGas =\n existingTransactionMeta.txParams.maxFeePerGas;\n transactionMeta.txParams.maxPriorityFeePerGas =\n existingTransactionMeta.txParams.maxPriorityFeePerGas;\n transactionMeta.txParams.nonce = existingTransactionMeta.txParams.nonce;\n transactionMeta.txParams.type ??= TransactionEnvelopeType.feeMarket;\n },\n );\n\n const { newSignature } = await updateTransactionSignature({\n request,\n transactionId: existingTransactionMeta.id,\n });\n\n existingTransaction.onPublish?.({\n transactionHash: undefined,\n newSignature,\n });\n\n log('Transaction updated to EIP-7702', { batchId, txParams, newSignature });\n}\n\n/**\n * Update the signature of an existing transaction.\n *\n * @param options - Options object.\n * @param options.request - The request object including the user request and necessary callbacks.\n * @param options.transactionId - The ID of the transaction to update.\n * @returns An object containing the new signature and updated transaction metadata.\n */\nasync function updateTransactionSignature({\n request,\n transactionId,\n}: {\n request: AddTransactionBatchRequest;\n transactionId: string;\n}): Promise<{\n newSignature: Hex;\n transactionMeta: TransactionMeta;\n}> {\n const { getTransaction, signTransaction } = request;\n const metadataToSign = getTransaction(transactionId);\n\n log('Re-signing existing transaction', {\n transactionId,\n txParams: metadataToSign.txParams,\n });\n\n const newSignature = (await signTransaction(metadataToSign)) as\n | Hex\n | undefined;\n\n if (!newSignature) {\n throw new Error('Failed to re-sign transaction');\n }\n\n const transactionMeta = getTransaction(transactionId);\n\n log('New signature', newSignature);\n\n return { newSignature, transactionMeta };\n}\n"]}