@metamask/transaction-controller 14.0.0 → 16.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -1
- package/dist/TransactionController.d.ts +22 -7
- package/dist/TransactionController.d.ts.map +1 -1
- package/dist/TransactionController.js +42 -80
- package/dist/TransactionController.js.map +1 -1
- package/dist/{EtherscanRemoteTransactionSource.d.ts → helpers/EtherscanRemoteTransactionSource.d.ts} +1 -1
- package/dist/helpers/EtherscanRemoteTransactionSource.d.ts.map +1 -0
- package/dist/{EtherscanRemoteTransactionSource.js → helpers/EtherscanRemoteTransactionSource.js} +4 -4
- package/dist/helpers/EtherscanRemoteTransactionSource.js.map +1 -0
- package/dist/{IncomingTransactionHelper.d.ts → helpers/IncomingTransactionHelper.d.ts} +1 -1
- package/dist/helpers/IncomingTransactionHelper.d.ts.map +1 -0
- package/dist/{IncomingTransactionHelper.js → helpers/IncomingTransactionHelper.js} +1 -1
- package/dist/helpers/IncomingTransactionHelper.js.map +1 -0
- package/dist/{PendingTransactionTracker.d.ts → helpers/PendingTransactionTracker.d.ts} +4 -2
- package/dist/helpers/PendingTransactionTracker.d.ts.map +1 -0
- package/dist/{PendingTransactionTracker.js → helpers/PendingTransactionTracker.js} +47 -17
- package/dist/helpers/PendingTransactionTracker.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +71 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +36 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/etherscan.d.ts.map +1 -0
- package/dist/{etherscan.js → utils/etherscan.js} +3 -4
- package/dist/utils/etherscan.js.map +1 -0
- package/dist/{external-transactions.d.ts → utils/external-transactions.d.ts} +1 -1
- package/dist/utils/external-transactions.d.ts.map +1 -0
- package/dist/{external-transactions.js → utils/external-transactions.js} +1 -1
- package/dist/utils/external-transactions.js.map +1 -0
- package/dist/utils/gas-fees.d.ts +30 -0
- package/dist/utils/gas-fees.d.ts.map +1 -0
- package/dist/utils/gas-fees.js +194 -0
- package/dist/utils/gas-fees.js.map +1 -0
- package/dist/utils/gas.d.ts +25 -0
- package/dist/utils/gas.d.ts.map +1 -0
- package/dist/utils/gas.js +125 -0
- package/dist/utils/gas.js.map +1 -0
- package/dist/{history.d.ts → utils/history.d.ts} +1 -1
- package/dist/utils/history.d.ts.map +1 -0
- package/dist/utils/history.js.map +1 -0
- package/dist/{transaction-type.d.ts → utils/transaction-type.d.ts} +1 -1
- package/dist/utils/transaction-type.d.ts.map +1 -0
- package/dist/{transaction-type.js → utils/transaction-type.js} +1 -1
- package/dist/utils/transaction-type.js.map +1 -0
- package/dist/{utils.d.ts → utils/utils.d.ts} +3 -3
- package/dist/utils/utils.d.ts.map +1 -0
- package/dist/{utils.js → utils/utils.js} +3 -3
- package/dist/utils/utils.js.map +1 -0
- package/dist/{validation.d.ts → utils/validation.d.ts} +1 -1
- package/dist/utils/validation.d.ts.map +1 -0
- package/dist/utils/validation.js.map +1 -0
- package/package.json +9 -7
- package/dist/EtherscanRemoteTransactionSource.d.ts.map +0 -1
- package/dist/EtherscanRemoteTransactionSource.js.map +0 -1
- package/dist/IncomingTransactionHelper.d.ts.map +0 -1
- package/dist/IncomingTransactionHelper.js.map +0 -1
- package/dist/PendingTransactionTracker.d.ts.map +0 -1
- package/dist/PendingTransactionTracker.js.map +0 -1
- package/dist/etherscan.d.ts.map +0 -1
- package/dist/etherscan.js.map +0 -1
- package/dist/external-transactions.d.ts.map +0 -1
- package/dist/external-transactions.js.map +0 -1
- package/dist/history.d.ts.map +0 -1
- package/dist/history.js.map +0 -1
- package/dist/transaction-type.d.ts.map +0 -1
- package/dist/transaction-type.js.map +0 -1
- package/dist/utils.d.ts.map +0 -1
- package/dist/utils.js.map +0 -1
- package/dist/validation.d.ts.map +0 -1
- package/dist/validation.js.map +0 -1
- /package/dist/{etherscan.d.ts → utils/etherscan.d.ts} +0 -0
- /package/dist/{history.js → utils/history.js} +0 -0
- /package/dist/{validation.js → utils/validation.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TransactionController.js","sourceRoot":"","sources":["../src/TransactionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+CAAwE;AAExE,uCAAoD;AAWpD,+DAA2D;AAC3D,iEAUoC;AACpC,oEAA2C;AAM3C,qDAA6E;AAE7E,6CAAoC;AACpC,8EAAiD;AACjD,qDAA4D;AAC5D,mCAAsC;AACtC,mCAAuC;AACvC,kEAAyC;AACzC,+BAAoC;AAEpC,yFAAsF;AACtF,mEAA+E;AAC/E,uCAAgF;AAChF,2EAAwE;AACxE,qCAAqD;AACrD,2EAAwE;AACxE,yDAA8D;AAU9D,mCAA6D;AAC7D,mCAWiB;AACjB,6CAA2E;AAE9D,QAAA,QAAQ,GAAG,iBAAQ,CAAC,MAAM,CAAC;AA0DxC;;GAEG;AACU,QAAA,WAAW,GAAG,GAAG,CAAC;AAE/B;;GAEG;AACU,QAAA,aAAa,GAAG,GAAG,CAAC;AAEjC;;GAEG;AACH,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAkB/C;;GAEG;AACH,MAAa,qBAAsB,SAAQ,gCAG1C;IAwEC;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,YACE,EACE,YAAY,EACZ,cAAc,EACd,sBAAsB,EACtB,qCAAqC,EACrC,qCAAqC,EACrC,eAAe,EACf,oBAAoB,EACpB,kBAAkB,EAClB,oBAAoB,GAAG,EAAE,EACzB,SAAS,EACT,oBAAoB,EACpB,QAAQ,EACR,uBAAuB,GAoBxB,EACD,MAAmC,EACnC,KAAiC;QAEjC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAvHN,UAAK,GAAG,IAAI,mBAAK,EAAE,CAAC;QAuCrC;;WAEG;QACH,QAAG,GAAG,IAAI,qBAAY,EAAE,CAAC;QAEzB;;W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KAAA;IAEa,uBAAuB;;;YACnC,MAAM,iCAAiC,GACrC,MAAM,IAAI,CAAC,qCAAqC,EAAE,CAAC;YACrD,MAAM,iCAAiC,GACrC,MAAA,MAAA,IAAI,CAAC,qCAAqC,oDAAI,mCAAI,IAAI,CAAC;YAEzD,OAAO,CACL,iCAAiC,IAAI,iCAAiC,CACvE,CAAC;;KACH;CACF;AAhjDD,sDAgjDC;AAED,kBAAe,qBAAqB,CAAC","sourcesContent":["import { Hardfork, Common, type ChainConfig } from '@ethereumjs/common';\nimport type { TypedTransaction } from '@ethereumjs/tx';\nimport { TransactionFactory } from '@ethereumjs/tx';\nimport type {\n AcceptResultCallbacks,\n AddApprovalRequest,\n AddResult,\n} from '@metamask/approval-controller';\nimport type {\n BaseConfig,\n BaseState,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n BNToHex,\n fractionBN,\n hexToBN,\n query,\n NetworkType,\n RPC,\n ApprovalType,\n ORIGIN_METAMASK,\n convertHexToDecimal,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type {\n BlockTracker,\n NetworkState,\n Provider,\n} from '@metamask/network-controller';\nimport { errorCodes, rpcErrors, providerErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport MethodRegistry from 'eth-method-registry';\nimport { addHexPrefix, bufferToHex } from 'ethereumjs-util';\nimport { EventEmitter } from 'events';\nimport { merge, pickBy } from 'lodash';\nimport NonceTracker from 'nonce-tracker';\nimport { v1 as random } from 'uuid';\n\nimport { EtherscanRemoteTransactionSource } from './EtherscanRemoteTransactionSource';\nimport { validateConfirmedExternalTransaction } from './external-transactions';\nimport { addInitialHistorySnapshot, updateTransactionHistory } from './history';\nimport { IncomingTransactionHelper } from './IncomingTransactionHelper';\nimport { pendingTransactionsLogger } from './logger';\nimport { PendingTransactionTracker } from './PendingTransactionTracker';\nimport { determineTransactionType } from './transaction-type';\nimport type {\n DappSuggestedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionReceipt,\n SecurityProviderRequest,\n SendFlowHistoryEntry,\n WalletDevice,\n} from './types';\nimport { TransactionType, TransactionStatus } from './types';\nimport {\n getAndFormatTransactionsForNonceTracker,\n getIncreasedPriceFromExisting,\n normalizeTxParams,\n isEIP1559Transaction,\n isFeeMarketEIP1559Values,\n isGasPriceValue,\n validateGasValues,\n validateIfTransactionUnapproved,\n validateMinimumIncrease,\n ESTIMATE_GAS_ERROR,\n} from './utils';\nimport { validateTransactionOrigin, validateTxParams } from './validation';\n\nexport const HARDFORK = Hardfork.London;\n\n/**\n * @type Result\n * @property result - Promise resolving to a new transaction hash\n * @property transactionMeta - Meta information about this new transaction\n */\nexport interface Result {\n result: Promise<string>;\n transactionMeta: TransactionMeta;\n}\n\nexport interface GasPriceValue {\n gasPrice: string;\n}\n\nexport interface FeeMarketEIP1559Values {\n maxFeePerGas: string;\n maxPriorityFeePerGas: string;\n}\n\n/**\n * @type TransactionConfig\n *\n * Transaction controller configuration\n * @property provider - Provider used to create a new underlying EthQuery instance\n * @property sign - Method used to sign transactions\n */\nexport interface TransactionConfig extends BaseConfig {\n sign?: (txParams: TransactionParams, from: string) => Promise<any>;\n txHistoryLimit: number;\n}\n\n/**\n * @type MethodData\n *\n * Method data registry object\n * @property registryMethod - Registry method raw string\n * @property parsedRegistryMethod - Registry method object, containing name and method arguments\n */\nexport interface MethodData {\n registryMethod: string;\n parsedRegistryMethod: Record<string, unknown>;\n}\n\n/**\n * @type TransactionState\n *\n * Transaction controller state\n * @property transactions - A list of TransactionMeta objects\n * @property methodData - Object containing all known method data information\n */\nexport interface TransactionState extends BaseState {\n transactions: TransactionMeta[];\n methodData: { [key: string]: MethodData };\n lastFetchedBlockNumbers: { [key: string]: number };\n}\n\n/**\n * Multiplier used to determine a transaction's increased gas fee during cancellation\n */\nexport const CANCEL_RATE = 1.5;\n\n/**\n * Multiplier used to determine a transaction's increased gas fee during speed up\n */\nexport const SPEED_UP_RATE = 1.1;\n\n/**\n * The name of the {@link TransactionController}.\n */\nconst controllerName = 'TransactionController';\n\n/**\n * The external actions available to the {@link TransactionController}.\n */\ntype AllowedActions = AddApprovalRequest;\n\n/**\n * The messenger of the {@link TransactionController}.\n */\nexport type TransactionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n never,\n AllowedActions['type'],\n never\n>;\n\n/**\n * Controller responsible for submitting and managing transactions.\n */\nexport class TransactionController extends BaseController<\n TransactionConfig,\n TransactionState\n> {\n private ethQuery: EthQuery;\n\n private readonly isHistoryDisabled: boolean;\n\n private readonly isSendFlowHistoryDisabled: boolean;\n\n private readonly nonceTracker: NonceTracker;\n\n private registry: any;\n\n private readonly provider: Provider;\n\n private readonly handle?: ReturnType<typeof setTimeout>;\n\n private readonly mutex = new Mutex();\n\n private readonly getNetworkState: () => NetworkState;\n\n private readonly getCurrentAccountEIP1559Compatibility: () => Promise<boolean>;\n\n private readonly getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;\n\n private readonly getPermittedAccounts: (origin?: string) => Promise<string[]>;\n\n private readonly getSelectedAddress: () => string;\n\n private readonly messagingSystem: TransactionControllerMessenger;\n\n private readonly incomingTransactionHelper: IncomingTransactionHelper;\n\n private readonly securityProviderRequest?: SecurityProviderRequest;\n\n private readonly pendingTransactionTracker: PendingTransactionTracker;\n\n private failTransaction(transactionMeta: TransactionMeta, error: Error) {\n const newTransactionMeta = {\n ...transactionMeta,\n error,\n status: TransactionStatus.failed,\n };\n this.updateTransaction(\n newTransactionMeta,\n 'TransactionController#failTransaction - Add error message and set status to failed',\n );\n this.hub.emit(`${transactionMeta.id}:finished`, newTransactionMeta);\n }\n\n private async registryLookup(fourBytePrefix: string): Promise<MethodData> {\n const registryMethod = await this.registry.lookup(fourBytePrefix);\n const parsedRegistryMethod = this.registry.parse(registryMethod);\n return { registryMethod, parsedRegistryMethod };\n }\n\n /**\n * EventEmitter instance used to listen to specific transactional events\n */\n hub = new EventEmitter();\n\n /**\n * Name of this controller used during composition\n */\n override name = 'TransactionController';\n\n /**\n * Method used to sign transactions\n */\n sign?: (\n transaction: TypedTransaction,\n from: string,\n ) => Promise<TypedTransaction>;\n\n /**\n * Creates a TransactionController instance.\n *\n * @param options - The controller options.\n * @param options.blockTracker - The block tracker used to poll for new blocks data.\n * @param options.disableHistory - Whether to disable storing history in transaction metadata.\n * @param options.disableSendFlowHistory - Explicitly disable transaction metadata history.\n * @param options.getCurrentAccountEIP1559Compatibility - Whether or not the account supports EIP-1559.\n * @param options.getCurrentNetworkEIP1559Compatibility - Whether or not the network supports EIP-1559.\n * @param options.getNetworkState - Gets the state of the network controller.\n * @param options.getPermittedAccounts - Get accounts that a given origin has permissions for.\n * @param options.getSelectedAddress - Gets the address of the currently selected account.\n * @param options.incomingTransactions - Configuration options for incoming transaction support.\n * @param options.incomingTransactions.includeTokenTransfers - Whether or not to include ERC20 token transfers.\n * @param options.incomingTransactions.isEnabled - Whether or not incoming transaction retrieval is enabled.\n * @param options.incomingTransactions.queryEntireHistory - Whether to initially query the entire transaction history or only recent blocks.\n * @param options.incomingTransactions.updateTransactions - Whether to update local transactions using remote transaction data.\n * @param options.messenger - The controller messenger.\n * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.\n * @param options.provider - The provider used to create the underlying EthQuery instance.\n * @param options.securityProviderRequest - A function for verifying a transaction, whether it is malicious or not.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n blockTracker,\n disableHistory,\n disableSendFlowHistory,\n getCurrentAccountEIP1559Compatibility,\n getCurrentNetworkEIP1559Compatibility,\n getNetworkState,\n getPermittedAccounts,\n getSelectedAddress,\n incomingTransactions = {},\n messenger,\n onNetworkStateChange,\n provider,\n securityProviderRequest,\n }: {\n blockTracker: BlockTracker;\n disableHistory: boolean;\n disableSendFlowHistory: boolean;\n getCurrentAccountEIP1559Compatibility: () => Promise<boolean>;\n getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;\n getNetworkState: () => NetworkState;\n getPermittedAccounts: (origin?: string) => Promise<string[]>;\n getSelectedAddress: () => string;\n incomingTransactions: {\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n updateTransactions?: boolean;\n };\n messenger: TransactionControllerMessenger;\n onNetworkStateChange: (listener: (state: NetworkState) => void) => void;\n provider: Provider;\n securityProviderRequest?: SecurityProviderRequest;\n },\n config?: Partial<TransactionConfig>,\n state?: Partial<TransactionState>,\n ) {\n super(config, state);\n\n this.defaultConfig = {\n txHistoryLimit: 40,\n };\n\n this.defaultState = {\n methodData: {},\n transactions: [],\n lastFetchedBlockNumbers: {},\n };\n\n this.initialize();\n\n this.provider = provider;\n this.messagingSystem = messenger;\n this.getNetworkState = getNetworkState;\n this.ethQuery = new EthQuery(provider);\n this.isSendFlowHistoryDisabled = disableSendFlowHistory ?? false;\n this.isHistoryDisabled = disableHistory ?? false;\n this.registry = new MethodRegistry({ provider });\n this.getCurrentAccountEIP1559Compatibility =\n getCurrentAccountEIP1559Compatibility;\n this.getCurrentNetworkEIP1559Compatibility =\n getCurrentNetworkEIP1559Compatibility;\n this.getPermittedAccounts = getPermittedAccounts;\n this.getSelectedAddress = getSelectedAddress;\n this.securityProviderRequest = securityProviderRequest;\n\n this.nonceTracker = new NonceTracker({\n provider,\n blockTracker,\n getPendingTransactions: (address) =>\n getAndFormatTransactionsForNonceTracker(\n address,\n TransactionStatus.submitted,\n this.state.transactions,\n ),\n getConfirmedTransactions: (address) =>\n getAndFormatTransactionsForNonceTracker(\n address,\n TransactionStatus.confirmed,\n this.state.transactions,\n ),\n });\n\n this.incomingTransactionHelper = new IncomingTransactionHelper({\n blockTracker,\n getCurrentAccount: getSelectedAddress,\n getLastFetchedBlockNumbers: () => this.state.lastFetchedBlockNumbers,\n getNetworkState,\n isEnabled: incomingTransactions.isEnabled,\n queryEntireHistory: incomingTransactions.queryEntireHistory,\n remoteTransactionSource: new EtherscanRemoteTransactionSource({\n includeTokenTransfers: incomingTransactions.includeTokenTransfers,\n }),\n transactionLimit: this.config.txHistoryLimit,\n updateTransactions: incomingTransactions.updateTransactions,\n });\n\n this.incomingTransactionHelper.hub.on(\n 'transactions',\n this.onIncomingTransactions.bind(this),\n );\n\n this.incomingTransactionHelper.hub.on(\n 'updatedLastFetchedBlockNumbers',\n this.onUpdatedLastFetchedBlockNumbers.bind(this),\n );\n\n this.pendingTransactionTracker = new PendingTransactionTracker({\n blockTracker,\n failTransaction: this.failTransaction.bind(this),\n getChainId: this.getChainId.bind(this),\n getEthQuery: () => this.ethQuery,\n getTransactions: () => this.state.transactions,\n });\n\n this.pendingTransactionTracker.hub.on(\n 'transactions',\n this.onPendingTransactionsUpdate.bind(this),\n );\n\n this.pendingTransactionTracker.hub.on(\n 'transaction-confirmed',\n (transactionMeta: TransactionMeta) =>\n this.hub.emit(`${transactionMeta.id}:confirmed`, transactionMeta),\n );\n\n onNetworkStateChange(() => {\n this.ethQuery = new EthQuery(this.provider);\n this.registry = new MethodRegistry({ provider: this.provider });\n });\n\n this.pendingTransactionTracker.start();\n }\n\n /**\n * Handle new method data request.\n *\n * @param fourBytePrefix - The method prefix.\n * @returns The method data object corresponding to the given signature prefix.\n */\n async handleMethodData(fourBytePrefix: string): Promise<MethodData> {\n const releaseLock = await this.mutex.acquire();\n try {\n const { methodData } = this.state;\n const knownMethod = Object.keys(methodData).find(\n (knownFourBytePrefix) => fourBytePrefix === knownFourBytePrefix,\n );\n if (knownMethod) {\n return methodData[fourBytePrefix];\n }\n const registry = await this.registryLookup(fourBytePrefix);\n this.update({\n methodData: { ...methodData, ...{ [fourBytePrefix]: registry } },\n });\n return registry;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Add a new unapproved transaction to state. Parameters will be validated, a\n * unique transaction id will be generated, and gas and gasPrice will be calculated\n * if not provided. If A `<tx.id>:unapproved` hub event will be emitted once added.\n *\n * @param txParams - Standard parameters for an Ethereum transaction.\n * @param opts - Additional options to control how the transaction is added.\n * @param opts.actionId - Unique ID to prevent duplicate requests.\n * @param opts.deviceConfirmedOn - An enum to indicate what device confirmed the transaction.\n * @param opts.method - RPC method that requested the transaction.\n * @param opts.origin - The origin of the transaction request, such as a dApp hostname.\n * @param opts.requireApproval - Whether the transaction requires approval by the user, defaults to true unless explicitly disabled.\n * @param opts.securityAlertResponse - Response from security validator.\n * @param opts.sendFlowHistory - The sendFlowHistory entries to add.\n * @param opts.type - Type of transaction to add, such as 'cancel' or 'swap'.\n * @returns Object containing a promise resolving to the transaction hash if approved.\n */\n async addTransaction(\n txParams: TransactionParams,\n {\n actionId,\n deviceConfirmedOn,\n method,\n origin,\n requireApproval,\n securityAlertResponse,\n sendFlowHistory,\n type,\n }: {\n actionId?: string;\n deviceConfirmedOn?: WalletDevice;\n method?: string;\n origin?: string;\n requireApproval?: boolean | undefined;\n securityAlertResponse?: Record<string, unknown>;\n sendFlowHistory?: SendFlowHistoryEntry[];\n type?: TransactionType;\n } = {},\n ): Promise<Result> {\n const chainId = this.getChainId();\n const { transactions } = this.state;\n txParams = normalizeTxParams(txParams);\n const isEIP1559Compatible = await this.getEIP1559Compatibility();\n validateTxParams(txParams, isEIP1559Compatible);\n if (origin) {\n await validateTransactionOrigin(\n await this.getPermittedAccounts(origin),\n this.getSelectedAddress(),\n txParams.from,\n origin,\n );\n }\n\n const dappSuggestedGasFees = this.generateDappSuggestedGasFees(\n txParams,\n origin,\n );\n\n const transactionType =\n type ?? (await determineTransactionType(txParams, this.ethQuery)).type;\n\n const existingTransactionMeta = this.getTransactionWithActionId(actionId);\n // If a request to add a transaction with the same actionId is submitted again, a new transaction will not be created for it.\n const transactionMeta: TransactionMeta = existingTransactionMeta || {\n // Add actionId to txMeta to check if same actionId is seen again\n actionId,\n chainId,\n dappSuggestedGasFees,\n deviceConfirmedOn,\n id: random(),\n origin,\n securityAlertResponse,\n status: TransactionStatus.unapproved as TransactionStatus.unapproved,\n time: Date.now(),\n txParams,\n userEditedGasLimit: false,\n verifiedOnBlockchain: false,\n type: transactionType,\n };\n\n try {\n const { gas, estimateGasError } = await this.estimateGas(txParams);\n txParams.gas = gas;\n txParams.estimateGasError = estimateGasError;\n transactionMeta.originalGasEstimate = gas;\n } catch (error: any) {\n this.failTransaction(transactionMeta, error);\n return Promise.reject(error);\n }\n\n // Checks if a transaction already exists with a given actionId\n if (!existingTransactionMeta) {\n // Set security provider response\n if (method && this.securityProviderRequest) {\n const securityProviderResponse = await this.securityProviderRequest(\n transactionMeta,\n method,\n );\n transactionMeta.securityProviderResponse = securityProviderResponse;\n }\n\n if (!this.isSendFlowHistoryDisabled) {\n transactionMeta.sendFlowHistory = sendFlowHistory ?? [];\n }\n // Initial history push\n if (!this.isHistoryDisabled) {\n addInitialHistorySnapshot(transactionMeta);\n }\n transactions.push(transactionMeta);\n this.update({\n transactions: this.trimTransactionsForState(transactions),\n });\n this.hub.emit(`unapprovedTransaction`, transactionMeta);\n }\n\n return {\n result: this.processApproval(transactionMeta, {\n isExisting: Boolean(existingTransactionMeta),\n requireApproval,\n }),\n transactionMeta,\n };\n }\n\n startIncomingTransactionPolling() {\n this.incomingTransactionHelper.start();\n }\n\n stopIncomingTransactionPolling() {\n this.incomingTransactionHelper.stop();\n }\n\n async updateIncomingTransactions() {\n await this.incomingTransactionHelper.update();\n }\n\n /**\n * Creates approvals for all unapproved transactions persisted.\n */\n initApprovals() {\n const chainId = this.getChainId();\n const unapprovedTxs = this.state.transactions.filter(\n (transaction) =>\n transaction.status === TransactionStatus.unapproved &&\n transaction.chainId === chainId,\n );\n\n for (const txMeta of unapprovedTxs) {\n this.processApproval(txMeta, {\n shouldShowRequest: false,\n }).catch((error) => {\n /* istanbul ignore next */\n console.error('Error during persisted transaction approval', error);\n });\n }\n }\n\n /**\n * Attempts to cancel a transaction based on its ID by setting its status to \"rejected\"\n * and emitting a `<tx.id>:finished` hub event.\n *\n * @param transactionId - The ID of the transaction to cancel.\n * @param gasValues - The gas values to use for the cancellation transaction.\n * @param options - The options for the cancellation transaction.\n * @param options.estimatedBaseFee - The estimated base fee of the transaction.\n */\n async stopTransaction(\n transactionId: string,\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n { estimatedBaseFee }: { estimatedBaseFee?: string } = {},\n ) {\n if (gasValues) {\n validateGasValues(gasValues);\n }\n const transactionMeta = this.state.transactions.find(\n ({ id }) => id === transactionId,\n );\n if (!transactionMeta) {\n return;\n }\n\n if (!this.sign) {\n throw new Error('No sign method defined.');\n }\n\n // gasPrice (legacy non EIP1559)\n const minGasPrice = getIncreasedPriceFromExisting(\n transactionMeta.txParams.gasPrice,\n CANCEL_RATE,\n );\n\n const gasPriceFromValues = isGasPriceValue(gasValues) && gasValues.gasPrice;\n\n const newGasPrice =\n (gasPriceFromValues &&\n validateMinimumIncrease(gasPriceFromValues, minGasPrice)) ||\n minGasPrice;\n\n // maxFeePerGas (EIP1559)\n const existingMaxFeePerGas = transactionMeta.txParams?.maxFeePerGas;\n const minMaxFeePerGas = getIncreasedPriceFromExisting(\n existingMaxFeePerGas,\n CANCEL_RATE,\n );\n const maxFeePerGasValues =\n isFeeMarketEIP1559Values(gasValues) && gasValues.maxFeePerGas;\n const newMaxFeePerGas =\n (maxFeePerGasValues &&\n validateMinimumIncrease(maxFeePerGasValues, minMaxFeePerGas)) ||\n (existingMaxFeePerGas && minMaxFeePerGas);\n\n // maxPriorityFeePerGas (EIP1559)\n const existingMaxPriorityFeePerGas =\n transactionMeta.txParams?.maxPriorityFeePerGas;\n const minMaxPriorityFeePerGas = getIncreasedPriceFromExisting(\n existingMaxPriorityFeePerGas,\n CANCEL_RATE,\n );\n const maxPriorityFeePerGasValues =\n isFeeMarketEIP1559Values(gasValues) && gasValues.maxPriorityFeePerGas;\n const newMaxPriorityFeePerGas =\n (maxPriorityFeePerGasValues &&\n validateMinimumIncrease(\n maxPriorityFeePerGasValues,\n minMaxPriorityFeePerGas,\n )) ||\n (existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);\n\n const txParams =\n newMaxFeePerGas && newMaxPriorityFeePerGas\n ? {\n from: transactionMeta.txParams.from,\n gasLimit: transactionMeta.txParams.gas,\n maxFeePerGas: newMaxFeePerGas,\n maxPriorityFeePerGas: newMaxPriorityFeePerGas,\n type: 2,\n nonce: transactionMeta.txParams.nonce,\n to: transactionMeta.txParams.from,\n value: '0x0',\n }\n : {\n from: transactionMeta.txParams.from,\n gasLimit: transactionMeta.txParams.gas,\n gasPrice: newGasPrice,\n nonce: transactionMeta.txParams.nonce,\n to: transactionMeta.txParams.from,\n value: '0x0',\n };\n\n const unsignedEthTx = this.prepareUnsignedEthTx(txParams);\n\n const signedTx = await this.sign(\n unsignedEthTx,\n transactionMeta.txParams.from,\n );\n await this.updateTransactionMetaRSV(transactionMeta, signedTx);\n const rawTx = bufferToHex(signedTx.serialize());\n await query(this.ethQuery, 'sendRawTransaction', [rawTx]);\n transactionMeta.estimatedBaseFee = estimatedBaseFee;\n transactionMeta.status = TransactionStatus.cancelled;\n this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);\n }\n\n /**\n * Attempts to speed up a transaction increasing transaction gasPrice by ten percent.\n *\n * @param transactionId - The ID of the transaction to speed up.\n * @param gasValues - The gas values to use for the speed up transaction.\n * @param options - The options for the speed up transaction.\n * @param options.actionId - Unique ID to prevent duplicate requests\n * @param options.estimatedBaseFee - The estimated base fee of the transaction.\n */\n async speedUpTransaction(\n transactionId: string,\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n {\n actionId,\n estimatedBaseFee,\n }: { actionId?: string; estimatedBaseFee?: string } = {},\n ) {\n // If transaction is found for same action id, do not create a new speed up transaction.\n if (this.getTransactionWithActionId(actionId)) {\n return;\n }\n\n if (gasValues) {\n validateGasValues(gasValues);\n }\n const transactionMeta = this.state.transactions.find(\n ({ id }) => id === transactionId,\n );\n /* istanbul ignore next */\n if (!transactionMeta) {\n return;\n }\n\n /* istanbul ignore next */\n if (!this.sign) {\n throw new Error('No sign method defined.');\n }\n\n const { transactions } = this.state;\n\n // gasPrice (legacy non EIP1559)\n const minGasPrice = getIncreasedPriceFromExisting(\n transactionMeta.txParams.gasPrice,\n SPEED_UP_RATE,\n );\n\n const gasPriceFromValues = isGasPriceValue(gasValues) && gasValues.gasPrice;\n\n const newGasPrice =\n (gasPriceFromValues &&\n validateMinimumIncrease(gasPriceFromValues, minGasPrice)) ||\n minGasPrice;\n\n // maxFeePerGas (EIP1559)\n const existingMaxFeePerGas = transactionMeta.txParams?.maxFeePerGas;\n const minMaxFeePerGas = getIncreasedPriceFromExisting(\n existingMaxFeePerGas,\n SPEED_UP_RATE,\n );\n const maxFeePerGasValues =\n isFeeMarketEIP1559Values(gasValues) && gasValues.maxFeePerGas;\n const newMaxFeePerGas =\n (maxFeePerGasValues &&\n validateMinimumIncrease(maxFeePerGasValues, minMaxFeePerGas)) ||\n (existingMaxFeePerGas && minMaxFeePerGas);\n\n // maxPriorityFeePerGas (EIP1559)\n const existingMaxPriorityFeePerGas =\n transactionMeta.txParams?.maxPriorityFeePerGas;\n const minMaxPriorityFeePerGas = getIncreasedPriceFromExisting(\n existingMaxPriorityFeePerGas,\n SPEED_UP_RATE,\n );\n const maxPriorityFeePerGasValues =\n isFeeMarketEIP1559Values(gasValues) && gasValues.maxPriorityFeePerGas;\n const newMaxPriorityFeePerGas =\n (maxPriorityFeePerGasValues &&\n validateMinimumIncrease(\n maxPriorityFeePerGasValues,\n minMaxPriorityFeePerGas,\n )) ||\n (existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);\n\n const txParams =\n newMaxFeePerGas && newMaxPriorityFeePerGas\n ? {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n maxFeePerGas: newMaxFeePerGas,\n maxPriorityFeePerGas: newMaxPriorityFeePerGas,\n type: 2,\n }\n : {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n gasPrice: newGasPrice,\n };\n\n const unsignedEthTx = this.prepareUnsignedEthTx(txParams);\n\n const signedTx = await this.sign(\n unsignedEthTx,\n transactionMeta.txParams.from,\n );\n await this.updateTransactionMetaRSV(transactionMeta, signedTx);\n const rawTx = bufferToHex(signedTx.serialize());\n const hash = await query(this.ethQuery, 'sendRawTransaction', [rawTx]);\n const baseTransactionMeta = {\n ...transactionMeta,\n estimatedBaseFee,\n id: random(),\n time: Date.now(),\n hash,\n actionId,\n originalGasEstimate: transactionMeta.txParams.gas,\n type: TransactionType.retry,\n };\n const newTransactionMeta =\n newMaxFeePerGas && newMaxPriorityFeePerGas\n ? {\n ...baseTransactionMeta,\n txParams: {\n ...transactionMeta.txParams,\n maxFeePerGas: newMaxFeePerGas,\n maxPriorityFeePerGas: newMaxPriorityFeePerGas,\n },\n }\n : {\n ...baseTransactionMeta,\n txParams: {\n ...transactionMeta.txParams,\n gasPrice: newGasPrice,\n },\n };\n transactions.push(newTransactionMeta);\n this.update({ transactions: this.trimTransactionsForState(transactions) });\n this.hub.emit(`${transactionMeta.id}:speedup`, newTransactionMeta);\n }\n\n /**\n * Estimates required gas for a given transaction.\n *\n * @param transaction - The transaction to estimate gas for.\n * @returns The gas and gas price.\n */\n async estimateGas(transaction: TransactionParams) {\n const estimatedTransaction = { ...transaction };\n const {\n gas,\n gasPrice: providedGasPrice,\n to,\n value,\n data,\n } = estimatedTransaction;\n const gasPrice =\n typeof providedGasPrice === 'undefined'\n ? await query(this.ethQuery, 'gasPrice')\n : providedGasPrice;\n const { providerConfig } = this.getNetworkState();\n const isCustomNetwork = providerConfig.type === NetworkType.rpc;\n // 1. If gas is already defined on the transaction, use it\n if (typeof gas !== 'undefined') {\n return { gas, gasPrice };\n }\n const { gasLimit } = await query(this.ethQuery, 'getBlockByNumber', [\n 'latest',\n false,\n ]);\n\n // 2. If to is not defined or this is not a contract address, and there is no data use 0x5208 / 21000.\n // If the network is a custom network then bypass this check and fetch 'estimateGas'.\n /* istanbul ignore next */\n const code = to ? await query(this.ethQuery, 'getCode', [to]) : undefined;\n /* istanbul ignore next */\n if (\n !isCustomNetwork &&\n (!to || (to && !data && (!code || code === '0x')))\n ) {\n return { gas: '0x5208', gasPrice };\n }\n\n // if data, should be hex string format\n estimatedTransaction.data = !data\n ? data\n : /* istanbul ignore next */ addHexPrefix(data);\n\n // 3. If this is a contract address, safely estimate gas using RPC\n estimatedTransaction.value =\n typeof value === 'undefined' ? '0x0' : /* istanbul ignore next */ value;\n const gasLimitBN = hexToBN(gasLimit);\n estimatedTransaction.gas = BNToHex(fractionBN(gasLimitBN, 19, 20));\n\n let gasHex;\n let estimateGasError;\n try {\n gasHex = await query(this.ethQuery, 'estimateGas', [\n estimatedTransaction,\n ]);\n } catch (error) {\n estimateGasError = ESTIMATE_GAS_ERROR;\n }\n // 4. Pad estimated gas without exceeding the most recent block gasLimit. If the network is a\n // a custom network then return the eth_estimateGas value.\n const gasBN = hexToBN(gasHex);\n const maxGasBN = gasLimitBN.muln(0.9);\n const paddedGasBN = gasBN.muln(1.5);\n /* istanbul ignore next */\n if (gasBN.gt(maxGasBN) || isCustomNetwork) {\n return { gas: addHexPrefix(gasHex), gasPrice, estimateGasError };\n }\n\n /* istanbul ignore next */\n if (paddedGasBN.lt(maxGasBN)) {\n return {\n gas: addHexPrefix(BNToHex(paddedGasBN)),\n gasPrice,\n estimateGasError,\n };\n }\n return { gas: addHexPrefix(BNToHex(maxGasBN)), gasPrice, estimateGasError };\n }\n\n /**\n * Updates an existing transaction in state.\n *\n * @param transactionMeta - The new transaction to store in state.\n * @param note - A note or update reason to include in the transaction history.\n */\n updateTransaction(transactionMeta: TransactionMeta, note: string) {\n const { transactions } = this.state;\n transactionMeta.txParams = normalizeTxParams(transactionMeta.txParams);\n validateTxParams(transactionMeta.txParams);\n if (!this.isHistoryDisabled) {\n updateTransactionHistory(transactionMeta, note);\n }\n const index = transactions.findIndex(({ id }) => transactionMeta.id === id);\n transactions[index] = transactionMeta;\n this.update({ transactions: this.trimTransactionsForState(transactions) });\n }\n\n /**\n * Removes all transactions from state, optionally based on the current network.\n *\n * @param ignoreNetwork - Determines whether to wipe all transactions, or just those on the\n * current network. If `true`, all transactions are wiped.\n * @param address - If specified, only transactions originating from this address will be\n * wiped on current network.\n */\n wipeTransactions(ignoreNetwork?: boolean, address?: string) {\n /* istanbul ignore next */\n if (ignoreNetwork && !address) {\n this.update({ transactions: [] });\n return;\n }\n const currentChainId = this.getChainId();\n const newTransactions = this.state.transactions.filter(\n ({ chainId, txParams }) => {\n const isMatchingNetwork = ignoreNetwork || chainId === currentChainId;\n\n if (!isMatchingNetwork) {\n return true;\n }\n\n const isMatchingAddress =\n !address || txParams.from?.toLowerCase() === address.toLowerCase();\n\n return !isMatchingAddress;\n },\n );\n\n this.update({\n transactions: this.trimTransactionsForState(newTransactions),\n });\n }\n\n startIncomingTransactionProcessing() {\n this.incomingTransactionHelper.start();\n }\n\n stopIncomingTransactionProcessing() {\n this.incomingTransactionHelper.stop();\n }\n\n /**\n * Adds external provided transaction to state as confirmed transaction.\n *\n * @param transactionMeta - TransactionMeta to add transactions.\n * @param transactionReceipt - TransactionReceipt of the external transaction.\n * @param baseFeePerGas - Base fee per gas of the external transaction.\n */\n async confirmExternalTransaction(\n transactionMeta: TransactionMeta,\n transactionReceipt: TransactionReceipt,\n baseFeePerGas: Hex,\n ) {\n // Run validation and add external transaction to state.\n this.addExternalTransaction(transactionMeta);\n\n try {\n const transactionId = transactionMeta.id;\n\n // Make sure status is confirmed and define gasUsed as in receipt.\n transactionMeta.status = TransactionStatus.confirmed;\n transactionMeta.txReceipt = transactionReceipt;\n if (baseFeePerGas) {\n transactionMeta.baseFeePerGas = baseFeePerGas;\n }\n\n // Update same nonce local transactions as dropped and define replacedBy properties.\n this.markNonceDuplicatesDropped(transactionId);\n\n // Update external provided transaction with updated gas values and confirmed status.\n this.updateTransaction(\n transactionMeta,\n 'TransactionController:confirmExternalTransaction - Add external transaction',\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n /**\n * Append new send flow history to a transaction.\n *\n * @param transactionID - The ID of the transaction to update.\n * @param currentSendFlowHistoryLength - The length of the current sendFlowHistory array.\n * @param sendFlowHistoryToAdd - The sendFlowHistory entries to add.\n * @returns The updated transactionMeta.\n */\n updateTransactionSendFlowHistory(\n transactionID: string,\n currentSendFlowHistoryLength: number,\n sendFlowHistoryToAdd: SendFlowHistoryEntry[],\n ): TransactionMeta {\n if (this.isSendFlowHistoryDisabled) {\n throw new Error(\n 'Send flow history is disabled for the current transaction controller',\n );\n }\n\n const transactionMeta = this.getTransaction(transactionID);\n\n if (!transactionMeta) {\n throw new Error(\n `Cannot update send flow history as no transaction metadata found`,\n );\n }\n\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateTransactionSendFlowHistory',\n );\n\n if (\n currentSendFlowHistoryLength ===\n (transactionMeta?.sendFlowHistory?.length || 0)\n ) {\n transactionMeta.sendFlowHistory = [\n ...(transactionMeta?.sendFlowHistory ?? []),\n ...sendFlowHistoryToAdd,\n ];\n this.updateTransaction(\n transactionMeta,\n 'TransactionController:updateTransactionSendFlowHistory - sendFlowHistory updated',\n );\n }\n\n return this.getTransaction(transactionID) as TransactionMeta;\n }\n\n /**\n * Update the gas values of a transaction.\n *\n * @param transactionId - The ID of the transaction to update.\n * @param gasValues - Gas values to update.\n * @param gasValues.gas - Same as transaction.gasLimit.\n * @param gasValues.gasLimit - Maxmimum number of units of gas to use for this transaction.\n * @param gasValues.gasPrice - Price per gas for legacy transactions.\n * @param gasValues.maxPriorityFeePerGas - Maximum amount per gas to give to validator as incentive.\n * @param gasValues.maxFeePerGas - Maximum amount per gas to pay for the transaction, including the priority fee.\n * @param gasValues.estimateUsed - Which estimate level was used.\n * @param gasValues.estimateSuggested - Which estimate level that the API suggested.\n * @param gasValues.defaultGasEstimates - The default estimate for gas.\n * @param gasValues.originalGasEstimate - Original estimate for gas.\n * @param gasValues.userEditedGasLimit - The gas limit supplied by user.\n * @param gasValues.userFeeLevel - Estimate level user selected.\n * @returns The updated transactionMeta.\n */\n updateTransactionGasFees(\n transactionId: string,\n {\n defaultGasEstimates,\n estimateUsed,\n estimateSuggested,\n gas,\n gasLimit,\n gasPrice,\n maxPriorityFeePerGas,\n maxFeePerGas,\n originalGasEstimate,\n userEditedGasLimit,\n userFeeLevel,\n }: {\n defaultGasEstimates?: string;\n estimateUsed?: string;\n estimateSuggested?: string;\n gas?: string;\n gasLimit?: string;\n gasPrice?: string;\n maxPriorityFeePerGas?: string;\n maxFeePerGas?: string;\n originalGasEstimate?: string;\n userEditedGasLimit?: boolean;\n userFeeLevel?: string;\n },\n ): TransactionMeta {\n const transactionMeta = this.getTransaction(transactionId);\n\n if (!transactionMeta) {\n throw new Error(\n `Cannot update transaction as no transaction metadata found`,\n );\n }\n\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateTransactionGasFees',\n );\n\n let transactionGasFees = {\n txParams: {\n gas,\n gasLimit,\n gasPrice,\n maxPriorityFeePerGas,\n maxFeePerGas,\n },\n defaultGasEstimates,\n estimateUsed,\n estimateSuggested,\n originalGasEstimate,\n userEditedGasLimit,\n userFeeLevel,\n } as any;\n\n // only update what is defined\n transactionGasFees.txParams = pickBy(transactionGasFees.txParams);\n transactionGasFees = pickBy(transactionGasFees);\n\n // merge updated gas values with existing transaction meta\n const updatedMeta = merge(transactionMeta, transactionGasFees);\n\n this.updateTransaction(\n updatedMeta,\n 'TransactionController:updateTransactionGasFees - gas values updated',\n );\n\n return this.getTransaction(transactionId) as TransactionMeta;\n }\n\n private async processApproval(\n transactionMeta: TransactionMeta,\n {\n isExisting = false,\n requireApproval,\n shouldShowRequest = true,\n }: {\n isExisting?: boolean;\n requireApproval?: boolean | undefined;\n shouldShowRequest?: boolean;\n },\n ): Promise<string> {\n const transactionId = transactionMeta.id;\n let resultCallbacks: AcceptResultCallbacks | undefined;\n const { meta, isCompleted } = this.isTransactionCompleted(transactionId);\n const finishedPromise = isCompleted\n ? Promise.resolve(meta)\n : this.waitForTransactionFinished(transactionId);\n\n if (meta && !isExisting && !isCompleted) {\n try {\n if (requireApproval !== false) {\n const acceptResult = await this.requestApproval(transactionMeta, {\n shouldShowRequest,\n });\n resultCallbacks = acceptResult.resultCallbacks;\n }\n\n const { isCompleted: isTxCompleted } =\n this.isTransactionCompleted(transactionId);\n\n if (!isTxCompleted) {\n await this.approveTransaction(transactionId);\n }\n } catch (error: any) {\n const { isCompleted: isTxCompleted } =\n this.isTransactionCompleted(transactionId);\n if (!isTxCompleted) {\n if (error.code === errorCodes.provider.userRejectedRequest) {\n this.cancelTransaction(transactionId);\n\n throw providerErrors.userRejectedRequest(\n 'User rejected the transaction',\n );\n } else {\n this.failTransaction(meta, error);\n }\n }\n }\n }\n\n const finalMeta = await finishedPromise;\n\n switch (finalMeta?.status) {\n case TransactionStatus.failed:\n resultCallbacks?.error(finalMeta.error);\n throw rpcErrors.internal(finalMeta.error.message);\n\n case TransactionStatus.cancelled:\n const cancelError = rpcErrors.internal(\n 'User cancelled the transaction',\n );\n\n resultCallbacks?.error(cancelError);\n throw cancelError;\n\n case TransactionStatus.submitted:\n resultCallbacks?.success();\n return finalMeta.hash as string;\n\n default:\n const internalError = rpcErrors.internal(\n `MetaMask Tx Signature: Unknown problem: ${JSON.stringify(\n finalMeta || transactionId,\n )}`,\n );\n\n resultCallbacks?.error(internalError);\n throw internalError;\n }\n }\n\n /**\n * Approves a transaction and updates it's status in state. If this is not a\n * retry transaction, a nonce will be generated. The transaction is signed\n * using the sign configuration property, then published to the blockchain.\n * A `<tx.id>:finished` hub event is fired after success or failure.\n *\n * @param transactionId - The ID of the transaction to approve.\n */\n private async approveTransaction(transactionId: string) {\n const { transactions } = this.state;\n const releaseLock = await this.mutex.acquire();\n const chainId = this.getChainId();\n const index = transactions.findIndex(({ id }) => transactionId === id);\n const transactionMeta = transactions[index];\n const {\n txParams: { nonce, from },\n } = transactionMeta;\n let nonceLock;\n try {\n if (!this.sign) {\n releaseLock();\n this.failTransaction(\n transactionMeta,\n new Error('No sign method defined.'),\n );\n return;\n } else if (!chainId) {\n releaseLock();\n this.failTransaction(transactionMeta, new Error('No chainId defined.'));\n return;\n }\n\n const { approved: status } = TransactionStatus;\n let nonceToUse = nonce;\n // if a nonce already exists on the transactionMeta it means this is a speedup or cancel transaction\n // so we want to reuse that nonce and hope that it beats the previous attempt to chain. Otherwise use a new locked nonce\n if (!nonceToUse) {\n nonceLock = await this.nonceTracker.getNonceLock(from);\n nonceToUse = addHexPrefix(nonceLock.nextNonce.toString(16));\n }\n\n transactionMeta.status = status;\n transactionMeta.txParams.nonce = nonceToUse;\n transactionMeta.txParams.chainId = chainId;\n\n const baseTxParams = {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n };\n\n const isEIP1559 = isEIP1559Transaction(transactionMeta.txParams);\n\n const txParams = isEIP1559\n ? {\n ...baseTxParams,\n maxFeePerGas: transactionMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: transactionMeta.txParams.maxPriorityFeePerGas,\n estimatedBaseFee: transactionMeta.txParams.estimatedBaseFee,\n // specify type 2 if maxFeePerGas and maxPriorityFeePerGas are set\n type: 2,\n }\n : baseTxParams;\n\n // delete gasPrice if maxFeePerGas and maxPriorityFeePerGas are set\n if (isEIP1559) {\n delete txParams.gasPrice;\n }\n\n const unsignedEthTx = this.prepareUnsignedEthTx(txParams);\n const signedTx = await this.sign(unsignedEthTx, from);\n await this.updateTransactionMetaRSV(transactionMeta, signedTx);\n transactionMeta.status = TransactionStatus.signed;\n this.updateTransaction(\n transactionMeta,\n 'TransactionController#approveTransaction - Transaction signed',\n );\n\n const rawTx = bufferToHex(signedTx.serialize());\n transactionMeta.rawTx = rawTx;\n this.updateTransaction(\n transactionMeta,\n 'TransactionController#approveTransaction - RawTransaction added',\n );\n const hash = await query(this.ethQuery, 'sendRawTransaction', [rawTx]);\n transactionMeta.hash = hash;\n transactionMeta.status = TransactionStatus.submitted;\n transactionMeta.submittedTime = new Date().getTime();\n this.updateTransaction(\n transactionMeta,\n 'TransactionController#approveTransaction - Transaction submitted',\n );\n this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);\n } catch (error: any) {\n this.failTransaction(transactionMeta, error);\n } finally {\n // must set transaction to submitted/failed before releasing lock\n if (nonceLock) {\n nonceLock.releaseLock();\n }\n releaseLock();\n }\n }\n\n /**\n * Cancels a transaction based on its ID by setting its status to \"rejected\"\n * and emitting a `<tx.id>:finished` hub event.\n *\n * @param transactionId - The ID of the transaction to cancel.\n */\n private cancelTransaction(transactionId: string) {\n const transactionMeta = this.state.transactions.find(\n ({ id }) => id === transactionId,\n );\n if (!transactionMeta) {\n return;\n }\n transactionMeta.status = TransactionStatus.rejected;\n this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);\n const transactions = this.state.transactions.filter(\n ({ id }) => id !== transactionId,\n );\n this.update({ transactions: this.trimTransactionsForState(transactions) });\n }\n\n /**\n * Trim the amount of transactions that are set on the state. Checks\n * if the length of the tx history is longer then desired persistence\n * limit and then if it is removes the oldest confirmed or rejected tx.\n * Pending or unapproved transactions will not be removed by this\n * operation. For safety of presenting a fully functional transaction UI\n * representation, this function will not break apart transactions with the\n * same nonce, created on the same day, per network. Not accounting for transactions of the same\n * nonce, same day and network combo can result in confusing or broken experiences\n * in the UI. The transactions are then updated using the BaseController update.\n *\n * @param transactions - The transactions to be applied to the state.\n * @returns The trimmed list of transactions.\n */\n private trimTransactionsForState(\n transactions: TransactionMeta[],\n ): TransactionMeta[] {\n const nonceNetworkSet = new Set();\n\n const txsToKeep = transactions\n .sort((a, b) => (a.time > b.time ? -1 : 1)) // Descending time order\n .filter((tx) => {\n const { chainId, status, txParams, time } = tx;\n\n if (txParams) {\n const key = `${txParams.nonce}-${convertHexToDecimal(\n chainId,\n )}-${new Date(time).toDateString()}`;\n\n if (nonceNetworkSet.has(key)) {\n return true;\n } else if (\n nonceNetworkSet.size < this.config.txHistoryLimit ||\n !this.isFinalState(status)\n ) {\n nonceNetworkSet.add(key);\n return true;\n }\n }\n\n return false;\n });\n\n txsToKeep.reverse(); // Ascending time order\n return txsToKeep;\n }\n\n /**\n * Determines if the transaction is in a final state.\n *\n * @param status - The transaction status.\n * @returns Whether the transaction is in a final state.\n */\n private isFinalState(status: TransactionStatus): boolean {\n return (\n status === TransactionStatus.rejected ||\n status === TransactionStatus.confirmed ||\n status === TransactionStatus.failed ||\n status === TransactionStatus.cancelled\n );\n }\n\n /**\n * Whether the transaction has at least completed all local processing.\n *\n * @param status - The transaction status.\n * @returns Whether the transaction is in a final state.\n */\n private isLocalFinalState(status: TransactionStatus): boolean {\n return [\n TransactionStatus.cancelled,\n TransactionStatus.confirmed,\n TransactionStatus.failed,\n TransactionStatus.rejected,\n TransactionStatus.submitted,\n ].includes(status);\n }\n\n private async requestApproval(\n txMeta: TransactionMeta,\n { shouldShowRequest }: { shouldShowRequest: boolean },\n ): Promise<AddResult> {\n const id = this.getApprovalId(txMeta);\n const { origin } = txMeta;\n const type = ApprovalType.Transaction;\n const requestData = { txId: txMeta.id };\n\n return (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n id,\n origin: origin || ORIGIN_METAMASK,\n type,\n requestData,\n expectsResult: true,\n },\n shouldShowRequest,\n )) as Promise<AddResult>;\n }\n\n private getTransaction(transactionId: string): TransactionMeta | undefined {\n const { transactions } = this.state;\n return transactions.find(({ id }) => id === transactionId);\n }\n\n private getApprovalId(txMeta: TransactionMeta) {\n return String(txMeta.id);\n }\n\n private isTransactionCompleted(transactionId: string): {\n meta?: TransactionMeta;\n isCompleted: boolean;\n } {\n const transaction = this.getTransaction(transactionId);\n\n if (!transaction) {\n return { meta: undefined, isCompleted: false };\n }\n\n const isCompleted = this.isLocalFinalState(transaction.status);\n\n return { meta: transaction, isCompleted };\n }\n\n private getChainId(): Hex {\n const { providerConfig } = this.getNetworkState();\n return providerConfig.chainId;\n }\n\n private prepareUnsignedEthTx(\n txParams: Record<string, unknown>,\n ): TypedTransaction {\n return TransactionFactory.fromTxData(txParams, {\n common: this.getCommonConfiguration(),\n freeze: false,\n });\n }\n\n /**\n * `@ethereumjs/tx` uses `@ethereumjs/common` as a configuration tool for\n * specifying which chain, network, hardfork and EIPs to support for\n * a transaction. By referencing this configuration, and analyzing the fields\n * specified in txParams, @ethereumjs/tx is able to determine which EIP-2718\n * transaction type to use.\n *\n * @returns common configuration object\n */\n private getCommonConfiguration(): Common {\n const {\n providerConfig: { type: chain, chainId, nickname: name },\n } = this.getNetworkState();\n\n if (\n chain !== RPC &&\n chain !== NetworkType['linea-goerli'] &&\n chain !== NetworkType['linea-mainnet']\n ) {\n return new Common({ chain, hardfork: HARDFORK });\n }\n\n const customChainParams: Partial<ChainConfig> = {\n name,\n chainId: parseInt(chainId, 16),\n defaultHardfork: HARDFORK,\n };\n\n return Common.custom(customChainParams);\n }\n\n private onIncomingTransactions({\n added,\n updated,\n }: {\n added: TransactionMeta[];\n updated: TransactionMeta[];\n }) {\n const { transactions: currentTransactions } = this.state;\n\n const updatedTransactions = [\n ...added,\n ...currentTransactions.map((originalTransaction) => {\n const updatedTransaction = updated.find(\n ({ hash }) => hash === originalTransaction.hash,\n );\n\n return updatedTransaction ?? originalTransaction;\n }),\n ];\n\n this.update({\n transactions: this.trimTransactionsForState(updatedTransactions),\n });\n }\n\n private onUpdatedLastFetchedBlockNumbers({\n lastFetchedBlockNumbers,\n blockNumber,\n }: {\n lastFetchedBlockNumbers: {\n [key: string]: number;\n };\n blockNumber: number;\n }) {\n this.update({ lastFetchedBlockNumbers });\n this.hub.emit('incomingTransactionBlock', blockNumber);\n }\n\n private onPendingTransactionsUpdate(transactions: TransactionMeta[]) {\n pendingTransactionsLogger('Updated pending transactions');\n this.update({ transactions: this.trimTransactionsForState(transactions) });\n }\n\n private generateDappSuggestedGasFees(\n txParams: TransactionParams,\n origin?: string,\n ): DappSuggestedGasFees | undefined {\n if (!origin || origin === ORIGIN_METAMASK) {\n return undefined;\n }\n\n const { gasPrice, maxFeePerGas, maxPriorityFeePerGas, gas } = txParams;\n\n if (\n gasPrice === undefined &&\n maxFeePerGas === undefined &&\n maxPriorityFeePerGas === undefined &&\n gas === undefined\n ) {\n return undefined;\n }\n\n const dappSuggestedGasFees: DappSuggestedGasFees = {};\n\n if (gasPrice !== undefined) {\n dappSuggestedGasFees.gasPrice = gasPrice;\n } else if (\n maxFeePerGas !== undefined ||\n maxPriorityFeePerGas !== undefined\n ) {\n dappSuggestedGasFees.maxFeePerGas = maxFeePerGas;\n dappSuggestedGasFees.maxPriorityFeePerGas = maxPriorityFeePerGas;\n }\n\n if (gas !== undefined) {\n dappSuggestedGasFees.gas = gas;\n }\n\n return dappSuggestedGasFees;\n }\n\n /**\n * Validates and adds external provided transaction to state.\n *\n * @param transactionMeta - Nominated external transaction to be added to state.\n */\n private async addExternalTransaction(transactionMeta: TransactionMeta) {\n const chainId = this.getChainId();\n const { transactions } = this.state;\n const fromAddress = transactionMeta?.txParams?.from;\n const sameFromAndNetworkTransactions = transactions.filter(\n (transaction) =>\n transaction.txParams.from === fromAddress &&\n transaction.chainId === chainId,\n );\n const confirmedTxs = sameFromAndNetworkTransactions.filter(\n (transaction) => transaction.status === TransactionStatus.confirmed,\n );\n const pendingTxs = sameFromAndNetworkTransactions.filter(\n (transaction) => transaction.status === TransactionStatus.submitted,\n );\n\n validateConfirmedExternalTransaction(\n transactionMeta,\n confirmedTxs,\n pendingTxs,\n );\n\n // Make sure provided external transaction has non empty history array\n if (!(transactionMeta.history ?? []).length) {\n if (!this.isHistoryDisabled) {\n addInitialHistorySnapshot(transactionMeta);\n }\n }\n\n const updatedTransactions = [...transactions, transactionMeta];\n this.update({\n transactions: this.trimTransactionsForState(updatedTransactions),\n });\n }\n\n /**\n * Sets other txMeta statuses to dropped if the txMeta that has been confirmed has other transactions\n * in the transactions have the same nonce.\n *\n * @param transactionId - Used to identify original transaction.\n */\n private markNonceDuplicatesDropped(transactionId: string) {\n const chainId = this.getChainId();\n const transactionMeta = this.getTransaction(transactionId);\n const nonce = transactionMeta?.txParams?.nonce;\n const from = transactionMeta?.txParams?.from;\n const sameNonceTxs = this.state.transactions.filter(\n (transaction) =>\n transaction.txParams.from === from &&\n transaction.txParams.nonce === nonce &&\n transaction.chainId === chainId,\n );\n\n if (!sameNonceTxs.length) {\n return;\n }\n\n // Mark all same nonce transactions as dropped and give it a replacedBy hash\n for (const transaction of sameNonceTxs) {\n if (transaction.id === transactionId) {\n continue;\n }\n transaction.replacedBy = transactionMeta?.hash;\n transaction.replacedById = transactionMeta?.id;\n // Drop any transaction that wasn't previously failed (off chain failure)\n if (transaction.status !== TransactionStatus.failed) {\n this.setTransactionStatusDropped(transaction);\n }\n }\n }\n\n /**\n * Method to set transaction status to dropped.\n *\n * @param transactionMeta - TransactionMeta of transaction to be marked as dropped.\n */\n private setTransactionStatusDropped(transactionMeta: TransactionMeta) {\n transactionMeta.status = TransactionStatus.dropped;\n this.updateTransaction(\n transactionMeta,\n 'TransactionController#setTransactionStatusDropped - Transaction dropped',\n );\n }\n\n /**\n * Get transaction with provided actionId.\n *\n * @param actionId - Unique ID to prevent duplicate requests\n * @returns the filtered transaction\n */\n private getTransactionWithActionId(actionId?: string) {\n return this.state.transactions.find(\n (transaction) => actionId && transaction.actionId === actionId,\n );\n }\n\n private async waitForTransactionFinished(\n transactionId: string,\n ): Promise<TransactionMeta> {\n return new Promise((resolve) => {\n this.hub.once(`${transactionId}:finished`, (txMeta) => {\n resolve(txMeta);\n });\n });\n }\n\n /**\n * Updates the r, s, and v properties of a TransactionMeta object\n * with values from a signed transaction.\n *\n * @param transactionMeta - The TransactionMeta object to update.\n * @param signedTx - The encompassing type for all transaction types containing r, s, and v values.\n */\n private async updateTransactionMetaRSV(\n transactionMeta: TransactionMeta,\n signedTx: TypedTransaction,\n ): Promise<void> {\n if (signedTx.r) {\n transactionMeta.r = addHexPrefix(signedTx.r.toString(16));\n }\n\n if (signedTx.s) {\n transactionMeta.s = addHexPrefix(signedTx.s.toString(16));\n }\n\n if (signedTx.v) {\n transactionMeta.v = addHexPrefix(signedTx.v.toString(16));\n }\n }\n\n private async getEIP1559Compatibility() {\n const currentNetworkIsEIP1559Compatible =\n await this.getCurrentNetworkEIP1559Compatibility();\n const currentAccountIsEIP1559Compatible =\n this.getCurrentAccountEIP1559Compatibility?.() ?? true;\n\n return (\n currentNetworkIsEIP1559Compatible && currentAccountIsEIP1559Compatible\n );\n }\n}\n\nexport default TransactionController;\n"]}
|
|
1
|
+
{"version":3,"file":"TransactionController.js","sourceRoot":"","sources":["../src/TransactionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+CAAwE;AAExE,uCAAoD;AAWpD,+DAA2D;AAC3D,iEAOoC;AACpC,oEAA2C;AAO3C,qDAA6E;AAE7E,6CAAoC;AACpC,8EAAiD;AACjD,qDAA4D;AAC5D,mCAAsC;AACtC,mCAAuC;AACvC,kEAAyC;AAEzC,+BAAoC;AAEpC,iGAA8F;AAC9F,mFAAgF;AAChF,mFAAgF;AAChF,qCAAqD;AAUrD,mCAA6D;AAC7D,yEAAqF;AACrF,qCAAqD;AACrD,+CAAiD;AACjD,6CAGyB;AACzB,+DAAoE;AACpE,yCAUuB;AACvB,mDAG4B;AAEf,QAAA,QAAQ,GAAG,iBAAQ,CAAC,MAAM,CAAC;AA0DxC;;GAEG;AACU,QAAA,WAAW,GAAG,GAAG,CAAC;AAE/B;;GAEG;AACU,QAAA,aAAa,GAAG,GAAG,CAAC;AAEjC;;GAEG;AACH,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAkB/C;;GAEG;AACH,MAAa,qBAAsB,SAAQ,gCAG1C;IA0EC;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,YACE,EACE,YAAY,EACZ,cAAc,EACd,sBAAsB,EACtB,qCAAqC,EACrC,qCAAqC,EACrC,kBAAkB,EAClB,eAAe,EACf,oBAAoB,EACpB,kBAAkB,EAClB,oBAAoB,GAAG,EAAE,EACzB,SAAS,EACT,oBAAoB,EACpB,QAAQ,EACR,uBAAuB,GAqBxB,EACD,MAAmC,EACnC,KAAiC;QAEjC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QA5HN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AC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;aAC3D;YAED,IAAI,QAAQ,CAAC,CAAC,EAAE;gBACd,eAAe,CAAC,CAAC,GAAG,IAAA,8BAAY,EAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;aAC3D;YAED,IAAI,QAAQ,CAAC,CAAC,EAAE;gBACd,eAAe,CAAC,CAAC,GAAG,IAAA,8BAAY,EAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;aAC3D;QACH,CAAC;KAAA;IAEa,uBAAuB;;;YACnC,MAAM,iCAAiC,GACrC,MAAM,IAAI,CAAC,qCAAqC,EAAE,CAAC;YACrD,MAAM,iCAAiC,GACrC,MAAA,MAAA,IAAI,CAAC,qCAAqC,oDAAI,mCAAI,IAAI,CAAC;YAEzD,OAAO,CACL,iCAAiC,IAAI,iCAAiC,CACvE,CAAC;;KACH;CACF;AApgDD,sDAogDC;AAED,kBAAe,qBAAqB,CAAC","sourcesContent":["import { Hardfork, Common, type ChainConfig } from '@ethereumjs/common';\nimport type { TypedTransaction } from '@ethereumjs/tx';\nimport { TransactionFactory } from '@ethereumjs/tx';\nimport type {\n AcceptResultCallbacks,\n AddApprovalRequest,\n AddResult,\n} from '@metamask/approval-controller';\nimport type {\n BaseConfig,\n BaseState,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n query,\n NetworkType,\n RPC,\n ApprovalType,\n ORIGIN_METAMASK,\n convertHexToDecimal,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type { GasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n BlockTracker,\n NetworkState,\n Provider,\n} from '@metamask/network-controller';\nimport { errorCodes, rpcErrors, providerErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport MethodRegistry from 'eth-method-registry';\nimport { addHexPrefix, bufferToHex } from 'ethereumjs-util';\nimport { EventEmitter } from 'events';\nimport { merge, pickBy } from 'lodash';\nimport NonceTracker from 'nonce-tracker';\nimport type { NonceLock } from 'nonce-tracker/dist/NonceTracker';\nimport { v1 as random } from 'uuid';\n\nimport { EtherscanRemoteTransactionSource } from './helpers/EtherscanRemoteTransactionSource';\nimport { IncomingTransactionHelper } from './helpers/IncomingTransactionHelper';\nimport { PendingTransactionTracker } from './helpers/PendingTransactionTracker';\nimport { pendingTransactionsLogger } from './logger';\nimport type {\n DappSuggestedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionReceipt,\n SecurityProviderRequest,\n SendFlowHistoryEntry,\n WalletDevice,\n} from './types';\nimport { TransactionType, TransactionStatus } from './types';\nimport { validateConfirmedExternalTransaction } from './utils/external-transactions';\nimport { estimateGas, updateGas } from './utils/gas';\nimport { updateGasFees } from './utils/gas-fees';\nimport {\n addInitialHistorySnapshot,\n updateTransactionHistory,\n} from './utils/history';\nimport { determineTransactionType } from './utils/transaction-type';\nimport {\n getAndFormatTransactionsForNonceTracker,\n getIncreasedPriceFromExisting,\n normalizeTxParams,\n isEIP1559Transaction,\n isFeeMarketEIP1559Values,\n isGasPriceValue,\n validateGasValues,\n validateIfTransactionUnapproved,\n validateMinimumIncrease,\n} from './utils/utils';\nimport {\n validateTransactionOrigin,\n validateTxParams,\n} from './utils/validation';\n\nexport const HARDFORK = Hardfork.London;\n\n/**\n * @type Result\n * @property result - Promise resolving to a new transaction hash\n * @property transactionMeta - Meta information about this new transaction\n */\nexport interface Result {\n result: Promise<string>;\n transactionMeta: TransactionMeta;\n}\n\nexport interface GasPriceValue {\n gasPrice: string;\n}\n\nexport interface FeeMarketEIP1559Values {\n maxFeePerGas: string;\n maxPriorityFeePerGas: string;\n}\n\n/**\n * @type TransactionConfig\n *\n * Transaction controller configuration\n * @property provider - Provider used to create a new underlying EthQuery instance\n * @property sign - Method used to sign transactions\n */\nexport interface TransactionConfig extends BaseConfig {\n sign?: (txParams: TransactionParams, from: string) => Promise<any>;\n txHistoryLimit: number;\n}\n\n/**\n * @type MethodData\n *\n * Method data registry object\n * @property registryMethod - Registry method raw string\n * @property parsedRegistryMethod - Registry method object, containing name and method arguments\n */\nexport interface MethodData {\n registryMethod: string;\n parsedRegistryMethod: Record<string, unknown>;\n}\n\n/**\n * @type TransactionState\n *\n * Transaction controller state\n * @property transactions - A list of TransactionMeta objects\n * @property methodData - Object containing all known method data information\n */\nexport interface TransactionState extends BaseState {\n transactions: TransactionMeta[];\n methodData: { [key: string]: MethodData };\n lastFetchedBlockNumbers: { [key: string]: number };\n}\n\n/**\n * Multiplier used to determine a transaction's increased gas fee during cancellation\n */\nexport const CANCEL_RATE = 1.5;\n\n/**\n * Multiplier used to determine a transaction's increased gas fee during speed up\n */\nexport const SPEED_UP_RATE = 1.1;\n\n/**\n * The name of the {@link TransactionController}.\n */\nconst controllerName = 'TransactionController';\n\n/**\n * The external actions available to the {@link TransactionController}.\n */\ntype AllowedActions = AddApprovalRequest;\n\n/**\n * The messenger of the {@link TransactionController}.\n */\nexport type TransactionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n never,\n AllowedActions['type'],\n never\n>;\n\n/**\n * Controller responsible for submitting and managing transactions.\n */\nexport class TransactionController extends BaseController<\n TransactionConfig,\n TransactionState\n> {\n private ethQuery: EthQuery;\n\n private readonly isHistoryDisabled: boolean;\n\n private readonly isSendFlowHistoryDisabled: boolean;\n\n private readonly nonceTracker: NonceTracker;\n\n private registry: any;\n\n private readonly provider: Provider;\n\n private readonly handle?: ReturnType<typeof setTimeout>;\n\n private readonly mutex = new Mutex();\n\n private readonly getNetworkState: () => NetworkState;\n\n private readonly getCurrentAccountEIP1559Compatibility: () => Promise<boolean>;\n\n private readonly getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;\n\n private readonly getGasFeeEstimates: () => Promise<GasFeeState>;\n\n private readonly getPermittedAccounts: (origin?: string) => Promise<string[]>;\n\n private readonly getSelectedAddress: () => string;\n\n private readonly messagingSystem: TransactionControllerMessenger;\n\n private readonly incomingTransactionHelper: IncomingTransactionHelper;\n\n private readonly securityProviderRequest?: SecurityProviderRequest;\n\n private readonly pendingTransactionTracker: PendingTransactionTracker;\n\n private failTransaction(transactionMeta: TransactionMeta, error: Error) {\n const newTransactionMeta = {\n ...transactionMeta,\n error,\n status: TransactionStatus.failed,\n };\n this.updateTransaction(\n newTransactionMeta,\n 'TransactionController#failTransaction - Add error message and set status to failed',\n );\n this.hub.emit(`${transactionMeta.id}:finished`, newTransactionMeta);\n }\n\n private async registryLookup(fourBytePrefix: string): Promise<MethodData> {\n const registryMethod = await this.registry.lookup(fourBytePrefix);\n const parsedRegistryMethod = this.registry.parse(registryMethod);\n return { registryMethod, parsedRegistryMethod };\n }\n\n /**\n * EventEmitter instance used to listen to specific transactional events\n */\n hub = new EventEmitter();\n\n /**\n * Name of this controller used during composition\n */\n override name = 'TransactionController';\n\n /**\n * Method used to sign transactions\n */\n sign?: (\n transaction: TypedTransaction,\n from: string,\n ) => Promise<TypedTransaction>;\n\n /**\n * Creates a TransactionController instance.\n *\n * @param options - The controller options.\n * @param options.blockTracker - The block tracker used to poll for new blocks data.\n * @param options.disableHistory - Whether to disable storing history in transaction metadata.\n * @param options.disableSendFlowHistory - Explicitly disable transaction metadata history.\n * @param options.getCurrentAccountEIP1559Compatibility - Whether or not the account supports EIP-1559.\n * @param options.getCurrentNetworkEIP1559Compatibility - Whether or not the network supports EIP-1559.\n * @param options.getGasFeeEstimates - Callback to retrieve gas fee estimates.\n * @param options.getNetworkState - Gets the state of the network controller.\n * @param options.getPermittedAccounts - Get accounts that a given origin has permissions for.\n * @param options.getSelectedAddress - Gets the address of the currently selected account.\n * @param options.incomingTransactions - Configuration options for incoming transaction support.\n * @param options.incomingTransactions.includeTokenTransfers - Whether or not to include ERC20 token transfers.\n * @param options.incomingTransactions.isEnabled - Whether or not incoming transaction retrieval is enabled.\n * @param options.incomingTransactions.queryEntireHistory - Whether to initially query the entire transaction history or only recent blocks.\n * @param options.incomingTransactions.updateTransactions - Whether to update local transactions using remote transaction data.\n * @param options.messenger - The controller messenger.\n * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.\n * @param options.provider - The provider used to create the underlying EthQuery instance.\n * @param options.securityProviderRequest - A function for verifying a transaction, whether it is malicious or not.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n blockTracker,\n disableHistory,\n disableSendFlowHistory,\n getCurrentAccountEIP1559Compatibility,\n getCurrentNetworkEIP1559Compatibility,\n getGasFeeEstimates,\n getNetworkState,\n getPermittedAccounts,\n getSelectedAddress,\n incomingTransactions = {},\n messenger,\n onNetworkStateChange,\n provider,\n securityProviderRequest,\n }: {\n blockTracker: BlockTracker;\n disableHistory: boolean;\n disableSendFlowHistory: boolean;\n getCurrentAccountEIP1559Compatibility: () => Promise<boolean>;\n getCurrentNetworkEIP1559Compatibility: () => Promise<boolean>;\n getGasFeeEstimates?: () => Promise<GasFeeState>;\n getNetworkState: () => NetworkState;\n getPermittedAccounts: (origin?: string) => Promise<string[]>;\n getSelectedAddress: () => string;\n incomingTransactions: {\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n updateTransactions?: boolean;\n };\n messenger: TransactionControllerMessenger;\n onNetworkStateChange: (listener: (state: NetworkState) => void) => void;\n provider: Provider;\n securityProviderRequest?: SecurityProviderRequest;\n },\n config?: Partial<TransactionConfig>,\n state?: Partial<TransactionState>,\n ) {\n super(config, state);\n\n this.defaultConfig = {\n txHistoryLimit: 40,\n };\n\n this.defaultState = {\n methodData: {},\n transactions: [],\n lastFetchedBlockNumbers: {},\n };\n\n this.initialize();\n\n this.provider = provider;\n this.messagingSystem = messenger;\n this.getNetworkState = getNetworkState;\n // @ts-expect-error TODO: Provider type alignment\n this.ethQuery = new EthQuery(provider);\n this.isSendFlowHistoryDisabled = disableSendFlowHistory ?? false;\n this.isHistoryDisabled = disableHistory ?? false;\n this.registry = new MethodRegistry({ provider });\n this.getCurrentAccountEIP1559Compatibility =\n getCurrentAccountEIP1559Compatibility;\n this.getCurrentNetworkEIP1559Compatibility =\n getCurrentNetworkEIP1559Compatibility;\n this.getGasFeeEstimates =\n getGasFeeEstimates || (() => Promise.resolve({} as GasFeeState));\n this.getPermittedAccounts = getPermittedAccounts;\n this.getSelectedAddress = getSelectedAddress;\n this.securityProviderRequest = securityProviderRequest;\n\n this.nonceTracker = new NonceTracker({\n provider,\n blockTracker,\n getPendingTransactions: (address) =>\n getAndFormatTransactionsForNonceTracker(\n address,\n TransactionStatus.submitted,\n this.state.transactions,\n ),\n getConfirmedTransactions: (address) =>\n getAndFormatTransactionsForNonceTracker(\n address,\n TransactionStatus.confirmed,\n this.state.transactions,\n ),\n });\n\n this.incomingTransactionHelper = new IncomingTransactionHelper({\n blockTracker,\n getCurrentAccount: getSelectedAddress,\n getLastFetchedBlockNumbers: () => this.state.lastFetchedBlockNumbers,\n getNetworkState,\n isEnabled: incomingTransactions.isEnabled,\n queryEntireHistory: incomingTransactions.queryEntireHistory,\n remoteTransactionSource: new EtherscanRemoteTransactionSource({\n includeTokenTransfers: incomingTransactions.includeTokenTransfers,\n }),\n transactionLimit: this.config.txHistoryLimit,\n updateTransactions: incomingTransactions.updateTransactions,\n });\n\n this.incomingTransactionHelper.hub.on(\n 'transactions',\n this.onIncomingTransactions.bind(this),\n );\n\n this.incomingTransactionHelper.hub.on(\n 'updatedLastFetchedBlockNumbers',\n this.onUpdatedLastFetchedBlockNumbers.bind(this),\n );\n\n this.pendingTransactionTracker = new PendingTransactionTracker({\n blockTracker,\n failTransaction: this.failTransaction.bind(this),\n getChainId: this.getChainId.bind(this),\n getEthQuery: () => this.ethQuery,\n getTransactions: () => this.state.transactions,\n nonceTracker: this.nonceTracker,\n });\n\n this.pendingTransactionTracker.hub.on(\n 'transactions',\n this.onPendingTransactionsUpdate.bind(this),\n );\n\n this.pendingTransactionTracker.hub.on(\n 'transaction-confirmed',\n (transactionMeta: TransactionMeta) =>\n this.hub.emit(`${transactionMeta.id}:confirmed`, transactionMeta),\n );\n\n onNetworkStateChange(() => {\n // @ts-expect-error TODO: Provider type alignment\n this.ethQuery = new EthQuery(this.provider);\n this.registry = new MethodRegistry({ provider: this.provider });\n });\n\n this.pendingTransactionTracker.start();\n }\n\n /**\n * Handle new method data request.\n *\n * @param fourBytePrefix - The method prefix.\n * @returns The method data object corresponding to the given signature prefix.\n */\n async handleMethodData(fourBytePrefix: string): Promise<MethodData> {\n const releaseLock = await this.mutex.acquire();\n try {\n const { methodData } = this.state;\n const knownMethod = Object.keys(methodData).find(\n (knownFourBytePrefix) => fourBytePrefix === knownFourBytePrefix,\n );\n if (knownMethod) {\n return methodData[fourBytePrefix];\n }\n const registry = await this.registryLookup(fourBytePrefix);\n this.update({\n methodData: { ...methodData, ...{ [fourBytePrefix]: registry } },\n });\n return registry;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Add a new unapproved transaction to state. Parameters will be validated, a\n * unique transaction id will be generated, and gas and gasPrice will be calculated\n * if not provided. If A `<tx.id>:unapproved` hub event will be emitted once added.\n *\n * @param txParams - Standard parameters for an Ethereum transaction.\n * @param opts - Additional options to control how the transaction is added.\n * @param opts.actionId - Unique ID to prevent duplicate requests.\n * @param opts.deviceConfirmedOn - An enum to indicate what device confirmed the transaction.\n * @param opts.method - RPC method that requested the transaction.\n * @param opts.origin - The origin of the transaction request, such as a dApp hostname.\n * @param opts.requireApproval - Whether the transaction requires approval by the user, defaults to true unless explicitly disabled.\n * @param opts.securityAlertResponse - Response from security validator.\n * @param opts.sendFlowHistory - The sendFlowHistory entries to add.\n * @param opts.type - Type of transaction to add, such as 'cancel' or 'swap'.\n * @returns Object containing a promise resolving to the transaction hash if approved.\n */\n async addTransaction(\n txParams: TransactionParams,\n {\n actionId,\n deviceConfirmedOn,\n method,\n origin,\n requireApproval,\n securityAlertResponse,\n sendFlowHistory,\n type,\n }: {\n actionId?: string;\n deviceConfirmedOn?: WalletDevice;\n method?: string;\n origin?: string;\n requireApproval?: boolean | undefined;\n securityAlertResponse?: Record<string, unknown>;\n sendFlowHistory?: SendFlowHistoryEntry[];\n type?: TransactionType;\n } = {},\n ): Promise<Result> {\n const chainId = this.getChainId();\n const { transactions } = this.state;\n txParams = normalizeTxParams(txParams);\n const isEIP1559Compatible = await this.getEIP1559Compatibility();\n validateTxParams(txParams, isEIP1559Compatible);\n if (origin) {\n await validateTransactionOrigin(\n await this.getPermittedAccounts(origin),\n this.getSelectedAddress(),\n txParams.from,\n origin,\n );\n }\n\n const dappSuggestedGasFees = this.generateDappSuggestedGasFees(\n txParams,\n origin,\n );\n\n const transactionType =\n type ?? (await determineTransactionType(txParams, this.ethQuery)).type;\n\n const existingTransactionMeta = this.getTransactionWithActionId(actionId);\n // If a request to add a transaction with the same actionId is submitted again, a new transaction will not be created for it.\n const transactionMeta: TransactionMeta = existingTransactionMeta || {\n // Add actionId to txMeta to check if same actionId is seen again\n actionId,\n chainId,\n dappSuggestedGasFees,\n deviceConfirmedOn,\n id: random(),\n origin,\n securityAlertResponse,\n status: TransactionStatus.unapproved as TransactionStatus.unapproved,\n time: Date.now(),\n txParams,\n userEditedGasLimit: false,\n verifiedOnBlockchain: false,\n type: transactionType,\n };\n\n await updateGas({\n ethQuery: this.ethQuery,\n providerConfig: this.getNetworkState().providerConfig,\n txMeta: transactionMeta,\n });\n\n await updateGasFees({\n eip1559: isEIP1559Compatible,\n ethQuery: this.ethQuery,\n getGasFeeEstimates: this.getGasFeeEstimates.bind(this),\n txMeta: transactionMeta,\n });\n\n // Checks if a transaction already exists with a given actionId\n if (!existingTransactionMeta) {\n // Set security provider response\n if (method && this.securityProviderRequest) {\n const securityProviderResponse = await this.securityProviderRequest(\n transactionMeta,\n method,\n );\n transactionMeta.securityProviderResponse = securityProviderResponse;\n }\n\n if (!this.isSendFlowHistoryDisabled) {\n transactionMeta.sendFlowHistory = sendFlowHistory ?? [];\n }\n // Initial history push\n if (!this.isHistoryDisabled) {\n addInitialHistorySnapshot(transactionMeta);\n }\n transactions.push(transactionMeta);\n this.update({\n transactions: this.trimTransactionsForState(transactions),\n });\n this.hub.emit(`unapprovedTransaction`, transactionMeta);\n }\n\n return {\n result: this.processApproval(transactionMeta, {\n isExisting: Boolean(existingTransactionMeta),\n requireApproval,\n }),\n transactionMeta,\n };\n }\n\n startIncomingTransactionPolling() {\n this.incomingTransactionHelper.start();\n }\n\n stopIncomingTransactionPolling() {\n this.incomingTransactionHelper.stop();\n }\n\n async updateIncomingTransactions() {\n await this.incomingTransactionHelper.update();\n }\n\n /**\n * Creates approvals for all unapproved transactions persisted.\n */\n initApprovals() {\n const chainId = this.getChainId();\n const unapprovedTxs = this.state.transactions.filter(\n (transaction) =>\n transaction.status === TransactionStatus.unapproved &&\n transaction.chainId === chainId,\n );\n\n for (const txMeta of unapprovedTxs) {\n this.processApproval(txMeta, {\n shouldShowRequest: false,\n }).catch((error) => {\n /* istanbul ignore next */\n console.error('Error during persisted transaction approval', error);\n });\n }\n }\n\n /**\n * Attempts to cancel a transaction based on its ID by setting its status to \"rejected\"\n * and emitting a `<tx.id>:finished` hub event.\n *\n * @param transactionId - The ID of the transaction to cancel.\n * @param gasValues - The gas values to use for the cancellation transaction.\n * @param options - The options for the cancellation transaction.\n * @param options.estimatedBaseFee - The estimated base fee of the transaction.\n */\n async stopTransaction(\n transactionId: string,\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n { estimatedBaseFee }: { estimatedBaseFee?: string } = {},\n ) {\n if (gasValues) {\n validateGasValues(gasValues);\n }\n const transactionMeta = this.state.transactions.find(\n ({ id }) => id === transactionId,\n );\n if (!transactionMeta) {\n return;\n }\n\n if (!this.sign) {\n throw new Error('No sign method defined.');\n }\n\n // gasPrice (legacy non EIP1559)\n const minGasPrice = getIncreasedPriceFromExisting(\n transactionMeta.txParams.gasPrice,\n CANCEL_RATE,\n );\n\n const gasPriceFromValues = isGasPriceValue(gasValues) && gasValues.gasPrice;\n\n const newGasPrice =\n (gasPriceFromValues &&\n validateMinimumIncrease(gasPriceFromValues, minGasPrice)) ||\n minGasPrice;\n\n // maxFeePerGas (EIP1559)\n const existingMaxFeePerGas = transactionMeta.txParams?.maxFeePerGas;\n const minMaxFeePerGas = getIncreasedPriceFromExisting(\n existingMaxFeePerGas,\n CANCEL_RATE,\n );\n const maxFeePerGasValues =\n isFeeMarketEIP1559Values(gasValues) && gasValues.maxFeePerGas;\n const newMaxFeePerGas =\n (maxFeePerGasValues &&\n validateMinimumIncrease(maxFeePerGasValues, minMaxFeePerGas)) ||\n (existingMaxFeePerGas && minMaxFeePerGas);\n\n // maxPriorityFeePerGas (EIP1559)\n const existingMaxPriorityFeePerGas =\n transactionMeta.txParams?.maxPriorityFeePerGas;\n const minMaxPriorityFeePerGas = getIncreasedPriceFromExisting(\n existingMaxPriorityFeePerGas,\n CANCEL_RATE,\n );\n const maxPriorityFeePerGasValues =\n isFeeMarketEIP1559Values(gasValues) && gasValues.maxPriorityFeePerGas;\n const newMaxPriorityFeePerGas =\n (maxPriorityFeePerGasValues &&\n validateMinimumIncrease(\n maxPriorityFeePerGasValues,\n minMaxPriorityFeePerGas,\n )) ||\n (existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);\n\n const txParams =\n newMaxFeePerGas && newMaxPriorityFeePerGas\n ? {\n from: transactionMeta.txParams.from,\n gasLimit: transactionMeta.txParams.gas,\n maxFeePerGas: newMaxFeePerGas,\n maxPriorityFeePerGas: newMaxPriorityFeePerGas,\n type: 2,\n nonce: transactionMeta.txParams.nonce,\n to: transactionMeta.txParams.from,\n value: '0x0',\n }\n : {\n from: transactionMeta.txParams.from,\n gasLimit: transactionMeta.txParams.gas,\n gasPrice: newGasPrice,\n nonce: transactionMeta.txParams.nonce,\n to: transactionMeta.txParams.from,\n value: '0x0',\n };\n\n const unsignedEthTx = this.prepareUnsignedEthTx(txParams);\n\n const signedTx = await this.sign(\n unsignedEthTx,\n transactionMeta.txParams.from,\n );\n await this.updateTransactionMetaRSV(transactionMeta, signedTx);\n const rawTx = bufferToHex(signedTx.serialize());\n await query(this.ethQuery, 'sendRawTransaction', [rawTx]);\n transactionMeta.estimatedBaseFee = estimatedBaseFee;\n transactionMeta.status = TransactionStatus.cancelled;\n this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);\n }\n\n /**\n * Attempts to speed up a transaction increasing transaction gasPrice by ten percent.\n *\n * @param transactionId - The ID of the transaction to speed up.\n * @param gasValues - The gas values to use for the speed up transaction.\n * @param options - The options for the speed up transaction.\n * @param options.actionId - Unique ID to prevent duplicate requests\n * @param options.estimatedBaseFee - The estimated base fee of the transaction.\n */\n async speedUpTransaction(\n transactionId: string,\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n {\n actionId,\n estimatedBaseFee,\n }: { actionId?: string; estimatedBaseFee?: string } = {},\n ) {\n // If transaction is found for same action id, do not create a new speed up transaction.\n if (this.getTransactionWithActionId(actionId)) {\n return;\n }\n\n if (gasValues) {\n validateGasValues(gasValues);\n }\n const transactionMeta = this.state.transactions.find(\n ({ id }) => id === transactionId,\n );\n /* istanbul ignore next */\n if (!transactionMeta) {\n return;\n }\n\n /* istanbul ignore next */\n if (!this.sign) {\n throw new Error('No sign method defined.');\n }\n\n const { transactions } = this.state;\n\n // gasPrice (legacy non EIP1559)\n const minGasPrice = getIncreasedPriceFromExisting(\n transactionMeta.txParams.gasPrice,\n SPEED_UP_RATE,\n );\n\n const gasPriceFromValues = isGasPriceValue(gasValues) && gasValues.gasPrice;\n\n const newGasPrice =\n (gasPriceFromValues &&\n validateMinimumIncrease(gasPriceFromValues, minGasPrice)) ||\n minGasPrice;\n\n // maxFeePerGas (EIP1559)\n const existingMaxFeePerGas = transactionMeta.txParams?.maxFeePerGas;\n const minMaxFeePerGas = getIncreasedPriceFromExisting(\n existingMaxFeePerGas,\n SPEED_UP_RATE,\n );\n const maxFeePerGasValues =\n isFeeMarketEIP1559Values(gasValues) && gasValues.maxFeePerGas;\n const newMaxFeePerGas =\n (maxFeePerGasValues &&\n validateMinimumIncrease(maxFeePerGasValues, minMaxFeePerGas)) ||\n (existingMaxFeePerGas && minMaxFeePerGas);\n\n // maxPriorityFeePerGas (EIP1559)\n const existingMaxPriorityFeePerGas =\n transactionMeta.txParams?.maxPriorityFeePerGas;\n const minMaxPriorityFeePerGas = getIncreasedPriceFromExisting(\n existingMaxPriorityFeePerGas,\n SPEED_UP_RATE,\n );\n const maxPriorityFeePerGasValues =\n isFeeMarketEIP1559Values(gasValues) && gasValues.maxPriorityFeePerGas;\n const newMaxPriorityFeePerGas =\n (maxPriorityFeePerGasValues &&\n validateMinimumIncrease(\n maxPriorityFeePerGasValues,\n minMaxPriorityFeePerGas,\n )) ||\n (existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);\n\n const txParams =\n newMaxFeePerGas && newMaxPriorityFeePerGas\n ? {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n maxFeePerGas: newMaxFeePerGas,\n maxPriorityFeePerGas: newMaxPriorityFeePerGas,\n type: 2,\n }\n : {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n gasPrice: newGasPrice,\n };\n\n const unsignedEthTx = this.prepareUnsignedEthTx(txParams);\n\n const signedTx = await this.sign(\n unsignedEthTx,\n transactionMeta.txParams.from,\n );\n await this.updateTransactionMetaRSV(transactionMeta, signedTx);\n const rawTx = bufferToHex(signedTx.serialize());\n const hash = await query(this.ethQuery, 'sendRawTransaction', [rawTx]);\n const baseTransactionMeta = {\n ...transactionMeta,\n estimatedBaseFee,\n id: random(),\n time: Date.now(),\n hash,\n actionId,\n originalGasEstimate: transactionMeta.txParams.gas,\n type: TransactionType.retry,\n };\n const newTransactionMeta =\n newMaxFeePerGas && newMaxPriorityFeePerGas\n ? {\n ...baseTransactionMeta,\n txParams: {\n ...transactionMeta.txParams,\n maxFeePerGas: newMaxFeePerGas,\n maxPriorityFeePerGas: newMaxPriorityFeePerGas,\n },\n }\n : {\n ...baseTransactionMeta,\n txParams: {\n ...transactionMeta.txParams,\n gasPrice: newGasPrice,\n },\n };\n transactions.push(newTransactionMeta);\n this.update({ transactions: this.trimTransactionsForState(transactions) });\n this.hub.emit(`${transactionMeta.id}:speedup`, newTransactionMeta);\n }\n\n /**\n * Estimates required gas for a given transaction.\n *\n * @param transaction - The transaction to estimate gas for.\n * @returns The gas and gas price.\n */\n async estimateGas(transaction: TransactionParams) {\n const { estimatedGas, simulationFails } = await estimateGas(\n transaction,\n this.ethQuery,\n );\n\n return { gas: estimatedGas, simulationFails };\n }\n\n /**\n * Updates an existing transaction in state.\n *\n * @param transactionMeta - The new transaction to store in state.\n * @param note - A note or update reason to include in the transaction history.\n */\n updateTransaction(transactionMeta: TransactionMeta, note: string) {\n const { transactions } = this.state;\n transactionMeta.txParams = normalizeTxParams(transactionMeta.txParams);\n validateTxParams(transactionMeta.txParams);\n if (!this.isHistoryDisabled) {\n updateTransactionHistory(transactionMeta, note);\n }\n const index = transactions.findIndex(({ id }) => transactionMeta.id === id);\n transactions[index] = transactionMeta;\n this.update({ transactions: this.trimTransactionsForState(transactions) });\n }\n\n /**\n * Removes all transactions from state, optionally based on the current network.\n *\n * @param ignoreNetwork - Determines whether to wipe all transactions, or just those on the\n * current network. If `true`, all transactions are wiped.\n * @param address - If specified, only transactions originating from this address will be\n * wiped on current network.\n */\n wipeTransactions(ignoreNetwork?: boolean, address?: string) {\n /* istanbul ignore next */\n if (ignoreNetwork && !address) {\n this.update({ transactions: [] });\n return;\n }\n const currentChainId = this.getChainId();\n const newTransactions = this.state.transactions.filter(\n ({ chainId, txParams }) => {\n const isMatchingNetwork = ignoreNetwork || chainId === currentChainId;\n\n if (!isMatchingNetwork) {\n return true;\n }\n\n const isMatchingAddress =\n !address || txParams.from?.toLowerCase() === address.toLowerCase();\n\n return !isMatchingAddress;\n },\n );\n\n this.update({\n transactions: this.trimTransactionsForState(newTransactions),\n });\n }\n\n startIncomingTransactionProcessing() {\n this.incomingTransactionHelper.start();\n }\n\n stopIncomingTransactionProcessing() {\n this.incomingTransactionHelper.stop();\n }\n\n /**\n * Adds external provided transaction to state as confirmed transaction.\n *\n * @param transactionMeta - TransactionMeta to add transactions.\n * @param transactionReceipt - TransactionReceipt of the external transaction.\n * @param baseFeePerGas - Base fee per gas of the external transaction.\n */\n async confirmExternalTransaction(\n transactionMeta: TransactionMeta,\n transactionReceipt: TransactionReceipt,\n baseFeePerGas: Hex,\n ) {\n // Run validation and add external transaction to state.\n this.addExternalTransaction(transactionMeta);\n\n try {\n const transactionId = transactionMeta.id;\n\n // Make sure status is confirmed and define gasUsed as in receipt.\n transactionMeta.status = TransactionStatus.confirmed;\n transactionMeta.txReceipt = transactionReceipt;\n if (baseFeePerGas) {\n transactionMeta.baseFeePerGas = baseFeePerGas;\n }\n\n // Update same nonce local transactions as dropped and define replacedBy properties.\n this.markNonceDuplicatesDropped(transactionId);\n\n // Update external provided transaction with updated gas values and confirmed status.\n this.updateTransaction(\n transactionMeta,\n 'TransactionController:confirmExternalTransaction - Add external transaction',\n );\n } catch (error) {\n console.error(error);\n }\n }\n\n /**\n * Append new send flow history to a transaction.\n *\n * @param transactionID - The ID of the transaction to update.\n * @param currentSendFlowHistoryLength - The length of the current sendFlowHistory array.\n * @param sendFlowHistoryToAdd - The sendFlowHistory entries to add.\n * @returns The updated transactionMeta.\n */\n updateTransactionSendFlowHistory(\n transactionID: string,\n currentSendFlowHistoryLength: number,\n sendFlowHistoryToAdd: SendFlowHistoryEntry[],\n ): TransactionMeta {\n if (this.isSendFlowHistoryDisabled) {\n throw new Error(\n 'Send flow history is disabled for the current transaction controller',\n );\n }\n\n const transactionMeta = this.getTransaction(transactionID);\n\n if (!transactionMeta) {\n throw new Error(\n `Cannot update send flow history as no transaction metadata found`,\n );\n }\n\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateTransactionSendFlowHistory',\n );\n\n if (\n currentSendFlowHistoryLength ===\n (transactionMeta?.sendFlowHistory?.length || 0)\n ) {\n transactionMeta.sendFlowHistory = [\n ...(transactionMeta?.sendFlowHistory ?? []),\n ...sendFlowHistoryToAdd,\n ];\n this.updateTransaction(\n transactionMeta,\n 'TransactionController:updateTransactionSendFlowHistory - sendFlowHistory updated',\n );\n }\n\n return this.getTransaction(transactionID) as TransactionMeta;\n }\n\n /**\n * Update the gas values of a transaction.\n *\n * @param transactionId - The ID of the transaction to update.\n * @param gasValues - Gas values to update.\n * @param gasValues.gas - Same as transaction.gasLimit.\n * @param gasValues.gasLimit - Maxmimum number of units of gas to use for this transaction.\n * @param gasValues.gasPrice - Price per gas for legacy transactions.\n * @param gasValues.maxPriorityFeePerGas - Maximum amount per gas to give to validator as incentive.\n * @param gasValues.maxFeePerGas - Maximum amount per gas to pay for the transaction, including the priority fee.\n * @param gasValues.estimateUsed - Which estimate level was used.\n * @param gasValues.estimateSuggested - Which estimate level that the API suggested.\n * @param gasValues.defaultGasEstimates - The default estimate for gas.\n * @param gasValues.originalGasEstimate - Original estimate for gas.\n * @param gasValues.userEditedGasLimit - The gas limit supplied by user.\n * @param gasValues.userFeeLevel - Estimate level user selected.\n * @returns The updated transactionMeta.\n */\n updateTransactionGasFees(\n transactionId: string,\n {\n defaultGasEstimates,\n estimateUsed,\n estimateSuggested,\n gas,\n gasLimit,\n gasPrice,\n maxPriorityFeePerGas,\n maxFeePerGas,\n originalGasEstimate,\n userEditedGasLimit,\n userFeeLevel,\n }: {\n defaultGasEstimates?: string;\n estimateUsed?: string;\n estimateSuggested?: string;\n gas?: string;\n gasLimit?: string;\n gasPrice?: string;\n maxPriorityFeePerGas?: string;\n maxFeePerGas?: string;\n originalGasEstimate?: string;\n userEditedGasLimit?: boolean;\n userFeeLevel?: string;\n },\n ): TransactionMeta {\n const transactionMeta = this.getTransaction(transactionId);\n\n if (!transactionMeta) {\n throw new Error(\n `Cannot update transaction as no transaction metadata found`,\n );\n }\n\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateTransactionGasFees',\n );\n\n let transactionGasFees = {\n txParams: {\n gas,\n gasLimit,\n gasPrice,\n maxPriorityFeePerGas,\n maxFeePerGas,\n },\n defaultGasEstimates,\n estimateUsed,\n estimateSuggested,\n originalGasEstimate,\n userEditedGasLimit,\n userFeeLevel,\n } as any;\n\n // only update what is defined\n transactionGasFees.txParams = pickBy(transactionGasFees.txParams);\n transactionGasFees = pickBy(transactionGasFees);\n\n // merge updated gas values with existing transaction meta\n const updatedMeta = merge(transactionMeta, transactionGasFees);\n\n this.updateTransaction(\n updatedMeta,\n 'TransactionController:updateTransactionGasFees - gas values updated',\n );\n\n return this.getTransaction(transactionId) as TransactionMeta;\n }\n\n /**\n * Gets the next nonce according to the nonce-tracker.\n * Ensure `releaseLock` is called once processing of the `nonce` value is complete.\n *\n * @param address - The hex string address for the transaction.\n * @returns object with the `nextNonce` `nonceDetails`, and the releaseLock.\n */\n async getNonceLock(address: string): Promise<NonceLock> {\n return this.nonceTracker.getNonceLock(address);\n }\n\n private async processApproval(\n transactionMeta: TransactionMeta,\n {\n isExisting = false,\n requireApproval,\n shouldShowRequest = true,\n }: {\n isExisting?: boolean;\n requireApproval?: boolean | undefined;\n shouldShowRequest?: boolean;\n },\n ): Promise<string> {\n const transactionId = transactionMeta.id;\n let resultCallbacks: AcceptResultCallbacks | undefined;\n const { meta, isCompleted } = this.isTransactionCompleted(transactionId);\n const finishedPromise = isCompleted\n ? Promise.resolve(meta)\n : this.waitForTransactionFinished(transactionId);\n\n if (meta && !isExisting && !isCompleted) {\n try {\n if (requireApproval !== false) {\n const acceptResult = await this.requestApproval(transactionMeta, {\n shouldShowRequest,\n });\n resultCallbacks = acceptResult.resultCallbacks;\n }\n\n const { isCompleted: isTxCompleted } =\n this.isTransactionCompleted(transactionId);\n\n if (!isTxCompleted) {\n await this.approveTransaction(transactionId);\n }\n } catch (error: any) {\n const { isCompleted: isTxCompleted } =\n this.isTransactionCompleted(transactionId);\n if (!isTxCompleted) {\n if (error.code === errorCodes.provider.userRejectedRequest) {\n this.cancelTransaction(transactionId);\n\n throw providerErrors.userRejectedRequest(\n 'User rejected the transaction',\n );\n } else {\n this.failTransaction(meta, error);\n }\n }\n }\n }\n\n const finalMeta = await finishedPromise;\n\n switch (finalMeta?.status) {\n case TransactionStatus.failed:\n resultCallbacks?.error(finalMeta.error);\n throw rpcErrors.internal(finalMeta.error.message);\n\n case TransactionStatus.cancelled:\n const cancelError = rpcErrors.internal(\n 'User cancelled the transaction',\n );\n\n resultCallbacks?.error(cancelError);\n throw cancelError;\n\n case TransactionStatus.submitted:\n resultCallbacks?.success();\n return finalMeta.hash as string;\n\n default:\n const internalError = rpcErrors.internal(\n `MetaMask Tx Signature: Unknown problem: ${JSON.stringify(\n finalMeta || transactionId,\n )}`,\n );\n\n resultCallbacks?.error(internalError);\n throw internalError;\n }\n }\n\n /**\n * Approves a transaction and updates it's status in state. If this is not a\n * retry transaction, a nonce will be generated. The transaction is signed\n * using the sign configuration property, then published to the blockchain.\n * A `<tx.id>:finished` hub event is fired after success or failure.\n *\n * @param transactionId - The ID of the transaction to approve.\n */\n private async approveTransaction(transactionId: string) {\n const { transactions } = this.state;\n const releaseLock = await this.mutex.acquire();\n const chainId = this.getChainId();\n const index = transactions.findIndex(({ id }) => transactionId === id);\n const transactionMeta = transactions[index];\n const {\n txParams: { nonce, from },\n } = transactionMeta;\n let nonceLock;\n try {\n if (!this.sign) {\n releaseLock();\n this.failTransaction(\n transactionMeta,\n new Error('No sign method defined.'),\n );\n return;\n } else if (!chainId) {\n releaseLock();\n this.failTransaction(transactionMeta, new Error('No chainId defined.'));\n return;\n }\n\n const { approved: status } = TransactionStatus;\n let nonceToUse = nonce;\n // if a nonce already exists on the transactionMeta it means this is a speedup or cancel transaction\n // so we want to reuse that nonce and hope that it beats the previous attempt to chain. Otherwise use a new locked nonce\n if (!nonceToUse) {\n nonceLock = await this.nonceTracker.getNonceLock(from);\n nonceToUse = addHexPrefix(nonceLock.nextNonce.toString(16));\n }\n\n transactionMeta.status = status;\n transactionMeta.txParams.nonce = nonceToUse;\n transactionMeta.txParams.chainId = chainId;\n\n const baseTxParams = {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n };\n\n const isEIP1559 = isEIP1559Transaction(transactionMeta.txParams);\n\n const txParams = isEIP1559\n ? {\n ...baseTxParams,\n maxFeePerGas: transactionMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: transactionMeta.txParams.maxPriorityFeePerGas,\n estimatedBaseFee: transactionMeta.txParams.estimatedBaseFee,\n // specify type 2 if maxFeePerGas and maxPriorityFeePerGas are set\n type: 2,\n }\n : baseTxParams;\n\n // delete gasPrice if maxFeePerGas and maxPriorityFeePerGas are set\n if (isEIP1559) {\n delete txParams.gasPrice;\n }\n\n const unsignedEthTx = this.prepareUnsignedEthTx(txParams);\n const signedTx = await this.sign(unsignedEthTx, from);\n await this.updateTransactionMetaRSV(transactionMeta, signedTx);\n transactionMeta.status = TransactionStatus.signed;\n this.updateTransaction(\n transactionMeta,\n 'TransactionController#approveTransaction - Transaction signed',\n );\n\n const rawTx = bufferToHex(signedTx.serialize());\n transactionMeta.rawTx = rawTx;\n this.updateTransaction(\n transactionMeta,\n 'TransactionController#approveTransaction - RawTransaction added',\n );\n const hash = await query(this.ethQuery, 'sendRawTransaction', [rawTx]);\n transactionMeta.hash = hash;\n transactionMeta.status = TransactionStatus.submitted;\n transactionMeta.submittedTime = new Date().getTime();\n this.updateTransaction(\n transactionMeta,\n 'TransactionController#approveTransaction - Transaction submitted',\n );\n this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);\n } catch (error: any) {\n this.failTransaction(transactionMeta, error);\n } finally {\n // must set transaction to submitted/failed before releasing lock\n if (nonceLock) {\n nonceLock.releaseLock();\n }\n releaseLock();\n }\n }\n\n /**\n * Cancels a transaction based on its ID by setting its status to \"rejected\"\n * and emitting a `<tx.id>:finished` hub event.\n *\n * @param transactionId - The ID of the transaction to cancel.\n */\n private cancelTransaction(transactionId: string) {\n const transactionMeta = this.state.transactions.find(\n ({ id }) => id === transactionId,\n );\n if (!transactionMeta) {\n return;\n }\n transactionMeta.status = TransactionStatus.rejected;\n this.hub.emit(`${transactionMeta.id}:finished`, transactionMeta);\n const transactions = this.state.transactions.filter(\n ({ id }) => id !== transactionId,\n );\n this.update({ transactions: this.trimTransactionsForState(transactions) });\n }\n\n /**\n * Trim the amount of transactions that are set on the state. Checks\n * if the length of the tx history is longer then desired persistence\n * limit and then if it is removes the oldest confirmed or rejected tx.\n * Pending or unapproved transactions will not be removed by this\n * operation. For safety of presenting a fully functional transaction UI\n * representation, this function will not break apart transactions with the\n * same nonce, created on the same day, per network. Not accounting for transactions of the same\n * nonce, same day and network combo can result in confusing or broken experiences\n * in the UI. The transactions are then updated using the BaseController update.\n *\n * @param transactions - The transactions to be applied to the state.\n * @returns The trimmed list of transactions.\n */\n private trimTransactionsForState(\n transactions: TransactionMeta[],\n ): TransactionMeta[] {\n const nonceNetworkSet = new Set();\n\n const txsToKeep = transactions\n .sort((a, b) => (a.time > b.time ? -1 : 1)) // Descending time order\n .filter((tx) => {\n const { chainId, status, txParams, time } = tx;\n\n if (txParams) {\n const key = `${txParams.nonce}-${convertHexToDecimal(\n chainId,\n )}-${new Date(time).toDateString()}`;\n\n if (nonceNetworkSet.has(key)) {\n return true;\n } else if (\n nonceNetworkSet.size < this.config.txHistoryLimit ||\n !this.isFinalState(status)\n ) {\n nonceNetworkSet.add(key);\n return true;\n }\n }\n\n return false;\n });\n\n txsToKeep.reverse(); // Ascending time order\n return txsToKeep;\n }\n\n /**\n * Determines if the transaction is in a final state.\n *\n * @param status - The transaction status.\n * @returns Whether the transaction is in a final state.\n */\n private isFinalState(status: TransactionStatus): boolean {\n return (\n status === TransactionStatus.rejected ||\n status === TransactionStatus.confirmed ||\n status === TransactionStatus.failed ||\n status === TransactionStatus.cancelled\n );\n }\n\n /**\n * Whether the transaction has at least completed all local processing.\n *\n * @param status - The transaction status.\n * @returns Whether the transaction is in a final state.\n */\n private isLocalFinalState(status: TransactionStatus): boolean {\n return [\n TransactionStatus.cancelled,\n TransactionStatus.confirmed,\n TransactionStatus.failed,\n TransactionStatus.rejected,\n TransactionStatus.submitted,\n ].includes(status);\n }\n\n private async requestApproval(\n txMeta: TransactionMeta,\n { shouldShowRequest }: { shouldShowRequest: boolean },\n ): Promise<AddResult> {\n const id = this.getApprovalId(txMeta);\n const { origin } = txMeta;\n const type = ApprovalType.Transaction;\n const requestData = { txId: txMeta.id };\n\n return (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n id,\n origin: origin || ORIGIN_METAMASK,\n type,\n requestData,\n expectsResult: true,\n },\n shouldShowRequest,\n )) as Promise<AddResult>;\n }\n\n private getTransaction(transactionId: string): TransactionMeta | undefined {\n const { transactions } = this.state;\n return transactions.find(({ id }) => id === transactionId);\n }\n\n private getApprovalId(txMeta: TransactionMeta) {\n return String(txMeta.id);\n }\n\n private isTransactionCompleted(transactionId: string): {\n meta?: TransactionMeta;\n isCompleted: boolean;\n } {\n const transaction = this.getTransaction(transactionId);\n\n if (!transaction) {\n return { meta: undefined, isCompleted: false };\n }\n\n const isCompleted = this.isLocalFinalState(transaction.status);\n\n return { meta: transaction, isCompleted };\n }\n\n private getChainId(): Hex {\n const { providerConfig } = this.getNetworkState();\n return providerConfig.chainId;\n }\n\n private prepareUnsignedEthTx(\n txParams: Record<string, unknown>,\n ): TypedTransaction {\n return TransactionFactory.fromTxData(txParams, {\n common: this.getCommonConfiguration(),\n freeze: false,\n });\n }\n\n /**\n * `@ethereumjs/tx` uses `@ethereumjs/common` as a configuration tool for\n * specifying which chain, network, hardfork and EIPs to support for\n * a transaction. By referencing this configuration, and analyzing the fields\n * specified in txParams, @ethereumjs/tx is able to determine which EIP-2718\n * transaction type to use.\n *\n * @returns common configuration object\n */\n private getCommonConfiguration(): Common {\n const {\n providerConfig: { type: chain, chainId, nickname: name },\n } = this.getNetworkState();\n\n if (\n chain !== RPC &&\n chain !== NetworkType['linea-goerli'] &&\n chain !== NetworkType['linea-mainnet']\n ) {\n return new Common({ chain, hardfork: HARDFORK });\n }\n\n const customChainParams: Partial<ChainConfig> = {\n name,\n chainId: parseInt(chainId, 16),\n defaultHardfork: HARDFORK,\n };\n\n return Common.custom(customChainParams);\n }\n\n private onIncomingTransactions({\n added,\n updated,\n }: {\n added: TransactionMeta[];\n updated: TransactionMeta[];\n }) {\n const { transactions: currentTransactions } = this.state;\n\n const updatedTransactions = [\n ...added,\n ...currentTransactions.map((originalTransaction) => {\n const updatedTransaction = updated.find(\n ({ hash }) => hash === originalTransaction.hash,\n );\n\n return updatedTransaction ?? originalTransaction;\n }),\n ];\n\n this.update({\n transactions: this.trimTransactionsForState(updatedTransactions),\n });\n }\n\n private onUpdatedLastFetchedBlockNumbers({\n lastFetchedBlockNumbers,\n blockNumber,\n }: {\n lastFetchedBlockNumbers: {\n [key: string]: number;\n };\n blockNumber: number;\n }) {\n this.update({ lastFetchedBlockNumbers });\n this.hub.emit('incomingTransactionBlock', blockNumber);\n }\n\n private onPendingTransactionsUpdate(transactions: TransactionMeta[]) {\n pendingTransactionsLogger('Updated pending transactions');\n this.update({ transactions: this.trimTransactionsForState(transactions) });\n }\n\n private generateDappSuggestedGasFees(\n txParams: TransactionParams,\n origin?: string,\n ): DappSuggestedGasFees | undefined {\n if (!origin || origin === ORIGIN_METAMASK) {\n return undefined;\n }\n\n const { gasPrice, maxFeePerGas, maxPriorityFeePerGas, gas } = txParams;\n\n if (\n gasPrice === undefined &&\n maxFeePerGas === undefined &&\n maxPriorityFeePerGas === undefined &&\n gas === undefined\n ) {\n return undefined;\n }\n\n const dappSuggestedGasFees: DappSuggestedGasFees = {};\n\n if (gasPrice !== undefined) {\n dappSuggestedGasFees.gasPrice = gasPrice;\n } else if (\n maxFeePerGas !== undefined ||\n maxPriorityFeePerGas !== undefined\n ) {\n dappSuggestedGasFees.maxFeePerGas = maxFeePerGas;\n dappSuggestedGasFees.maxPriorityFeePerGas = maxPriorityFeePerGas;\n }\n\n if (gas !== undefined) {\n dappSuggestedGasFees.gas = gas;\n }\n\n return dappSuggestedGasFees;\n }\n\n /**\n * Validates and adds external provided transaction to state.\n *\n * @param transactionMeta - Nominated external transaction to be added to state.\n */\n private async addExternalTransaction(transactionMeta: TransactionMeta) {\n const chainId = this.getChainId();\n const { transactions } = this.state;\n const fromAddress = transactionMeta?.txParams?.from;\n const sameFromAndNetworkTransactions = transactions.filter(\n (transaction) =>\n transaction.txParams.from === fromAddress &&\n transaction.chainId === chainId,\n );\n const confirmedTxs = sameFromAndNetworkTransactions.filter(\n (transaction) => transaction.status === TransactionStatus.confirmed,\n );\n const pendingTxs = sameFromAndNetworkTransactions.filter(\n (transaction) => transaction.status === TransactionStatus.submitted,\n );\n\n validateConfirmedExternalTransaction(\n transactionMeta,\n confirmedTxs,\n pendingTxs,\n );\n\n // Make sure provided external transaction has non empty history array\n if (!(transactionMeta.history ?? []).length) {\n if (!this.isHistoryDisabled) {\n addInitialHistorySnapshot(transactionMeta);\n }\n }\n\n const updatedTransactions = [...transactions, transactionMeta];\n this.update({\n transactions: this.trimTransactionsForState(updatedTransactions),\n });\n }\n\n /**\n * Sets other txMeta statuses to dropped if the txMeta that has been confirmed has other transactions\n * in the transactions have the same nonce.\n *\n * @param transactionId - Used to identify original transaction.\n */\n private markNonceDuplicatesDropped(transactionId: string) {\n const chainId = this.getChainId();\n const transactionMeta = this.getTransaction(transactionId);\n const nonce = transactionMeta?.txParams?.nonce;\n const from = transactionMeta?.txParams?.from;\n const sameNonceTxs = this.state.transactions.filter(\n (transaction) =>\n transaction.txParams.from === from &&\n transaction.txParams.nonce === nonce &&\n transaction.chainId === chainId,\n );\n\n if (!sameNonceTxs.length) {\n return;\n }\n\n // Mark all same nonce transactions as dropped and give it a replacedBy hash\n for (const transaction of sameNonceTxs) {\n if (transaction.id === transactionId) {\n continue;\n }\n transaction.replacedBy = transactionMeta?.hash;\n transaction.replacedById = transactionMeta?.id;\n // Drop any transaction that wasn't previously failed (off chain failure)\n if (transaction.status !== TransactionStatus.failed) {\n this.setTransactionStatusDropped(transaction);\n }\n }\n }\n\n /**\n * Method to set transaction status to dropped.\n *\n * @param transactionMeta - TransactionMeta of transaction to be marked as dropped.\n */\n private setTransactionStatusDropped(transactionMeta: TransactionMeta) {\n transactionMeta.status = TransactionStatus.dropped;\n this.updateTransaction(\n transactionMeta,\n 'TransactionController#setTransactionStatusDropped - Transaction dropped',\n );\n }\n\n /**\n * Get transaction with provided actionId.\n *\n * @param actionId - Unique ID to prevent duplicate requests\n * @returns the filtered transaction\n */\n private getTransactionWithActionId(actionId?: string) {\n return this.state.transactions.find(\n (transaction) => actionId && transaction.actionId === actionId,\n );\n }\n\n private async waitForTransactionFinished(\n transactionId: string,\n ): Promise<TransactionMeta> {\n return new Promise((resolve) => {\n this.hub.once(`${transactionId}:finished`, (txMeta) => {\n resolve(txMeta);\n });\n });\n }\n\n /**\n * Updates the r, s, and v properties of a TransactionMeta object\n * with values from a signed transaction.\n *\n * @param transactionMeta - The TransactionMeta object to update.\n * @param signedTx - The encompassing type for all transaction types containing r, s, and v values.\n */\n private async updateTransactionMetaRSV(\n transactionMeta: TransactionMeta,\n signedTx: TypedTransaction,\n ): Promise<void> {\n if (signedTx.r) {\n transactionMeta.r = addHexPrefix(signedTx.r.toString(16));\n }\n\n if (signedTx.s) {\n transactionMeta.s = addHexPrefix(signedTx.s.toString(16));\n }\n\n if (signedTx.v) {\n transactionMeta.v = addHexPrefix(signedTx.v.toString(16));\n }\n }\n\n private async getEIP1559Compatibility() {\n const currentNetworkIsEIP1559Compatible =\n await this.getCurrentNetworkEIP1559Compatibility();\n const currentAccountIsEIP1559Compatible =\n this.getCurrentAccountEIP1559Compatibility?.() ?? true;\n\n return (\n currentNetworkIsEIP1559Compatible && currentAccountIsEIP1559Compatible\n );\n }\n}\n\nexport default TransactionController;\n"]}
|
package/dist/{EtherscanRemoteTransactionSource.d.ts → helpers/EtherscanRemoteTransactionSource.d.ts}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Hex } from '@metamask/utils';
|
|
2
|
-
import type { RemoteTransactionSource, RemoteTransactionSourceRequest, TransactionMeta } from '
|
|
2
|
+
import type { RemoteTransactionSource, RemoteTransactionSourceRequest, TransactionMeta } from '../types';
|
|
3
3
|
/**
|
|
4
4
|
* A RemoteTransactionSource that fetches transaction data from Etherscan.
|
|
5
5
|
*/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EtherscanRemoteTransactionSource.d.ts","sourceRoot":"","sources":["../../src/helpers/EtherscanRemoteTransactionSource.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAM3C,OAAO,KAAK,EACV,uBAAuB,EACvB,8BAA8B,EAC9B,eAAe,EAChB,MAAM,UAAU,CAAC;AAclB;;GAEG;AACH,qBAAa,gCACX,YAAW,uBAAuB;;gBAMtB,EACV,qBAAqB,GACtB,GAAE;QAAE,qBAAqB,CAAC,EAAE,OAAO,CAAA;KAAO;IAK3C,kBAAkB,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO;IAIzC,sBAAsB,IAAI,MAAM,EAAE;IAI5B,iBAAiB,CACrB,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,eAAe,EAAE,CAAC;CAkI9B"}
|
package/dist/{EtherscanRemoteTransactionSource.js → helpers/EtherscanRemoteTransactionSource.js}
RENAMED
|
@@ -25,10 +25,10 @@ exports.EtherscanRemoteTransactionSource = void 0;
|
|
|
25
25
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
26
26
|
const ethereumjs_util_1 = require("ethereumjs-util");
|
|
27
27
|
const uuid_1 = require("uuid");
|
|
28
|
-
const constants_1 = require("
|
|
29
|
-
const
|
|
30
|
-
const
|
|
31
|
-
const
|
|
28
|
+
const constants_1 = require("../constants");
|
|
29
|
+
const logger_1 = require("../logger");
|
|
30
|
+
const types_1 = require("../types");
|
|
31
|
+
const etherscan_1 = require("../utils/etherscan");
|
|
32
32
|
/**
|
|
33
33
|
* A RemoteTransactionSource that fetches transaction data from Etherscan.
|
|
34
34
|
*/
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EtherscanRemoteTransactionSource.js","sourceRoot":"","sources":["../../src/helpers/EtherscanRemoteTransactionSource.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,iEAAqD;AAErD,qDAAqC;AACrC,+BAAoC;AAEpC,4CAA4D;AAC5D,sCAA8D;AAM9D,oCAA6C;AAC7C,kDAG4B;AAS5B;;GAEG;AACH,MAAa,gCAAgC;IAO3C,YAAY,EACV,qBAAqB,MACkB,EAAE;;QAN3C,0EAAgC;QAEhC,0EAAgC;QAoChC,oEAA2B,CACzB,OAAuC,EACvC,gBAA6C,EAC7C,EAAE;YACF,MAAM,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC;YAEnC,MAAM,qBAAqB,GAAG,MAAM,IAAA,sCAA0B,EAC5D,gBAAgB,CACjB,CAAC;YAEF,OAAO,uBAAA,IAAI,8GAAyB,MAA7B,IAAI,EAA0B,qBAAqB,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACrE,uBAAA,IAAI,2GAAsB,MAA1B,IAAI,EAAuB,EAAE,EAAE,cAAc,CAAC,CAC/C,CAAC;QACJ,CAAC,CAAA,EAAC;QAEF,mEAA0B,CACxB,OAAuC,EACvC,gBAA6C,EAC7C,EAAE;YACF,MAAM,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC;YAEnC,MAAM,qBAAqB,GAAG,MAAM,IAAA,2CAA+B,EACjE,gBAAgB,CACjB,CAAC;YAEF,OAAO,uBAAA,IAAI,8GAAyB,MAA7B,IAAI,EAA0B,qBAAqB,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACrE,uBAAA,IAAI,gHAA2B,MAA/B,IAAI,EAA4B,EAAE,EAAE,cAAc,CAAC,CACpD,CAAC;QACJ,CAAC,CAAA,E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E,CAAC;QAC3B,MAAM,EAAE,yBAAiB,CAAC,SAAS;QACnC,IAAI;QACJ,QAAQ,EAAE;YACR,OAAO,EAAE,cAAc;YACvB,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,GAAG,EAAE,IAAA,0BAAO,EAAC,IAAI,oBAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAChC,QAAQ,EAAE,IAAA,0BAAO,EAAC,IAAI,oBAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC1C,OAAO,EAAE,IAAA,0BAAO,EAAC,IAAI,oBAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YACxC,KAAK,EAAE,IAAA,0BAAO,EAAC,IAAI,oBAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACpC,EAAE,EAAE,MAAM,CAAC,EAAE;YACb,KAAK,EAAE,IAAA,0BAAO,EAAC,IAAI,oBAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SACrC;QACD,oBAAoB,EAAE,KAAK;KAC5B,CAAC;AACJ,CAAC","sourcesContent":["import { BNToHex } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { BN } from 'ethereumjs-util';\nimport { v1 as random } from 'uuid';\n\nimport { ETHERSCAN_SUPPORTED_NETWORKS } from '../constants';\nimport { incomingTransactionsLogger as log } from '../logger';\nimport type {\n RemoteTransactionSource,\n RemoteTransactionSourceRequest,\n TransactionMeta,\n} from '../types';\nimport { TransactionStatus } from '../types';\nimport {\n fetchEtherscanTokenTransactions,\n fetchEtherscanTransactions,\n} from '../utils/etherscan';\nimport type {\n EtherscanTokenTransactionMeta,\n EtherscanTransactionMeta,\n EtherscanTransactionMetaBase,\n EtherscanTransactionRequest,\n EtherscanTransactionResponse,\n} from '../utils/etherscan';\n\n/**\n * A RemoteTransactionSource that fetches transaction data from Etherscan.\n */\nexport class EtherscanRemoteTransactionSource\n implements RemoteTransactionSource\n{\n #includeTokenTransfers: boolean;\n\n #isTokenRequestPending: boolean;\n\n constructor({\n includeTokenTransfers,\n }: { includeTokenTransfers?: boolean } = {}) {\n this.#includeTokenTransfers = includeTokenTransfers ?? true;\n this.#isTokenRequestPending = false;\n }\n\n isSupportedNetwork(chainId: Hex): boolean {\n return Object.keys(ETHERSCAN_SUPPORTED_NETWORKS).includes(chainId);\n }\n\n getLastBlockVariations(): string[] {\n return [this.#isTokenRequestPending ? 'token' : 'normal'];\n }\n\n async fetchTransactions(\n request: RemoteTransactionSourceRequest,\n ): Promise<TransactionMeta[]> {\n const etherscanRequest: EtherscanTransactionRequest = {\n ...request,\n chainId: request.currentChainId,\n };\n\n const transactions = this.#isTokenRequestPending\n ? await this.#fetchTokenTransactions(request, etherscanRequest)\n : await this.#fetchNormalTransactions(request, etherscanRequest);\n\n if (this.#includeTokenTransfers) {\n this.#isTokenRequestPending = !this.#isTokenRequestPending;\n }\n\n return transactions;\n }\n\n #fetchNormalTransactions = async (\n request: RemoteTransactionSourceRequest,\n etherscanRequest: EtherscanTransactionRequest,\n ) => {\n const { currentChainId } = request;\n\n const etherscanTransactions = await fetchEtherscanTransactions(\n etherscanRequest,\n );\n\n return this.#getResponseTransactions(etherscanTransactions).map((tx) =>\n this.#normalizeTransaction(tx, currentChainId),\n );\n };\n\n #fetchTokenTransactions = async (\n request: RemoteTransactionSourceRequest,\n etherscanRequest: EtherscanTransactionRequest,\n ) => {\n const { currentChainId } = request;\n\n const etherscanTransactions = await fetchEtherscanTokenTransactions(\n etherscanRequest,\n );\n\n return this.#getResponseTransactions(etherscanTransactions).map((tx) =>\n this.#normalizeTokenTransaction(tx, currentChainId),\n );\n };\n\n #getResponseTransactions<T extends EtherscanTransactionMetaBase>(\n response: EtherscanTransactionResponse<T>,\n ): T[] {\n let result = response.result as T[];\n\n if (response.status === '0') {\n result = [];\n\n if (response.result.length) {\n log('Ignored Etherscan request error', {\n message: response.result,\n type: this.#isTokenRequestPending ? 'token' : 'normal',\n });\n }\n }\n\n return result;\n }\n\n #normalizeTransaction(\n txMeta: EtherscanTransactionMeta,\n currentChainId: Hex,\n ): TransactionMeta {\n const base = this.#normalizeTransactionBase(txMeta, currentChainId);\n\n return {\n ...base,\n txParams: {\n ...base.txParams,\n data: txMeta.input,\n },\n ...(txMeta.isError === '0'\n ? { status: TransactionStatus.confirmed }\n : {\n error: new Error('Transaction failed'),\n status: TransactionStatus.failed,\n }),\n };\n }\n\n #normalizeTokenTransaction(\n txMeta: EtherscanTokenTransactionMeta,\n currentChainId: Hex,\n ): TransactionMeta {\n const base = this.#normalizeTransactionBase(txMeta, currentChainId);\n\n return {\n ...base,\n isTransfer: true,\n transferInformation: {\n contractAddress: txMeta.contractAddress,\n decimals: Number(txMeta.tokenDecimal),\n symbol: txMeta.tokenSymbol,\n },\n };\n }\n\n #normalizeTransactionBase(\n txMeta: EtherscanTransactionMetaBase,\n currentChainId: Hex,\n ): TransactionMeta {\n const time = parseInt(txMeta.timeStamp, 10) * 1000;\n\n return {\n blockNumber: txMeta.blockNumber,\n chainId: currentChainId,\n hash: txMeta.hash,\n id: random({ msecs: time }),\n status: TransactionStatus.confirmed,\n time,\n txParams: {\n chainId: currentChainId,\n from: txMeta.from,\n gas: BNToHex(new BN(txMeta.gas)),\n gasPrice: BNToHex(new BN(txMeta.gasPrice)),\n gasUsed: BNToHex(new BN(txMeta.gasUsed)),\n nonce: BNToHex(new BN(txMeta.nonce)),\n to: txMeta.to,\n value: BNToHex(new BN(txMeta.value)),\n },\n verifiedOnBlockchain: false,\n };\n }\n}\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import type { BlockTracker, NetworkState } from '@metamask/network-controller';
|
|
3
3
|
import type { Hex } from '@metamask/utils';
|
|
4
4
|
import EventEmitter from 'events';
|
|
5
|
-
import type { RemoteTransactionSource, TransactionMeta } from '
|
|
5
|
+
import type { RemoteTransactionSource, TransactionMeta } from '../types';
|
|
6
6
|
export declare class IncomingTransactionHelper {
|
|
7
7
|
#private;
|
|
8
8
|
hub: EventEmitter;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IncomingTransactionHelper.d.ts","sourceRoot":"","sources":["../../src/helpers/IncomingTransactionHelper.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC/E,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,YAAY,MAAM,QAAQ,CAAC;AAGlC,OAAO,KAAK,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AASzE,qBAAa,yBAAyB;;IACpC,GAAG,EAAE,YAAY,CAAC;gBA4BN,EACV,YAAY,EACZ,iBAAiB,EACjB,0BAA0B,EAC1B,oBAAoB,EACpB,eAAe,EACf,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,GACnB,EAAE;QACD,YAAY,EAAE,YAAY,CAAC;QAC3B,iBAAiB,EAAE,MAAM,MAAM,CAAC;QAChC,0BAA0B,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACzD,oBAAoB,CAAC,EAAE,MAAM,eAAe,EAAE,CAAC;QAC/C,eAAe,EAAE,MAAM,YAAY,CAAC;QACpC,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;QAC1B,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,uBAAuB,EAAE,uBAAuB,CAAC;QACjD,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B;IA0BD,KAAK;IAaL,IAAI;IAKE,MAAM,CAAC,oBAAoB,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;CAmMxD"}
|
|
@@ -27,7 +27,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
27
27
|
exports.IncomingTransactionHelper = void 0;
|
|
28
28
|
const async_mutex_1 = require("async-mutex");
|
|
29
29
|
const events_1 = __importDefault(require("events"));
|
|
30
|
-
const logger_1 = require("
|
|
30
|
+
const logger_1 = require("../logger");
|
|
31
31
|
const RECENT_HISTORY_BLOCK_RANGE = 10;
|
|
32
32
|
const UPDATE_CHECKS = [
|
|
33
33
|
(txMeta) => txMeta.status,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IncomingTransactionHelper.js","sourceRoot":"","sources":["../../src/helpers/IncomingTransactionHelper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,6CAAoC;AACpC,oDAAkC;AAElC,sCAA8D;AAG9D,MAAM,0BAA0B,GAAG,EAAE,CAAC;AAEtC,MAAM,aAAa,GAAyC;IAC1D,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM;IACzB,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO;CACpC,CAAC;AAEF,MAAa,yBAAyB;IA6BpC,YAAY,EACV,YAAY,EACZ,iBAAiB,EACjB,0BAA0B,EAC1B,oBAAoB,EACpB,eAAe,EACf,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,GAYnB;;QAhDD,0DAA4B;QAE5B,+DAAiC;QAEjC,wEAA0D;QAE1D,kEAA+C;QAE/C,6DAAqC;QAErC,uDAA0B;QAE1B,uDAAoB;QAEpB,2CAAS,IAAI,mBAAK,EAAE,EAAC;QAErB,2DAAuD;QAEvD,gEAA6B;QAE7B,qEAAkD;QAElD,8DAA2B;QAE3B,gEAA6B;QAyB3B,IAAI,CAAC,GAAG,GAAG,IAAI,gBAAY,EAAE,CAAC;QAE9B,uBAAA,IAAI,2CAAiB,YAAY,MAAA,CAAC;QAClC,uBAAA,IAAI,gDAAsB,iBAAiB,MAAA,CAAC;QAC5C,uBAAA,IAAI,yDAA+B,0BAA0B,MAAA,CAAC;QAC9D,uBAAA,IAAI,mDAAyB,o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G,uBAAA,IAAI,0FAAmB,MAAvB,IAAI,CAAqB,CAAC;IAEjD,MAAM,kBAAkB,GACtB,uBAAA,IAAI,0DAAyB,CAAC,kBAAkB,CAAC,cAAc,CAAC,CAAC;IAEnE,OAAO,SAAS,IAAI,kBAAkB,CAAC;AACzC,CAAC;IAGC,OAAO,uBAAA,IAAI,kDAAiB,MAArB,IAAI,CAAmB,CAAC,cAAc,CAAC,OAAO,CAAC;AACxD,CAAC","sourcesContent":["import type { BlockTracker, NetworkState } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport EventEmitter from 'events';\n\nimport { incomingTransactionsLogger as log } from '../logger';\nimport type { RemoteTransactionSource, TransactionMeta } from '../types';\n\nconst RECENT_HISTORY_BLOCK_RANGE = 10;\n\nconst UPDATE_CHECKS: ((txMeta: TransactionMeta) => any)[] = [\n (txMeta) => txMeta.status,\n (txMeta) => txMeta.txParams.gasUsed,\n];\n\nexport class IncomingTransactionHelper {\n hub: EventEmitter;\n\n #blockTracker: BlockTracker;\n\n #getCurrentAccount: () => string;\n\n #getLastFetchedBlockNumbers: () => Record<string, number>;\n\n #getLocalTransactions: () => TransactionMeta[];\n\n #getNetworkState: () => NetworkState;\n\n #isEnabled: () => boolean;\n\n #isRunning: boolean;\n\n #mutex = new Mutex();\n\n #onLatestBlock: (blockNumberHex: Hex) => Promise<void>;\n\n #queryEntireHistory: boolean;\n\n #remoteTransactionSource: RemoteTransactionSource;\n\n #transactionLimit?: number;\n\n #updateTransactions: boolean;\n\n constructor({\n blockTracker,\n getCurrentAccount,\n getLastFetchedBlockNumbers,\n getLocalTransactions,\n getNetworkState,\n isEnabled,\n queryEntireHistory,\n remoteTransactionSource,\n transactionLimit,\n updateTransactions,\n }: {\n blockTracker: BlockTracker;\n getCurrentAccount: () => string;\n getLastFetchedBlockNumbers: () => Record<string, number>;\n getLocalTransactions?: () => TransactionMeta[];\n getNetworkState: () => NetworkState;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n remoteTransactionSource: RemoteTransactionSource;\n transactionLimit?: number;\n updateTransactions?: boolean;\n }) {\n this.hub = new EventEmitter();\n\n this.#blockTracker = blockTracker;\n this.#getCurrentAccount = getCurrentAccount;\n this.#getLastFetchedBlockNumbers = getLastFetchedBlockNumbers;\n this.#getLocalTransactions = getLocalTransactions || (() => []);\n this.#getNetworkState = getNetworkState;\n this.#isEnabled = isEnabled ?? (() => true);\n this.#isRunning = false;\n this.#queryEntireHistory = queryEntireHistory ?? true;\n this.#remoteTransactionSource = remoteTransactionSource;\n this.#transactionLimit = transactionLimit;\n this.#updateTransactions = updateTransactions ?? false;\n\n // Using a property instead of a method to provide a listener reference\n // with the correct scope that we can remove later if stopped.\n this.#onLatestBlock = async (blockNumberHex: Hex) => {\n try {\n await this.update(blockNumberHex);\n } catch (error) {\n console.error('Error while checking incoming transactions', error);\n }\n };\n }\n\n start() {\n if (this.#isRunning) {\n return;\n }\n\n if (!this.#canStart()) {\n return;\n }\n\n this.#blockTracker.addListener('latest', this.#onLatestBlock);\n this.#isRunning = true;\n }\n\n stop() {\n this.#blockTracker.removeListener('latest', this.#onLatestBlock);\n this.#isRunning = false;\n }\n\n async update(latestBlockNumberHex?: Hex): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n\n log('Checking for incoming transactions');\n\n try {\n if (!this.#canStart()) {\n return;\n }\n\n const latestBlockNumber = parseInt(\n latestBlockNumberHex || (await this.#blockTracker.getLatestBlock()),\n 16,\n );\n\n const additionalLastFetchedKeys =\n this.#remoteTransactionSource.getLastBlockVariations?.() ?? [];\n\n const fromBlock = this.#getFromBlock(\n latestBlockNumber,\n additionalLastFetchedKeys,\n );\n\n const address = this.#getCurrentAccount();\n const currentChainId = this.#getCurrentChainId();\n\n let remoteTransactions = [];\n\n try {\n remoteTransactions =\n await this.#remoteTransactionSource.fetchTransactions({\n address,\n currentChainId,\n fromBlock,\n limit: this.#transactionLimit,\n });\n } catch (error: any) {\n log('Error while fetching remote transactions', error);\n return;\n }\n\n if (!this.#updateTransactions) {\n remoteTransactions = remoteTransactions.filter(\n (tx) => tx.txParams.to?.toLowerCase() === address.toLowerCase(),\n );\n }\n\n const localTransactions = !this.#updateTransactions\n ? []\n : this.#getLocalTransactions();\n\n const newTransactions = this.#getNewTransactions(\n remoteTransactions,\n localTransactions,\n );\n\n const updatedTransactions = this.#getUpdatedTransactions(\n remoteTransactions,\n localTransactions,\n );\n\n if (newTransactions.length > 0 || updatedTransactions.length > 0) {\n this.#sortTransactionsByTime(newTransactions);\n this.#sortTransactionsByTime(updatedTransactions);\n\n log('Found incoming transactions', {\n new: newTransactions,\n updated: updatedTransactions,\n });\n\n this.hub.emit('transactions', {\n added: newTransactions,\n updated: updatedTransactions,\n });\n }\n\n this.#updateLastFetchedBlockNumber(\n remoteTransactions,\n additionalLastFetchedKeys,\n );\n } finally {\n releaseLock();\n }\n }\n\n #sortTransactionsByTime(transactions: TransactionMeta[]) {\n transactions.sort((a, b) => (a.time < b.time ? -1 : 1));\n }\n\n #getNewTransactions(\n remoteTxs: TransactionMeta[],\n localTxs: TransactionMeta[],\n ): TransactionMeta[] {\n return remoteTxs.filter(\n (tx) => !localTxs.some(({ hash }) => hash === tx.hash),\n );\n }\n\n #getUpdatedTransactions(\n remoteTxs: TransactionMeta[],\n localTxs: TransactionMeta[],\n ): TransactionMeta[] {\n return remoteTxs.filter((remoteTx) =>\n localTxs.some(\n (localTx) =>\n remoteTx.hash === localTx.hash &&\n this.#isTransactionOutdated(remoteTx, localTx),\n ),\n );\n }\n\n #isTransactionOutdated(\n remoteTx: TransactionMeta,\n localTx: TransactionMeta,\n ): boolean {\n return UPDATE_CHECKS.some(\n (getValue) => getValue(remoteTx) !== getValue(localTx),\n );\n }\n\n #getFromBlock(\n latestBlockNumber: number,\n additionalKeys: string[],\n ): number | undefined {\n const lastFetchedKey = this.#getBlockNumberKey(additionalKeys);\n\n const lastFetchedBlockNumber =\n this.#getLastFetchedBlockNumbers()[lastFetchedKey];\n\n if (lastFetchedBlockNumber) {\n return lastFetchedBlockNumber + 1;\n }\n\n return this.#queryEntireHistory\n ? undefined\n : latestBlockNumber - RECENT_HISTORY_BLOCK_RANGE;\n }\n\n #updateLastFetchedBlockNumber(\n remoteTxs: TransactionMeta[],\n additionalKeys: string[],\n ) {\n let lastFetchedBlockNumber = -1;\n\n for (const tx of remoteTxs) {\n const currentBlockNumberValue = tx.blockNumber\n ? parseInt(tx.blockNumber, 10)\n : -1;\n\n lastFetchedBlockNumber = Math.max(\n lastFetchedBlockNumber,\n currentBlockNumberValue,\n );\n }\n\n if (lastFetchedBlockNumber === -1) {\n return;\n }\n\n const lastFetchedKey = this.#getBlockNumberKey(additionalKeys);\n const lastFetchedBlockNumbers = this.#getLastFetchedBlockNumbers();\n const previousValue = lastFetchedBlockNumbers[lastFetchedKey];\n\n if (previousValue >= lastFetchedBlockNumber) {\n return;\n }\n\n lastFetchedBlockNumbers[lastFetchedKey] = lastFetchedBlockNumber;\n\n this.hub.emit('updatedLastFetchedBlockNumbers', {\n lastFetchedBlockNumbers,\n blockNumber: lastFetchedBlockNumber,\n });\n }\n\n #getBlockNumberKey(additionalKeys: string[]): string {\n const currentChainId = this.#getCurrentChainId();\n const currentAccount = this.#getCurrentAccount().toLowerCase();\n\n return [currentChainId, currentAccount, ...additionalKeys].join('#');\n }\n\n #canStart(): boolean {\n const isEnabled = this.#isEnabled();\n const currentChainId = this.#getCurrentChainId();\n\n const isSupportedNetwork =\n this.#remoteTransactionSource.isSupportedNetwork(currentChainId);\n\n return isEnabled && isSupportedNetwork;\n }\n\n #getCurrentChainId(): Hex {\n return this.#getNetworkState().providerConfig.chainId;\n }\n}\n"]}
|
|
@@ -2,16 +2,18 @@
|
|
|
2
2
|
import type EthQuery from '@metamask/eth-query';
|
|
3
3
|
import type { BlockTracker } from '@metamask/network-controller';
|
|
4
4
|
import EventEmitter from 'events';
|
|
5
|
-
import type
|
|
5
|
+
import type NonceTracker from 'nonce-tracker';
|
|
6
|
+
import type { TransactionMeta } from '../types';
|
|
6
7
|
export declare class PendingTransactionTracker {
|
|
7
8
|
#private;
|
|
8
9
|
hub: EventEmitter;
|
|
9
|
-
constructor({ blockTracker, failTransaction, getChainId, getEthQuery, getTransactions, }: {
|
|
10
|
+
constructor({ blockTracker, failTransaction, getChainId, getEthQuery, getTransactions, nonceTracker, }: {
|
|
10
11
|
blockTracker: BlockTracker;
|
|
11
12
|
failTransaction: (txMeta: TransactionMeta, error: Error) => void;
|
|
12
13
|
getChainId: () => string;
|
|
13
14
|
getEthQuery: () => EthQuery;
|
|
14
15
|
getTransactions: () => TransactionMeta[];
|
|
16
|
+
nonceTracker: NonceTracker;
|
|
15
17
|
});
|
|
16
18
|
start(): void;
|
|
17
19
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PendingTransactionTracker.d.ts","sourceRoot":"","sources":["../../src/helpers/PendingTransactionTracker.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,YAAY,MAAM,QAAQ,CAAC;AAClC,OAAO,KAAK,YAAY,MAAM,eAAe,CAAC;AAG9C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAGhD,qBAAa,yBAAyB;;IACpC,GAAG,EAAE,YAAY,CAAC;gBAcN,EACV,YAAY,EACZ,eAAe,EACf,UAAU,EACV,WAAW,EACX,eAAe,EACf,YAAY,GACb,EAAE;QACD,YAAY,EAAE,YAAY,CAAC;QAC3B,eAAe,EAAE,CAAC,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;QACjE,UAAU,EAAE,MAAM,MAAM,CAAC;QACzB,WAAW,EAAE,MAAM,QAAQ,CAAC;QAC5B,eAAe,EAAE,MAAM,eAAe,EAAE,CAAC;QACzC,YAAY,EAAE,YAAY,CAAC;KAC5B;IAWD,KAAK;CAwLN"}
|