@metamask/transaction-controller 55.0.1 → 56.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 +16 -1
- package/dist/TransactionController.cjs +1 -0
- package/dist/TransactionController.cjs.map +1 -1
- package/dist/TransactionController.d.cts.map +1 -1
- package/dist/TransactionController.d.mts.map +1 -1
- package/dist/TransactionController.mjs +1 -0
- package/dist/TransactionController.mjs.map +1 -1
- package/dist/api/simulation-api.cjs.map +1 -1
- package/dist/api/simulation-api.d.cts +3 -1
- package/dist/api/simulation-api.d.cts.map +1 -1
- package/dist/api/simulation-api.d.mts +3 -1
- package/dist/api/simulation-api.d.mts.map +1 -1
- package/dist/api/simulation-api.mjs.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.cjs +13 -7
- package/dist/helpers/IncomingTransactionHelper.cjs.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.d.cts +3 -1
- package/dist/helpers/IncomingTransactionHelper.d.cts.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.d.mts +3 -1
- package/dist/helpers/IncomingTransactionHelper.d.mts.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.mjs +13 -7
- package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -1
- package/dist/utils/feature-flags.cjs +16 -1
- package/dist/utils/feature-flags.cjs.map +1 -1
- package/dist/utils/feature-flags.d.cts +14 -0
- package/dist/utils/feature-flags.d.cts.map +1 -1
- package/dist/utils/feature-flags.d.mts +14 -0
- package/dist/utils/feature-flags.d.mts.map +1 -1
- package/dist/utils/feature-flags.mjs +14 -0
- package/dist/utils/feature-flags.mjs.map +1 -1
- package/dist/utils/gas.cjs +3 -3
- package/dist/utils/gas.cjs.map +1 -1
- package/dist/utils/gas.mjs +3 -3
- package/dist/utils/gas.mjs.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation-api.cjs","sourceRoot":"","sources":["../../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AAED;;;;;GAKG;AACH,KAAK,UAAU,gBAAgB,CAAC,OAAY;IAC1C,MAAM,WAAW,GAAG,MAAM,cAAc,EAAE,CAAC;IAC3C,MAAM,cAAc,GAAG,IAAA,sCAAmB,EAAC,OAAO,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,WAAW,CAAC,cAAc,CAAC,CAAC;IAE5C,IAAI,CAAC,OAAO,EAAE,aAAa,EAAE;QAC3B,GAAG,CAAC,wBAAwB,EAAE,OAAO,CAAC,CAAC;QACvC,MAAM,IAAI,yCAAgC,CAAC,OAAO,CAAC,CAAC;KACrD;IAED,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACjC,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,cAAc;IAC3B,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,kBAAkB,CAAC,GAAG,iBAAiB,EAAE,CAAC;IAChE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC;AAED;;;;;GAKG;AACH,SAAS,MAAM,CAAC,SAAiB;IAC/B,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport { SimulationChainNotSupportedError, SimulationError } from '../errors';\nimport { projectLogger } from '../logger';\n\nconst log = createModuleLogger(projectLogger, 'simulation-api');\n\nconst RPC_METHOD = 'infura_simulateTransactions';\nconst BASE_URL = 'https://tx-sentinel-{0}.api.cx.metamask.io/';\nconst ENDPOINT_NETWORKS = 'networks';\n\n/** Single transaction to simulate in a simulation API request. */\nexport type SimulationRequestTransaction = {\n authorizationList?: {\n /** Address of a smart contract that contains the code to be set. */\n address: Hex;\n\n /** Address of the account being upgraded. */\n from: Hex;\n }[];\n\n /** Data to send with the transaction. */\n data?: Hex;\n\n /** Sender of the transaction. */\n from: Hex;\n\n /** Gas limit for the transaction. */\n gas?: Hex;\n\n /** Maximum fee per gas for the transaction. */\n maxFeePerGas?: Hex;\n\n /** Maximum priority fee per gas for the transaction. */\n maxPriorityFeePerGas?: Hex;\n\n /** Recipient of the transaction. */\n to?: Hex;\n\n /** Value to send with the transaction. */\n value?: Hex;\n};\n\n/** Request to the simulation API to simulate transactions. */\nexport type SimulationRequest = {\n /**\n * Transactions to be sequentially simulated.\n * State changes impact subsequent transactions in the list.\n */\n transactions: SimulationRequestTransaction[];\n\n blockOverrides?: {\n time?: Hex;\n };\n\n /**\n * Overrides to the state of the blockchain, keyed by address.\n */\n overrides?: {\n [address: Hex]: {\n /** Override the code for an address. */\n code?: Hex;\n\n /** Overrides to the storage slots for an address. */\n stateDiff?: {\n [slot: Hex]: Hex;\n };\n };\n };\n\n /**\n * Whether to include available token fees.\n */\n suggestFees?: {\n /* Whether to estimate gas for the transaction being submitted via a delegation. */\n with7702?: boolean;\n\n /* Whether to include the gas fee of the token transfer. */\n withFeeTransfer?: boolean;\n\n /* Whether to include the native transfer if available. */\n withTransfer?: boolean;\n };\n\n /**\n * Whether to include call traces in the response.\n * Defaults to false.\n */\n withCallTrace?: boolean;\n\n /**\n * Whether to include event logs in the response.\n * Defaults to false.\n */\n withLogs?: boolean;\n};\n\n/** Raw event log emitted by a simulated transaction. */\nexport type SimulationResponseLog = {\n /** Address of the account that created the event. */\n address: Hex;\n\n /** Raw data in the event that is not indexed. */\n data: Hex;\n\n /** Raw indexed data from the event. */\n topics: Hex[];\n};\n\n/** Call trace of a single simulated transaction. */\nexport type SimulationResponseCallTrace = {\n /** Nested calls. */\n calls: SimulationResponseCallTrace[];\n\n /** Raw event logs created by the call. */\n logs: SimulationResponseLog[];\n};\n\n/**\n * Changes to the blockchain state.\n * Keyed by account address.\n */\nexport type SimulationResponseStateDiff = {\n [address: Hex]: {\n /** Native balance of the account. */\n balance?: Hex;\n\n /** Nonce of the account. */\n nonce?: Hex;\n\n /** Storage values per slot. */\n storage?: {\n [slot: Hex]: Hex;\n };\n };\n};\n\nexport type SimulationResponseTokenFee = {\n /** Token data independent of current transaction. */\n token: {\n /** Address of the token contract. */\n address: Hex;\n\n /** Decimals of the token. */\n decimals: number;\n\n /** Symbol of the token. */\n symbol: string;\n };\n\n /** Amount of tokens needed to pay for gas. */\n balanceNeededToken: Hex;\n\n /** Current token balance of sender. */\n currentBalanceToken: Hex;\n\n /** Account address that token should be transferred to. */\n feeRecipient: Hex;\n\n /** Conversation rate of 1 token to native WEI. */\n rateWei: Hex;\n\n /** Estimated gas limit required for fee transfer. */\n transferEstimate: Hex;\n};\n\n/** Response from the simulation API for a single transaction. */\nexport type SimulationResponseTransaction = {\n /** Hierarchy of call data including nested calls and logs. */\n callTrace?: SimulationResponseCallTrace;\n\n /** An error message indicating the transaction could not be simulated. */\n error?: string;\n\n /** Recommended gas fees for the transaction. */\n fees?: {\n /** Gas limit for the fee level. */\n gas: Hex;\n\n /** Maximum fee per gas for the fee level. */\n maxFeePerGas: Hex;\n\n /** Maximum priority fee per gas for the fee level. */\n maxPriorityFeePerGas: Hex;\n\n /** Token fee data for the fee level. */\n tokenFees: SimulationResponseTokenFee[];\n }[];\n\n /** The total gas used by the transaction. */\n gasUsed?: Hex;\n\n /** Return value of the transaction, such as the balance if calling balanceOf. */\n return: Hex;\n\n /** Changes to the blockchain state. */\n stateDiff?: {\n /** Initial blockchain state before the transaction. */\n pre?: SimulationResponseStateDiff;\n\n /** Updated blockchain state after the transaction. */\n post?: SimulationResponseStateDiff;\n };\n};\n\n/** Response from the simulation API. */\nexport type SimulationResponse = {\n /** Simulation data for each transaction in the request. */\n transactions: SimulationResponseTransaction[];\n};\n\n/** Data for a network supported by the Simulation API. */\ntype SimulationNetwork = {\n /** Subdomain of the API for the network. */\n network: string;\n\n /** Whether the network supports confirmation simulations. */\n confirmations: boolean;\n};\n\n/** Response from the simulation API containing supported networks. */\ntype SimulationNetworkResponse = {\n [chainIdDecimal: string]: SimulationNetwork;\n};\n\nlet requestIdCounter = 0;\n\n/**\n * Simulate transactions using the transaction simulation API.\n *\n * @param chainId - The chain ID to simulate transactions on.\n * @param request - The request to simulate transactions.\n * @returns The response from the simulation API.\n */\nexport async function simulateTransactions(\n chainId: Hex,\n request: SimulationRequest,\n): Promise<SimulationResponse> {\n const url = await getSimulationUrl(chainId);\n\n log('Sending request', url, request);\n\n const requestId = requestIdCounter;\n requestIdCounter += 1;\n\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify({\n id: String(requestId),\n jsonrpc: '2.0',\n method: RPC_METHOD,\n params: [request],\n }),\n });\n\n const responseJson = await response.json();\n\n log('Received response', responseJson);\n\n if (responseJson.error) {\n const { code, message } = responseJson.error;\n throw new SimulationError(message, code);\n }\n\n return responseJson?.result;\n}\n\n/**\n * Get the URL for the transaction simulation API.\n *\n * @param chainId - The chain ID to get the URL for.\n * @returns The URL for the transaction simulation API.\n */\nasync function getSimulationUrl(chainId: Hex): Promise<string> {\n const networkData = await getNetworkData();\n const chainIdDecimal = convertHexToDecimal(chainId);\n const network = networkData[chainIdDecimal];\n\n if (!network?.confirmations) {\n log('Chain is not supported', chainId);\n throw new SimulationChainNotSupportedError(chainId);\n }\n\n return getUrl(network.network);\n}\n\n/**\n * Retrieve the supported network data from the simulation API.\n *\n * @returns The network data response from the simulation API.\n */\nasync function getNetworkData(): Promise<SimulationNetworkResponse> {\n const url = `${getUrl('ethereum-mainnet')}${ENDPOINT_NETWORKS}`;\n const response = await fetch(url);\n return response.json();\n}\n\n/**\n * Generate the URL for the specified subdomain in the simulation API.\n *\n * @param subdomain - The subdomain to generate the URL for.\n * @returns The URL for the transaction simulation API.\n */\nfunction getUrl(subdomain: string): string {\n return BASE_URL.replace('{0}', subdomain);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"simulation-api.cjs","sourceRoot":"","sources":["../../src/api/simulation-api.ts"],"names":[],"mappings":";;;AAAA,iEAAiE;AACj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Y;IAC1C,MAAM,WAAW,GAAG,MAAM,cAAc,EAAE,CAAC;IAC3C,MAAM,cAAc,GAAG,IAAA,sCAAmB,EAAC,OAAO,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,WAAW,CAAC,cAAc,CAAC,CAAC;IAE5C,IAAI,CAAC,OAAO,EAAE,aAAa,EAAE;QAC3B,GAAG,CAAC,wBAAwB,EAAE,OAAO,CAAC,CAAC;QACvC,MAAM,IAAI,yCAAgC,CAAC,OAAO,CAAC,CAAC;KACrD;IAED,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACjC,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,cAAc;IAC3B,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,kBAAkB,CAAC,GAAG,iBAAiB,EAAE,CAAC;IAChE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC;AAED;;;;;GAKG;AACH,SAAS,MAAM,CAAC,SAAiB;IAC/B,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport { SimulationChainNotSupportedError, SimulationError } from '../errors';\nimport { projectLogger } from '../logger';\n\nconst log = createModuleLogger(projectLogger, 'simulation-api');\n\nconst RPC_METHOD = 'infura_simulateTransactions';\nconst BASE_URL = 'https://tx-sentinel-{0}.api.cx.metamask.io/';\nconst ENDPOINT_NETWORKS = 'networks';\n\n/** Single transaction to simulate in a simulation API request. */\nexport type SimulationRequestTransaction = {\n authorizationList?: {\n /** Address of a smart contract that contains the code to be set. */\n address: Hex;\n\n /** Address of the account being upgraded. */\n from: Hex;\n }[];\n\n /** Data to send with the transaction. */\n data?: Hex;\n\n /** Sender of the transaction. */\n from: Hex;\n\n /** Gas limit for the transaction. */\n gas?: Hex;\n\n /** Maximum fee per gas for the transaction. */\n maxFeePerGas?: Hex;\n\n /** Maximum priority fee per gas for the transaction. */\n maxPriorityFeePerGas?: Hex;\n\n /** Recipient of the transaction. */\n to?: Hex;\n\n /** Value to send with the transaction. */\n value?: Hex;\n};\n\n/** Request to the simulation API to simulate transactions. */\nexport type SimulationRequest = {\n /**\n * Transactions to be sequentially simulated.\n * State changes impact subsequent transactions in the list.\n */\n transactions: SimulationRequestTransaction[];\n\n blockOverrides?: {\n time?: Hex;\n };\n\n /**\n * Overrides to the state of the blockchain, keyed by address.\n */\n overrides?: {\n [address: Hex]: {\n /** Override the code for an address. */\n code?: Hex;\n\n /** Overrides to the storage slots for an address. */\n stateDiff?: {\n [slot: Hex]: Hex;\n };\n };\n };\n\n /**\n * Whether to include available token fees.\n */\n suggestFees?: {\n /* Whether to estimate gas for the transaction being submitted via a delegation. */\n with7702?: boolean;\n\n /* Whether to include the gas fee of the token transfer. */\n withFeeTransfer?: boolean;\n\n /* Whether to include the native transfer if available. */\n withTransfer?: boolean;\n };\n\n /**\n * Whether to include call traces in the response.\n * Defaults to false.\n */\n withCallTrace?: boolean;\n\n /**\n * Whether to include event logs in the response.\n * Defaults to false.\n */\n withLogs?: boolean;\n};\n\n/** Raw event log emitted by a simulated transaction. */\nexport type SimulationResponseLog = {\n /** Address of the account that created the event. */\n address: Hex;\n\n /** Raw data in the event that is not indexed. */\n data: Hex;\n\n /** Raw indexed data from the event. */\n topics: Hex[];\n};\n\n/** Call trace of a single simulated transaction. */\nexport type SimulationResponseCallTrace = {\n /** Nested calls. */\n calls: SimulationResponseCallTrace[];\n\n /** Raw event logs created by the call. */\n logs: SimulationResponseLog[];\n};\n\n/**\n * Changes to the blockchain state.\n * Keyed by account address.\n */\nexport type SimulationResponseStateDiff = {\n [address: Hex]: {\n /** Native balance of the account. */\n balance?: Hex;\n\n /** Nonce of the account. */\n nonce?: Hex;\n\n /** Storage values per slot. */\n storage?: {\n [slot: Hex]: Hex;\n };\n };\n};\n\nexport type SimulationResponseTokenFee = {\n /** Token data independent of current transaction. */\n token: {\n /** Address of the token contract. */\n address: Hex;\n\n /** Decimals of the token. */\n decimals: number;\n\n /** Symbol of the token. */\n symbol: string;\n };\n\n /** Amount of tokens needed to pay for gas. */\n balanceNeededToken: Hex;\n\n /** Current token balance of sender. */\n currentBalanceToken: Hex;\n\n /** Account address that token should be transferred to. */\n feeRecipient: Hex;\n\n /** Conversation rate of 1 token to native WEI. */\n rateWei: Hex;\n\n /** Estimated gas limit required for fee transfer. */\n transferEstimate: Hex;\n};\n\n/** Response from the simulation API for a single transaction. */\nexport type SimulationResponseTransaction = {\n /** Hierarchy of call data including nested calls and logs. */\n callTrace?: SimulationResponseCallTrace;\n\n /** An error message indicating the transaction could not be simulated. */\n error?: string;\n\n /** Recommended gas fees for the transaction. */\n fees?: {\n /** Gas limit for the fee level. */\n gas: Hex;\n\n /** Maximum fee per gas for the fee level. */\n maxFeePerGas: Hex;\n\n /** Maximum priority fee per gas for the fee level. */\n maxPriorityFeePerGas: Hex;\n\n /** Token fee data for the fee level. */\n tokenFees: SimulationResponseTokenFee[];\n }[];\n\n /** Required `gasLimit` for the transaction. */\n gasLimit?: Hex;\n\n /** Total gas used by the transaction. */\n gasUsed?: Hex;\n\n /** Return value of the transaction, such as the balance if calling balanceOf. */\n return: Hex;\n\n /** Changes to the blockchain state. */\n stateDiff?: {\n /** Initial blockchain state before the transaction. */\n pre?: SimulationResponseStateDiff;\n\n /** Updated blockchain state after the transaction. */\n post?: SimulationResponseStateDiff;\n };\n};\n\n/** Response from the simulation API. */\nexport type SimulationResponse = {\n /** Simulation data for each transaction in the request. */\n transactions: SimulationResponseTransaction[];\n};\n\n/** Data for a network supported by the Simulation API. */\ntype SimulationNetwork = {\n /** Subdomain of the API for the network. */\n network: string;\n\n /** Whether the network supports confirmation simulations. */\n confirmations: boolean;\n};\n\n/** Response from the simulation API containing supported networks. */\ntype SimulationNetworkResponse = {\n [chainIdDecimal: string]: SimulationNetwork;\n};\n\nlet requestIdCounter = 0;\n\n/**\n * Simulate transactions using the transaction simulation API.\n *\n * @param chainId - The chain ID to simulate transactions on.\n * @param request - The request to simulate transactions.\n * @returns The response from the simulation API.\n */\nexport async function simulateTransactions(\n chainId: Hex,\n request: SimulationRequest,\n): Promise<SimulationResponse> {\n const url = await getSimulationUrl(chainId);\n\n log('Sending request', url, request);\n\n const requestId = requestIdCounter;\n requestIdCounter += 1;\n\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify({\n id: String(requestId),\n jsonrpc: '2.0',\n method: RPC_METHOD,\n params: [request],\n }),\n });\n\n const responseJson = await response.json();\n\n log('Received response', responseJson);\n\n if (responseJson.error) {\n const { code, message } = responseJson.error;\n throw new SimulationError(message, code);\n }\n\n return responseJson?.result;\n}\n\n/**\n * Get the URL for the transaction simulation API.\n *\n * @param chainId - The chain ID to get the URL for.\n * @returns The URL for the transaction simulation API.\n */\nasync function getSimulationUrl(chainId: Hex): Promise<string> {\n const networkData = await getNetworkData();\n const chainIdDecimal = convertHexToDecimal(chainId);\n const network = networkData[chainIdDecimal];\n\n if (!network?.confirmations) {\n log('Chain is not supported', chainId);\n throw new SimulationChainNotSupportedError(chainId);\n }\n\n return getUrl(network.network);\n}\n\n/**\n * Retrieve the supported network data from the simulation API.\n *\n * @returns The network data response from the simulation API.\n */\nasync function getNetworkData(): Promise<SimulationNetworkResponse> {\n const url = `${getUrl('ethereum-mainnet')}${ENDPOINT_NETWORKS}`;\n const response = await fetch(url);\n return response.json();\n}\n\n/**\n * Generate the URL for the specified subdomain in the simulation API.\n *\n * @param subdomain - The subdomain to generate the URL for.\n * @returns The URL for the transaction simulation API.\n */\nfunction getUrl(subdomain: string): string {\n return BASE_URL.replace('{0}', subdomain);\n}\n"]}
|
|
@@ -134,7 +134,9 @@ export type SimulationResponseTransaction = {
|
|
|
134
134
|
/** Token fee data for the fee level. */
|
|
135
135
|
tokenFees: SimulationResponseTokenFee[];
|
|
136
136
|
}[];
|
|
137
|
-
/**
|
|
137
|
+
/** Required `gasLimit` for the transaction. */
|
|
138
|
+
gasLimit?: Hex;
|
|
139
|
+
/** Total gas used by the transaction. */
|
|
138
140
|
gasUsed?: Hex;
|
|
139
141
|
/** Return value of the transaction, such as the balance if calling balanceOf. */
|
|
140
142
|
return: Hex;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation-api.d.cts","sourceRoot":"","sources":["../../src/api/simulation-api.ts"],"names":[],"mappings":"AACA,OAAO,EAAsB,KAAK,GAAG,EAAE,wBAAwB;AAW/D,mEAAmE;AACnE,MAAM,MAAM,4BAA4B,GAAG;IACzC,iBAAiB,CAAC,EAAE;QAClB,oEAAoE;QACpE,OAAO,EAAE,GAAG,CAAC;QAEb,6CAA6C;QAC7C,IAAI,EAAE,GAAG,CAAC;KACX,EAAE,CAAC;IAEJ,yCAAyC;IACzC,IAAI,CAAC,EAAE,GAAG,CAAC;IAEX,iCAAiC;IACjC,IAAI,EAAE,GAAG,CAAC;IAEV,qCAAqC;IACrC,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV,+CAA+C;IAC/C,YAAY,CAAC,EAAE,GAAG,CAAC;IAEnB,wDAAwD;IACxD,oBAAoB,CAAC,EAAE,GAAG,CAAC;IAE3B,oCAAoC;IACpC,EAAE,CAAC,EAAE,GAAG,CAAC;IAET,0CAA0C;IAC1C,KAAK,CAAC,EAAE,GAAG,CAAC;CACb,CAAC;AAEF,8DAA8D;AAC9D,MAAM,MAAM,iBAAiB,GAAG;IAC9B;;;OAGG;IACH,YAAY,EAAE,4BAA4B,EAAE,CAAC;IAE7C,cAAc,CAAC,EAAE;QACf,IAAI,CAAC,EAAE,GAAG,CAAC;KACZ,CAAC;IAEF;;OAEG;IACH,SAAS,CAAC,EAAE;QACV,CAAC,OAAO,EAAE,GAAG,GAAG;YACd,wCAAwC;YACxC,IAAI,CAAC,EAAE,GAAG,CAAC;YAEX,qDAAqD;YACrD,SAA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,EAAE,GAAG,CAAC;IAEZ,uCAAuC;IACvC,SAAS,CAAC,EAAE;QACV,uDAAuD;QACvD,GAAG,CAAC,EAAE,2BAA2B,CAAC;QAElC,sDAAsD;QACtD,IAAI,CAAC,EAAE,2BAA2B,CAAC;KACpC,CAAC;CACH,CAAC;AAEF,wCAAwC;AACxC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,2DAA2D;IAC3D,YAAY,EAAE,6BAA6B,EAAE,CAAC;CAC/C,CAAC;AAkBF;;;;;;GAMG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,GAAG,EACZ,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,kBAAkB,CAAC,CA4B7B"}
|
|
@@ -134,7 +134,9 @@ export type SimulationResponseTransaction = {
|
|
|
134
134
|
/** Token fee data for the fee level. */
|
|
135
135
|
tokenFees: SimulationResponseTokenFee[];
|
|
136
136
|
}[];
|
|
137
|
-
/**
|
|
137
|
+
/** Required `gasLimit` for the transaction. */
|
|
138
|
+
gasLimit?: Hex;
|
|
139
|
+
/** Total gas used by the transaction. */
|
|
138
140
|
gasUsed?: Hex;
|
|
139
141
|
/** Return value of the transaction, such as the balance if calling balanceOf. */
|
|
140
142
|
return: Hex;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation-api.d.mts","sourceRoot":"","sources":["../../src/api/simulation-api.ts"],"names":[],"mappings":"AACA,OAAO,EAAsB,KAAK,GAAG,EAAE,wBAAwB;AAW/D,mEAAmE;AACnE,MAAM,MAAM,4BAA4B,GAAG;IACzC,iBAAiB,CAAC,EAAE;QAClB,oEAAoE;QACpE,OAAO,EAAE,GAAG,CAAC;QAEb,6CAA6C;QAC7C,IAAI,EAAE,GAAG,CAAC;KACX,EAAE,CAAC;IAEJ,yCAAyC;IACzC,IAAI,CAAC,EAAE,GAAG,CAAC;IAEX,iCAAiC;IACjC,IAAI,EAAE,GAAG,CAAC;IAEV,qCAAqC;IACrC,GAAG,CAAC,EAAE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AW,GAAG,MAAM,cAAc,EAAE,CAAC;IAC3C,MAAM,cAAc,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,WAAW,CAAC,cAAc,CAAC,CAAC;IAE5C,IAAI,CAAC,OAAO,EAAE,aAAa,EAAE;QAC3B,GAAG,CAAC,wBAAwB,EAAE,OAAO,CAAC,CAAC;QACvC,MAAM,IAAI,gCAAgC,CAAC,OAAO,CAAC,CAAC;KACrD;IAED,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACjC,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,cAAc;IAC3B,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,kBAAkB,CAAC,GAAG,iBAAiB,EAAE,CAAC;IAChE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC;AAED;;;;;GAKG;AACH,SAAS,MAAM,CAAC,SAAiB;IAC/B,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport { SimulationChainNotSupportedError, SimulationError } from '../errors';\nimport { projectLogger } from '../logger';\n\nconst log = createModuleLogger(projectLogger, 'simulation-api');\n\nconst RPC_METHOD = 'infura_simulateTransactions';\nconst BASE_URL = 'https://tx-sentinel-{0}.api.cx.metamask.io/';\nconst ENDPOINT_NETWORKS = 'networks';\n\n/** Single transaction to simulate in a simulation API request. */\nexport type SimulationRequestTransaction = {\n authorizationList?: {\n /** Address of a smart contract that contains the code to be set. */\n address: Hex;\n\n /** Address of the account being upgraded. */\n from: Hex;\n }[];\n\n /** Data to send with the transaction. */\n data?: Hex;\n\n /** Sender of the transaction. */\n from: Hex;\n\n /** Gas limit for the transaction. */\n gas?: Hex;\n\n /** Maximum fee per gas for the transaction. */\n maxFeePerGas?: Hex;\n\n /** Maximum priority fee per gas for the transaction. */\n maxPriorityFeePerGas?: Hex;\n\n /** Recipient of the transaction. */\n to?: Hex;\n\n /** Value to send with the transaction. */\n value?: Hex;\n};\n\n/** Request to the simulation API to simulate transactions. */\nexport type SimulationRequest = {\n /**\n * Transactions to be sequentially simulated.\n * State changes impact subsequent transactions in the list.\n */\n transactions: SimulationRequestTransaction[];\n\n blockOverrides?: {\n time?: Hex;\n };\n\n /**\n * Overrides to the state of the blockchain, keyed by address.\n */\n overrides?: {\n [address: Hex]: {\n /** Override the code for an address. */\n code?: Hex;\n\n /** Overrides to the storage slots for an address. */\n stateDiff?: {\n [slot: Hex]: Hex;\n };\n };\n };\n\n /**\n * Whether to include available token fees.\n */\n suggestFees?: {\n /* Whether to estimate gas for the transaction being submitted via a delegation. */\n with7702?: boolean;\n\n /* Whether to include the gas fee of the token transfer. */\n withFeeTransfer?: boolean;\n\n /* Whether to include the native transfer if available. */\n withTransfer?: boolean;\n };\n\n /**\n * Whether to include call traces in the response.\n * Defaults to false.\n */\n withCallTrace?: boolean;\n\n /**\n * Whether to include event logs in the response.\n * Defaults to false.\n */\n withLogs?: boolean;\n};\n\n/** Raw event log emitted by a simulated transaction. */\nexport type SimulationResponseLog = {\n /** Address of the account that created the event. */\n address: Hex;\n\n /** Raw data in the event that is not indexed. */\n data: Hex;\n\n /** Raw indexed data from the event. */\n topics: Hex[];\n};\n\n/** Call trace of a single simulated transaction. */\nexport type SimulationResponseCallTrace = {\n /** Nested calls. */\n calls: SimulationResponseCallTrace[];\n\n /** Raw event logs created by the call. */\n logs: SimulationResponseLog[];\n};\n\n/**\n * Changes to the blockchain state.\n * Keyed by account address.\n */\nexport type SimulationResponseStateDiff = {\n [address: Hex]: {\n /** Native balance of the account. */\n balance?: Hex;\n\n /** Nonce of the account. */\n nonce?: Hex;\n\n /** Storage values per slot. */\n storage?: {\n [slot: Hex]: Hex;\n };\n };\n};\n\nexport type SimulationResponseTokenFee = {\n /** Token data independent of current transaction. */\n token: {\n /** Address of the token contract. */\n address: Hex;\n\n /** Decimals of the token. */\n decimals: number;\n\n /** Symbol of the token. */\n symbol: string;\n };\n\n /** Amount of tokens needed to pay for gas. */\n balanceNeededToken: Hex;\n\n /** Current token balance of sender. */\n currentBalanceToken: Hex;\n\n /** Account address that token should be transferred to. */\n feeRecipient: Hex;\n\n /** Conversation rate of 1 token to native WEI. */\n rateWei: Hex;\n\n /** Estimated gas limit required for fee transfer. */\n transferEstimate: Hex;\n};\n\n/** Response from the simulation API for a single transaction. */\nexport type SimulationResponseTransaction = {\n /** Hierarchy of call data including nested calls and logs. */\n callTrace?: SimulationResponseCallTrace;\n\n /** An error message indicating the transaction could not be simulated. */\n error?: string;\n\n /** Recommended gas fees for the transaction. */\n fees?: {\n /** Gas limit for the fee level. */\n gas: Hex;\n\n /** Maximum fee per gas for the fee level. */\n maxFeePerGas: Hex;\n\n /** Maximum priority fee per gas for the fee level. */\n maxPriorityFeePerGas: Hex;\n\n /** Token fee data for the fee level. */\n tokenFees: SimulationResponseTokenFee[];\n }[];\n\n /** The total gas used by the transaction. */\n gasUsed?: Hex;\n\n /** Return value of the transaction, such as the balance if calling balanceOf. */\n return: Hex;\n\n /** Changes to the blockchain state. */\n stateDiff?: {\n /** Initial blockchain state before the transaction. */\n pre?: SimulationResponseStateDiff;\n\n /** Updated blockchain state after the transaction. */\n post?: SimulationResponseStateDiff;\n };\n};\n\n/** Response from the simulation API. */\nexport type SimulationResponse = {\n /** Simulation data for each transaction in the request. */\n transactions: SimulationResponseTransaction[];\n};\n\n/** Data for a network supported by the Simulation API. */\ntype SimulationNetwork = {\n /** Subdomain of the API for the network. */\n network: string;\n\n /** Whether the network supports confirmation simulations. */\n confirmations: boolean;\n};\n\n/** Response from the simulation API containing supported networks. */\ntype SimulationNetworkResponse = {\n [chainIdDecimal: string]: SimulationNetwork;\n};\n\nlet requestIdCounter = 0;\n\n/**\n * Simulate transactions using the transaction simulation API.\n *\n * @param chainId - The chain ID to simulate transactions on.\n * @param request - The request to simulate transactions.\n * @returns The response from the simulation API.\n */\nexport async function simulateTransactions(\n chainId: Hex,\n request: SimulationRequest,\n): Promise<SimulationResponse> {\n const url = await getSimulationUrl(chainId);\n\n log('Sending request', url, request);\n\n const requestId = requestIdCounter;\n requestIdCounter += 1;\n\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify({\n id: String(requestId),\n jsonrpc: '2.0',\n method: RPC_METHOD,\n params: [request],\n }),\n });\n\n const responseJson = await response.json();\n\n log('Received response', responseJson);\n\n if (responseJson.error) {\n const { code, message } = responseJson.error;\n throw new SimulationError(message, code);\n }\n\n return responseJson?.result;\n}\n\n/**\n * Get the URL for the transaction simulation API.\n *\n * @param chainId - The chain ID to get the URL for.\n * @returns The URL for the transaction simulation API.\n */\nasync function getSimulationUrl(chainId: Hex): Promise<string> {\n const networkData = await getNetworkData();\n const chainIdDecimal = convertHexToDecimal(chainId);\n const network = networkData[chainIdDecimal];\n\n if (!network?.confirmations) {\n log('Chain is not supported', chainId);\n throw new SimulationChainNotSupportedError(chainId);\n }\n\n return getUrl(network.network);\n}\n\n/**\n * Retrieve the supported network data from the simulation API.\n *\n * @returns The network data response from the simulation API.\n */\nasync function getNetworkData(): Promise<SimulationNetworkResponse> {\n const url = `${getUrl('ethereum-mainnet')}${ENDPOINT_NETWORKS}`;\n const response = await fetch(url);\n return response.json();\n}\n\n/**\n * Generate the URL for the specified subdomain in the simulation API.\n *\n * @param subdomain - The subdomain to generate the URL for.\n * @returns The URL for the transaction simulation API.\n */\nfunction getUrl(subdomain: string): string {\n return BASE_URL.replace('{0}', subdomain);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"simulation-api.mjs","sourceRoot":"","sources":["../../src/api/simulation-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mCAAmC;AACjE,OAAO,EAAE,kBAAkB,EAAY,wBAAwB;AAE/D,OAAO,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K,UAAU,gBAAgB,CAAC,OAAY;IAC1C,MAAM,WAAW,GAAG,MAAM,cAAc,EAAE,CAAC;IAC3C,MAAM,cAAc,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,WAAW,CAAC,cAAc,CAAC,CAAC;IAE5C,IAAI,CAAC,OAAO,EAAE,aAAa,EAAE;QAC3B,GAAG,CAAC,wBAAwB,EAAE,OAAO,CAAC,CAAC;QACvC,MAAM,IAAI,gCAAgC,CAAC,OAAO,CAAC,CAAC;KACrD;IAED,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACjC,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,cAAc;IAC3B,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,kBAAkB,CAAC,GAAG,iBAAiB,EAAE,CAAC;IAChE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC;AAED;;;;;GAKG;AACH,SAAS,MAAM,CAAC,SAAiB;IAC/B,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport { SimulationChainNotSupportedError, SimulationError } from '../errors';\nimport { projectLogger } from '../logger';\n\nconst log = createModuleLogger(projectLogger, 'simulation-api');\n\nconst RPC_METHOD = 'infura_simulateTransactions';\nconst BASE_URL = 'https://tx-sentinel-{0}.api.cx.metamask.io/';\nconst ENDPOINT_NETWORKS = 'networks';\n\n/** Single transaction to simulate in a simulation API request. */\nexport type SimulationRequestTransaction = {\n authorizationList?: {\n /** Address of a smart contract that contains the code to be set. */\n address: Hex;\n\n /** Address of the account being upgraded. */\n from: Hex;\n }[];\n\n /** Data to send with the transaction. */\n data?: Hex;\n\n /** Sender of the transaction. */\n from: Hex;\n\n /** Gas limit for the transaction. */\n gas?: Hex;\n\n /** Maximum fee per gas for the transaction. */\n maxFeePerGas?: Hex;\n\n /** Maximum priority fee per gas for the transaction. */\n maxPriorityFeePerGas?: Hex;\n\n /** Recipient of the transaction. */\n to?: Hex;\n\n /** Value to send with the transaction. */\n value?: Hex;\n};\n\n/** Request to the simulation API to simulate transactions. */\nexport type SimulationRequest = {\n /**\n * Transactions to be sequentially simulated.\n * State changes impact subsequent transactions in the list.\n */\n transactions: SimulationRequestTransaction[];\n\n blockOverrides?: {\n time?: Hex;\n };\n\n /**\n * Overrides to the state of the blockchain, keyed by address.\n */\n overrides?: {\n [address: Hex]: {\n /** Override the code for an address. */\n code?: Hex;\n\n /** Overrides to the storage slots for an address. */\n stateDiff?: {\n [slot: Hex]: Hex;\n };\n };\n };\n\n /**\n * Whether to include available token fees.\n */\n suggestFees?: {\n /* Whether to estimate gas for the transaction being submitted via a delegation. */\n with7702?: boolean;\n\n /* Whether to include the gas fee of the token transfer. */\n withFeeTransfer?: boolean;\n\n /* Whether to include the native transfer if available. */\n withTransfer?: boolean;\n };\n\n /**\n * Whether to include call traces in the response.\n * Defaults to false.\n */\n withCallTrace?: boolean;\n\n /**\n * Whether to include event logs in the response.\n * Defaults to false.\n */\n withLogs?: boolean;\n};\n\n/** Raw event log emitted by a simulated transaction. */\nexport type SimulationResponseLog = {\n /** Address of the account that created the event. */\n address: Hex;\n\n /** Raw data in the event that is not indexed. */\n data: Hex;\n\n /** Raw indexed data from the event. */\n topics: Hex[];\n};\n\n/** Call trace of a single simulated transaction. */\nexport type SimulationResponseCallTrace = {\n /** Nested calls. */\n calls: SimulationResponseCallTrace[];\n\n /** Raw event logs created by the call. */\n logs: SimulationResponseLog[];\n};\n\n/**\n * Changes to the blockchain state.\n * Keyed by account address.\n */\nexport type SimulationResponseStateDiff = {\n [address: Hex]: {\n /** Native balance of the account. */\n balance?: Hex;\n\n /** Nonce of the account. */\n nonce?: Hex;\n\n /** Storage values per slot. */\n storage?: {\n [slot: Hex]: Hex;\n };\n };\n};\n\nexport type SimulationResponseTokenFee = {\n /** Token data independent of current transaction. */\n token: {\n /** Address of the token contract. */\n address: Hex;\n\n /** Decimals of the token. */\n decimals: number;\n\n /** Symbol of the token. */\n symbol: string;\n };\n\n /** Amount of tokens needed to pay for gas. */\n balanceNeededToken: Hex;\n\n /** Current token balance of sender. */\n currentBalanceToken: Hex;\n\n /** Account address that token should be transferred to. */\n feeRecipient: Hex;\n\n /** Conversation rate of 1 token to native WEI. */\n rateWei: Hex;\n\n /** Estimated gas limit required for fee transfer. */\n transferEstimate: Hex;\n};\n\n/** Response from the simulation API for a single transaction. */\nexport type SimulationResponseTransaction = {\n /** Hierarchy of call data including nested calls and logs. */\n callTrace?: SimulationResponseCallTrace;\n\n /** An error message indicating the transaction could not be simulated. */\n error?: string;\n\n /** Recommended gas fees for the transaction. */\n fees?: {\n /** Gas limit for the fee level. */\n gas: Hex;\n\n /** Maximum fee per gas for the fee level. */\n maxFeePerGas: Hex;\n\n /** Maximum priority fee per gas for the fee level. */\n maxPriorityFeePerGas: Hex;\n\n /** Token fee data for the fee level. */\n tokenFees: SimulationResponseTokenFee[];\n }[];\n\n /** Required `gasLimit` for the transaction. */\n gasLimit?: Hex;\n\n /** Total gas used by the transaction. */\n gasUsed?: Hex;\n\n /** Return value of the transaction, such as the balance if calling balanceOf. */\n return: Hex;\n\n /** Changes to the blockchain state. */\n stateDiff?: {\n /** Initial blockchain state before the transaction. */\n pre?: SimulationResponseStateDiff;\n\n /** Updated blockchain state after the transaction. */\n post?: SimulationResponseStateDiff;\n };\n};\n\n/** Response from the simulation API. */\nexport type SimulationResponse = {\n /** Simulation data for each transaction in the request. */\n transactions: SimulationResponseTransaction[];\n};\n\n/** Data for a network supported by the Simulation API. */\ntype SimulationNetwork = {\n /** Subdomain of the API for the network. */\n network: string;\n\n /** Whether the network supports confirmation simulations. */\n confirmations: boolean;\n};\n\n/** Response from the simulation API containing supported networks. */\ntype SimulationNetworkResponse = {\n [chainIdDecimal: string]: SimulationNetwork;\n};\n\nlet requestIdCounter = 0;\n\n/**\n * Simulate transactions using the transaction simulation API.\n *\n * @param chainId - The chain ID to simulate transactions on.\n * @param request - The request to simulate transactions.\n * @returns The response from the simulation API.\n */\nexport async function simulateTransactions(\n chainId: Hex,\n request: SimulationRequest,\n): Promise<SimulationResponse> {\n const url = await getSimulationUrl(chainId);\n\n log('Sending request', url, request);\n\n const requestId = requestIdCounter;\n requestIdCounter += 1;\n\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify({\n id: String(requestId),\n jsonrpc: '2.0',\n method: RPC_METHOD,\n params: [request],\n }),\n });\n\n const responseJson = await response.json();\n\n log('Received response', responseJson);\n\n if (responseJson.error) {\n const { code, message } = responseJson.error;\n throw new SimulationError(message, code);\n }\n\n return responseJson?.result;\n}\n\n/**\n * Get the URL for the transaction simulation API.\n *\n * @param chainId - The chain ID to get the URL for.\n * @returns The URL for the transaction simulation API.\n */\nasync function getSimulationUrl(chainId: Hex): Promise<string> {\n const networkData = await getNetworkData();\n const chainIdDecimal = convertHexToDecimal(chainId);\n const network = networkData[chainIdDecimal];\n\n if (!network?.confirmations) {\n log('Chain is not supported', chainId);\n throw new SimulationChainNotSupportedError(chainId);\n }\n\n return getUrl(network.network);\n}\n\n/**\n * Retrieve the supported network data from the simulation API.\n *\n * @returns The network data response from the simulation API.\n */\nasync function getNetworkData(): Promise<SimulationNetworkResponse> {\n const url = `${getUrl('ethereum-mainnet')}${ENDPOINT_NETWORKS}`;\n const response = await fetch(url);\n return response.json();\n}\n\n/**\n * Generate the URL for the specified subdomain in the simulation API.\n *\n * @param subdomain - The subdomain to generate the URL for.\n * @returns The URL for the transaction simulation API.\n */\nfunction getUrl(subdomain: string): string {\n return BASE_URL.replace('{0}', subdomain);\n}\n"]}
|
|
@@ -13,16 +13,16 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
13
13
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
14
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
15
|
};
|
|
16
|
-
var _IncomingTransactionHelper_instances, _IncomingTransactionHelper_getCache, _IncomingTransactionHelper_getCurrentAccount, _IncomingTransactionHelper_getLocalTransactions, _IncomingTransactionHelper_includeTokenTransfers, _IncomingTransactionHelper_isEnabled, _IncomingTransactionHelper_isRunning, _IncomingTransactionHelper_queryEntireHistory, _IncomingTransactionHelper_remoteTransactionSource, _IncomingTransactionHelper_timeoutId, _IncomingTransactionHelper_trimTransactions, _IncomingTransactionHelper_updateCache, _IncomingTransactionHelper_updateTransactions, _IncomingTransactionHelper_onInterval, _IncomingTransactionHelper_sortTransactionsByTime, _IncomingTransactionHelper_canStart;
|
|
16
|
+
var _IncomingTransactionHelper_instances, _IncomingTransactionHelper_getCache, _IncomingTransactionHelper_getCurrentAccount, _IncomingTransactionHelper_getLocalTransactions, _IncomingTransactionHelper_includeTokenTransfers, _IncomingTransactionHelper_isEnabled, _IncomingTransactionHelper_isRunning, _IncomingTransactionHelper_messenger, _IncomingTransactionHelper_queryEntireHistory, _IncomingTransactionHelper_remoteTransactionSource, _IncomingTransactionHelper_timeoutId, _IncomingTransactionHelper_trimTransactions, _IncomingTransactionHelper_updateCache, _IncomingTransactionHelper_updateTransactions, _IncomingTransactionHelper_onInterval, _IncomingTransactionHelper_sortTransactionsByTime, _IncomingTransactionHelper_canStart, _IncomingTransactionHelper_getInterval;
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
18
|
exports.IncomingTransactionHelper = void 0;
|
|
19
19
|
// This package purposefully relies on Node's EventEmitter module.
|
|
20
20
|
// eslint-disable-next-line import-x/no-nodejs-modules
|
|
21
21
|
const events_1 = __importDefault(require("events"));
|
|
22
22
|
const logger_1 = require("../logger.cjs");
|
|
23
|
-
const
|
|
23
|
+
const feature_flags_1 = require("../utils/feature-flags.cjs");
|
|
24
24
|
class IncomingTransactionHelper {
|
|
25
|
-
constructor({ getCache, getCurrentAccount, getLocalTransactions, includeTokenTransfers, isEnabled, queryEntireHistory, remoteTransactionSource, trimTransactions, updateCache, updateTransactions, }) {
|
|
25
|
+
constructor({ getCache, getCurrentAccount, getLocalTransactions, includeTokenTransfers, isEnabled, messenger, queryEntireHistory, remoteTransactionSource, trimTransactions, updateCache, updateTransactions, }) {
|
|
26
26
|
_IncomingTransactionHelper_instances.add(this);
|
|
27
27
|
_IncomingTransactionHelper_getCache.set(this, void 0);
|
|
28
28
|
_IncomingTransactionHelper_getCurrentAccount.set(this, void 0);
|
|
@@ -30,6 +30,7 @@ class IncomingTransactionHelper {
|
|
|
30
30
|
_IncomingTransactionHelper_includeTokenTransfers.set(this, void 0);
|
|
31
31
|
_IncomingTransactionHelper_isEnabled.set(this, void 0);
|
|
32
32
|
_IncomingTransactionHelper_isRunning.set(this, void 0);
|
|
33
|
+
_IncomingTransactionHelper_messenger.set(this, void 0);
|
|
33
34
|
_IncomingTransactionHelper_queryEntireHistory.set(this, void 0);
|
|
34
35
|
_IncomingTransactionHelper_remoteTransactionSource.set(this, void 0);
|
|
35
36
|
_IncomingTransactionHelper_timeoutId.set(this, void 0);
|
|
@@ -43,6 +44,7 @@ class IncomingTransactionHelper {
|
|
|
43
44
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_includeTokenTransfers, includeTokenTransfers, "f");
|
|
44
45
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_isEnabled, isEnabled ?? (() => true), "f");
|
|
45
46
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_isRunning, false, "f");
|
|
47
|
+
__classPrivateFieldSet(this, _IncomingTransactionHelper_messenger, messenger, "f");
|
|
46
48
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_queryEntireHistory, queryEntireHistory, "f");
|
|
47
49
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_remoteTransactionSource, remoteTransactionSource, "f");
|
|
48
50
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_trimTransactions, trimTransactions, "f");
|
|
@@ -56,9 +58,10 @@ class IncomingTransactionHelper {
|
|
|
56
58
|
if (!__classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_canStart).call(this)) {
|
|
57
59
|
return;
|
|
58
60
|
}
|
|
59
|
-
(
|
|
61
|
+
const interval = __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_getInterval).call(this);
|
|
62
|
+
(0, logger_1.incomingTransactionsLogger)('Starting polling', { interval });
|
|
60
63
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
61
|
-
__classPrivateFieldSet(this, _IncomingTransactionHelper_timeoutId, setTimeout(() => __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_onInterval).call(this),
|
|
64
|
+
__classPrivateFieldSet(this, _IncomingTransactionHelper_timeoutId, setTimeout(() => __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_onInterval).call(this), interval), "f");
|
|
62
65
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_isRunning, true, "f");
|
|
63
66
|
(0, logger_1.incomingTransactionsLogger)('Started polling');
|
|
64
67
|
}
|
|
@@ -130,7 +133,7 @@ class IncomingTransactionHelper {
|
|
|
130
133
|
}
|
|
131
134
|
}
|
|
132
135
|
exports.IncomingTransactionHelper = IncomingTransactionHelper;
|
|
133
|
-
_IncomingTransactionHelper_getCache = new WeakMap(), _IncomingTransactionHelper_getCurrentAccount = new WeakMap(), _IncomingTransactionHelper_getLocalTransactions = new WeakMap(), _IncomingTransactionHelper_includeTokenTransfers = new WeakMap(), _IncomingTransactionHelper_isEnabled = new WeakMap(), _IncomingTransactionHelper_isRunning = new WeakMap(), _IncomingTransactionHelper_queryEntireHistory = new WeakMap(), _IncomingTransactionHelper_remoteTransactionSource = new WeakMap(), _IncomingTransactionHelper_timeoutId = new WeakMap(), _IncomingTransactionHelper_trimTransactions = new WeakMap(), _IncomingTransactionHelper_updateCache = new WeakMap(), _IncomingTransactionHelper_updateTransactions = new WeakMap(), _IncomingTransactionHelper_instances = new WeakSet(), _IncomingTransactionHelper_onInterval = async function _IncomingTransactionHelper_onInterval() {
|
|
136
|
+
_IncomingTransactionHelper_getCache = new WeakMap(), _IncomingTransactionHelper_getCurrentAccount = new WeakMap(), _IncomingTransactionHelper_getLocalTransactions = new WeakMap(), _IncomingTransactionHelper_includeTokenTransfers = new WeakMap(), _IncomingTransactionHelper_isEnabled = new WeakMap(), _IncomingTransactionHelper_isRunning = new WeakMap(), _IncomingTransactionHelper_messenger = new WeakMap(), _IncomingTransactionHelper_queryEntireHistory = new WeakMap(), _IncomingTransactionHelper_remoteTransactionSource = new WeakMap(), _IncomingTransactionHelper_timeoutId = new WeakMap(), _IncomingTransactionHelper_trimTransactions = new WeakMap(), _IncomingTransactionHelper_updateCache = new WeakMap(), _IncomingTransactionHelper_updateTransactions = new WeakMap(), _IncomingTransactionHelper_instances = new WeakSet(), _IncomingTransactionHelper_onInterval = async function _IncomingTransactionHelper_onInterval() {
|
|
134
137
|
try {
|
|
135
138
|
await this.update({ isInterval: true });
|
|
136
139
|
}
|
|
@@ -138,12 +141,15 @@ _IncomingTransactionHelper_getCache = new WeakMap(), _IncomingTransactionHelper_
|
|
|
138
141
|
console.error('Error while checking incoming transactions', error);
|
|
139
142
|
}
|
|
140
143
|
if (__classPrivateFieldGet(this, _IncomingTransactionHelper_isRunning, "f")) {
|
|
144
|
+
__classPrivateFieldSet(this, _IncomingTransactionHelper_timeoutId, setTimeout(
|
|
141
145
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
142
|
-
|
|
146
|
+
() => __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_onInterval).call(this), __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_getInterval).call(this)), "f");
|
|
143
147
|
}
|
|
144
148
|
}, _IncomingTransactionHelper_sortTransactionsByTime = function _IncomingTransactionHelper_sortTransactionsByTime(transactions) {
|
|
145
149
|
transactions.sort((a, b) => (a.time < b.time ? -1 : 1));
|
|
146
150
|
}, _IncomingTransactionHelper_canStart = function _IncomingTransactionHelper_canStart() {
|
|
147
151
|
return __classPrivateFieldGet(this, _IncomingTransactionHelper_isEnabled, "f").call(this);
|
|
152
|
+
}, _IncomingTransactionHelper_getInterval = function _IncomingTransactionHelper_getInterval() {
|
|
153
|
+
return (0, feature_flags_1.getIncomingTransactionsPollingInterval)(__classPrivateFieldGet(this, _IncomingTransactionHelper_messenger, "f"));
|
|
148
154
|
};
|
|
149
155
|
//# sourceMappingURL=IncomingTransactionHelper.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IncomingTransactionHelper.cjs","sourceRoot":"","sources":["../../src/helpers/IncomingTransactionHelper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAEA,kEAAkE;AAClE,sDAAsD;AACtD,oDAAkC;AAElC,0CAA8D;AAU9D,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAE,CAAC,CAAC,aAAa;AAEzC,MAAa,yBAAyB;IA+BpC,YAAY,EACV,QAAQ,EACR,iBAAiB,EACjB,oBAAoB,EACpB,qBAAqB,EACrB,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,gBAAgB,EAChB,WAAW,EACX,kBAAkB,GAcnB;;QApDQ,sDAAyC;QAEzC,+DAEP;QAEO,kEAA+C;QAE/C,mEAAiC;QAEjC,uDAA0B;QAEnC,uDAAoB;QAEX,gEAA8B;QAE9B,qEAAkD;QAE3D,uDAAqB;QAEZ,8DAEc;QAEd,yDAAqE;QAErE,gEAA8B;QA2BrC,IAAI,CAAC,GAAG,GAAG,IAAI,gBAAY,EAAE,CAAC;QAE9B,uBAAA,IAAI,uCAAa,QAAQ,MAAA,CAAC;QAC1B,uBAAA,IAAI,gDAAsB,iBAAiB,MAAA,CAAC;QAC5C,uBAAA,IAAI,mDAAyB,oBAAoB,MA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F,MAAM,IAAI,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;KACzC;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,CAAC,KAAK,CAAC,4CAA4C,EAAE,KAAK,CAAC,CAAC;KACpE;IAED,IAAI,uBAAA,IAAI,4CAAW,EAAE;QACnB,kEAAkE;QAClE,uBAAA,IAAI,wCAAc,UAAU,CAAC,GAAG,EAAE,CAAC,uBAAA,IAAI,mFAAY,MAAhB,IAAI,CAAc,EAAE,QAAQ,CAAC,MAAA,CAAC;KAClE;AACH,CAAC,iHA2FuB,YAA+B;IACrD,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,CAAC;IAGC,OAAO,uBAAA,IAAI,4CAAW,MAAf,IAAI,CAAa,CAAC;AAC3B,CAAC","sourcesContent":["import type { AccountsController } from '@metamask/accounts-controller';\nimport type { Hex } from '@metamask/utils';\n// This package purposefully relies on Node's EventEmitter module.\n// eslint-disable-next-line import-x/no-nodejs-modules\nimport EventEmitter from 'events';\n\nimport { incomingTransactionsLogger as log } from '../logger';\nimport type { RemoteTransactionSource, TransactionMeta } from '../types';\n\nexport type IncomingTransactionOptions = {\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n updateTransactions?: boolean;\n};\n\nconst INTERVAL = 1000 * 30; // 30 Seconds\n\nexport class IncomingTransactionHelper {\n hub: EventEmitter;\n\n readonly #getCache: () => Record<string, unknown>;\n\n readonly #getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n\n readonly #getLocalTransactions: () => TransactionMeta[];\n\n readonly #includeTokenTransfers?: boolean;\n\n readonly #isEnabled: () => boolean;\n\n #isRunning: boolean;\n\n readonly #queryEntireHistory?: boolean;\n\n readonly #remoteTransactionSource: RemoteTransactionSource;\n\n #timeoutId?: unknown;\n\n readonly #trimTransactions: (\n transactions: TransactionMeta[],\n ) => TransactionMeta[];\n\n readonly #updateCache: (fn: (cache: Record<string, unknown>) => void) => void;\n\n readonly #updateTransactions?: boolean;\n\n constructor({\n getCache,\n getCurrentAccount,\n getLocalTransactions,\n includeTokenTransfers,\n isEnabled,\n queryEntireHistory,\n remoteTransactionSource,\n trimTransactions,\n updateCache,\n updateTransactions,\n }: {\n getCache: () => Record<string, unknown>;\n getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n getLocalTransactions: () => TransactionMeta[];\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n remoteTransactionSource: RemoteTransactionSource;\n trimTransactions: (transactions: TransactionMeta[]) => TransactionMeta[];\n updateCache: (fn: (cache: Record<string, unknown>) => void) => void;\n updateTransactions?: boolean;\n }) {\n this.hub = new EventEmitter();\n\n this.#getCache = getCache;\n this.#getCurrentAccount = getCurrentAccount;\n this.#getLocalTransactions = getLocalTransactions;\n this.#includeTokenTransfers = includeTokenTransfers;\n this.#isEnabled = isEnabled ?? (() => true);\n this.#isRunning = false;\n this.#queryEntireHistory = queryEntireHistory;\n this.#remoteTransactionSource = remoteTransactionSource;\n this.#trimTransactions = trimTransactions;\n this.#updateCache = updateCache;\n this.#updateTransactions = updateTransactions;\n }\n\n start() {\n if (this.#isRunning) {\n return;\n }\n\n if (!this.#canStart()) {\n return;\n }\n\n log('Starting polling');\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#timeoutId = setTimeout(() => this.#onInterval(), INTERVAL);\n this.#isRunning = true;\n\n log('Started polling');\n }\n\n stop() {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId as number);\n }\n\n if (!this.#isRunning) {\n return;\n }\n\n this.#isRunning = false;\n\n log('Stopped polling');\n }\n\n async #onInterval() {\n try {\n await this.update({ isInterval: true });\n } catch (error) {\n console.error('Error while checking incoming transactions', error);\n }\n\n if (this.#isRunning) {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#timeoutId = setTimeout(() => this.#onInterval(), INTERVAL);\n }\n }\n\n async update({ isInterval }: { isInterval?: boolean } = {}): Promise<void> {\n log('Checking for incoming transactions', {\n isInterval: Boolean(isInterval),\n });\n\n if (!this.#canStart()) {\n return;\n }\n\n const account = this.#getCurrentAccount();\n const cache = this.#getCache();\n const includeTokenTransfers = this.#includeTokenTransfers ?? true;\n const queryEntireHistory = this.#queryEntireHistory ?? true;\n const updateTransactions = this.#updateTransactions ?? false;\n\n let remoteTransactions: TransactionMeta[] = [];\n\n try {\n remoteTransactions =\n await this.#remoteTransactionSource.fetchTransactions({\n address: account.address as Hex,\n cache,\n includeTokenTransfers,\n queryEntireHistory,\n updateCache: this.#updateCache,\n updateTransactions,\n });\n } catch (error: unknown) {\n log('Error while fetching remote transactions', error);\n return;\n }\n\n if (!remoteTransactions.length) {\n return;\n }\n\n this.#sortTransactionsByTime(remoteTransactions);\n\n log(\n 'Found potential transactions',\n remoteTransactions.length,\n remoteTransactions,\n );\n\n const localTransactions = this.#getLocalTransactions();\n\n const uniqueTransactions = remoteTransactions.filter(\n (tx) =>\n !localTransactions.some(\n (currentTx) =>\n currentTx.hash?.toLowerCase() === tx.hash?.toLowerCase() &&\n currentTx.txParams.from?.toLowerCase() ===\n tx.txParams.from?.toLowerCase() &&\n currentTx.type === tx.type,\n ),\n );\n\n if (!uniqueTransactions.length) {\n log('All transactions are already known');\n return;\n }\n\n log(\n 'Found unique transactions',\n uniqueTransactions.length,\n uniqueTransactions,\n );\n\n const trimmedTransactions = this.#trimTransactions([\n ...uniqueTransactions,\n ...localTransactions,\n ]);\n\n const uniqueTransactionIds = uniqueTransactions.map((tx) => tx.id);\n\n const newTransactions = trimmedTransactions.filter((tx) =>\n uniqueTransactionIds.includes(tx.id),\n );\n\n if (!newTransactions.length) {\n log('All unique transactions truncated due to limit');\n return;\n }\n\n log('Adding new transactions', newTransactions.length, newTransactions);\n\n this.hub.emit('transactions', newTransactions);\n }\n\n #sortTransactionsByTime(transactions: TransactionMeta[]) {\n transactions.sort((a, b) => (a.time < b.time ? -1 : 1));\n }\n\n #canStart(): boolean {\n return this.#isEnabled();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"IncomingTransactionHelper.cjs","sourceRoot":"","sources":["../../src/helpers/IncomingTransactionHelper.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAEA,kEAAkE;AAClE,sDAAsD;AACtD,oDAAkC;AAGlC,0CAA8D;AAE9D,8DAAgF;AAShF,MAAa,yBAAyB;IAiCpC,YAAY,EACV,QAAQ,EACR,iBAAiB,EACjB,oBAAoB,EACpB,qBAAqB,EACrB,SAAS,EACT,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,gBAAgB,EAChB,WAAW,EACX,kBAAkB,GAenB;;QAxDQ,sDAAyC;QAEzC,+DAEP;QAEO,kEAA+C;QAE/C,mEAAiC;QAEjC,uDAA0B;QAEnC,uDAAoB;QAEX,uDAA2C;QAE3C,gEAA8B;QAE9B,qEAAkD;QAE3D,uDAAqB;QAEZ,8DAEc;QAEd,yDAAqE;QAErE,gEAA8B;QA6BrC,IAAI,CAAC,GAAG,GAAG,IAAI,gBAAY,EAAE,CAAC;QAE9B,uBAAA,IAAI,uCAAa,QAAQ,MAAA,CAAC;QAC1B,uBAAA,IAAI,gDAAsB,iBAAiB,MAAA,CAAC;QAC5C,uBAAA,IAAI,mDAAyB,oBAAoB,MAAA,CAAC;QAClD,uBAAA,IAAI,oDAA0B,qBAAqB,MAAA,CAAC;QACpD,uBAAA,IAAI,wCAAc,SAAS,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,MAAA,CAAC;QAC5C,uBAAA,IAAI,wCAAc,KAAK,MAAA,CAAC;QACxB,uBAAA,IAAI,wCAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,I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;QACd,OAAO,CAAC,KAAK,CAAC,4CAA4C,EAAE,KAAK,CAAC,CAAC;KACpE;IAED,IAAI,uBAAA,IAAI,4CAAW,EAAE;QACnB,uBAAA,IAAI,wCAAc,UAAU;QAC1B,kEAAkE;QAClE,GAAG,EAAE,CAAC,uBAAA,IAAI,mFAAY,MAAhB,IAAI,CAAc,EACxB,uBAAA,IAAI,oFAAa,MAAjB,IAAI,CAAe,CACpB,MAAA,CAAC;KACH;AACH,CAAC,iHA2FuB,YAA+B;IACrD,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,CAAC;IAGC,OAAO,uBAAA,IAAI,4CAAW,MAAf,IAAI,CAAa,CAAC;AAC3B,CAAC;IAGC,OAAO,IAAA,sDAAsC,EAAC,uBAAA,IAAI,4CAAW,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import type { AccountsController } from '@metamask/accounts-controller';\nimport type { Hex } from '@metamask/utils';\n// This package purposefully relies on Node's EventEmitter module.\n// eslint-disable-next-line import-x/no-nodejs-modules\nimport EventEmitter from 'events';\n\nimport type { TransactionControllerMessenger } from '..';\nimport { incomingTransactionsLogger as log } from '../logger';\nimport type { RemoteTransactionSource, TransactionMeta } from '../types';\nimport { getIncomingTransactionsPollingInterval } from '../utils/feature-flags';\n\nexport type IncomingTransactionOptions = {\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n updateTransactions?: boolean;\n};\n\nexport class IncomingTransactionHelper {\n hub: EventEmitter;\n\n readonly #getCache: () => Record<string, unknown>;\n\n readonly #getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n\n readonly #getLocalTransactions: () => TransactionMeta[];\n\n readonly #includeTokenTransfers?: boolean;\n\n readonly #isEnabled: () => boolean;\n\n #isRunning: boolean;\n\n readonly #messenger: TransactionControllerMessenger;\n\n readonly #queryEntireHistory?: boolean;\n\n readonly #remoteTransactionSource: RemoteTransactionSource;\n\n #timeoutId?: unknown;\n\n readonly #trimTransactions: (\n transactions: TransactionMeta[],\n ) => TransactionMeta[];\n\n readonly #updateCache: (fn: (cache: Record<string, unknown>) => void) => void;\n\n readonly #updateTransactions?: boolean;\n\n constructor({\n getCache,\n getCurrentAccount,\n getLocalTransactions,\n includeTokenTransfers,\n isEnabled,\n messenger,\n queryEntireHistory,\n remoteTransactionSource,\n trimTransactions,\n updateCache,\n updateTransactions,\n }: {\n getCache: () => Record<string, unknown>;\n getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n getLocalTransactions: () => TransactionMeta[];\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n messenger: TransactionControllerMessenger;\n queryEntireHistory?: boolean;\n remoteTransactionSource: RemoteTransactionSource;\n trimTransactions: (transactions: TransactionMeta[]) => TransactionMeta[];\n updateCache: (fn: (cache: Record<string, unknown>) => void) => void;\n updateTransactions?: boolean;\n }) {\n this.hub = new EventEmitter();\n\n this.#getCache = getCache;\n this.#getCurrentAccount = getCurrentAccount;\n this.#getLocalTransactions = getLocalTransactions;\n this.#includeTokenTransfers = includeTokenTransfers;\n this.#isEnabled = isEnabled ?? (() => true);\n this.#isRunning = false;\n this.#messenger = messenger;\n this.#queryEntireHistory = queryEntireHistory;\n this.#remoteTransactionSource = remoteTransactionSource;\n this.#trimTransactions = trimTransactions;\n this.#updateCache = updateCache;\n this.#updateTransactions = updateTransactions;\n }\n\n start() {\n if (this.#isRunning) {\n return;\n }\n\n if (!this.#canStart()) {\n return;\n }\n\n const interval = this.#getInterval();\n\n log('Starting polling', { interval });\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#timeoutId = setTimeout(() => this.#onInterval(), interval);\n this.#isRunning = true;\n\n log('Started polling');\n }\n\n stop() {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId as number);\n }\n\n if (!this.#isRunning) {\n return;\n }\n\n this.#isRunning = false;\n\n log('Stopped polling');\n }\n\n async #onInterval() {\n try {\n await this.update({ isInterval: true });\n } catch (error) {\n console.error('Error while checking incoming transactions', error);\n }\n\n if (this.#isRunning) {\n this.#timeoutId = setTimeout(\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n () => this.#onInterval(),\n this.#getInterval(),\n );\n }\n }\n\n async update({ isInterval }: { isInterval?: boolean } = {}): Promise<void> {\n log('Checking for incoming transactions', {\n isInterval: Boolean(isInterval),\n });\n\n if (!this.#canStart()) {\n return;\n }\n\n const account = this.#getCurrentAccount();\n const cache = this.#getCache();\n const includeTokenTransfers = this.#includeTokenTransfers ?? true;\n const queryEntireHistory = this.#queryEntireHistory ?? true;\n const updateTransactions = this.#updateTransactions ?? false;\n\n let remoteTransactions: TransactionMeta[] = [];\n\n try {\n remoteTransactions =\n await this.#remoteTransactionSource.fetchTransactions({\n address: account.address as Hex,\n cache,\n includeTokenTransfers,\n queryEntireHistory,\n updateCache: this.#updateCache,\n updateTransactions,\n });\n } catch (error: unknown) {\n log('Error while fetching remote transactions', error);\n return;\n }\n\n if (!remoteTransactions.length) {\n return;\n }\n\n this.#sortTransactionsByTime(remoteTransactions);\n\n log(\n 'Found potential transactions',\n remoteTransactions.length,\n remoteTransactions,\n );\n\n const localTransactions = this.#getLocalTransactions();\n\n const uniqueTransactions = remoteTransactions.filter(\n (tx) =>\n !localTransactions.some(\n (currentTx) =>\n currentTx.hash?.toLowerCase() === tx.hash?.toLowerCase() &&\n currentTx.txParams.from?.toLowerCase() ===\n tx.txParams.from?.toLowerCase() &&\n currentTx.type === tx.type,\n ),\n );\n\n if (!uniqueTransactions.length) {\n log('All transactions are already known');\n return;\n }\n\n log(\n 'Found unique transactions',\n uniqueTransactions.length,\n uniqueTransactions,\n );\n\n const trimmedTransactions = this.#trimTransactions([\n ...uniqueTransactions,\n ...localTransactions,\n ]);\n\n const uniqueTransactionIds = uniqueTransactions.map((tx) => tx.id);\n\n const newTransactions = trimmedTransactions.filter((tx) =>\n uniqueTransactionIds.includes(tx.id),\n );\n\n if (!newTransactions.length) {\n log('All unique transactions truncated due to limit');\n return;\n }\n\n log('Adding new transactions', newTransactions.length, newTransactions);\n\n this.hub.emit('transactions', newTransactions);\n }\n\n #sortTransactionsByTime(transactions: TransactionMeta[]) {\n transactions.sort((a, b) => (a.time < b.time ? -1 : 1));\n }\n\n #canStart(): boolean {\n return this.#isEnabled();\n }\n\n #getInterval(): number {\n return getIncomingTransactionsPollingInterval(this.#messenger);\n }\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
import type { AccountsController } from "@metamask/accounts-controller";
|
|
3
3
|
import EventEmitter from "events";
|
|
4
|
+
import type { TransactionControllerMessenger } from "../index.cjs";
|
|
4
5
|
import type { RemoteTransactionSource, TransactionMeta } from "../types.cjs";
|
|
5
6
|
export type IncomingTransactionOptions = {
|
|
6
7
|
includeTokenTransfers?: boolean;
|
|
@@ -11,12 +12,13 @@ export type IncomingTransactionOptions = {
|
|
|
11
12
|
export declare class IncomingTransactionHelper {
|
|
12
13
|
#private;
|
|
13
14
|
hub: EventEmitter;
|
|
14
|
-
constructor({ getCache, getCurrentAccount, getLocalTransactions, includeTokenTransfers, isEnabled, queryEntireHistory, remoteTransactionSource, trimTransactions, updateCache, updateTransactions, }: {
|
|
15
|
+
constructor({ getCache, getCurrentAccount, getLocalTransactions, includeTokenTransfers, isEnabled, messenger, queryEntireHistory, remoteTransactionSource, trimTransactions, updateCache, updateTransactions, }: {
|
|
15
16
|
getCache: () => Record<string, unknown>;
|
|
16
17
|
getCurrentAccount: () => ReturnType<AccountsController['getSelectedAccount']>;
|
|
17
18
|
getLocalTransactions: () => TransactionMeta[];
|
|
18
19
|
includeTokenTransfers?: boolean;
|
|
19
20
|
isEnabled?: () => boolean;
|
|
21
|
+
messenger: TransactionControllerMessenger;
|
|
20
22
|
queryEntireHistory?: boolean;
|
|
21
23
|
remoteTransactionSource: RemoteTransactionSource;
|
|
22
24
|
trimTransactions: (transactions: TransactionMeta[]) => TransactionMeta[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IncomingTransactionHelper.d.cts","sourceRoot":"","sources":["../../src/helpers/IncomingTransactionHelper.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sCAAsC;AAIxE,OAAO,YAAY,eAAe;
|
|
1
|
+
{"version":3,"file":"IncomingTransactionHelper.d.cts","sourceRoot":"","sources":["../../src/helpers/IncomingTransactionHelper.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sCAAsC;AAIxE,OAAO,YAAY,eAAe;AAElC,OAAO,KAAK,EAAE,8BAA8B,EAAE,qBAAW;AAEzD,OAAO,KAAK,EAAE,uBAAuB,EAAE,eAAe,EAAE,qBAAiB;AAGzE,MAAM,MAAM,0BAA0B,GAAG;IACvC,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;IAC1B,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAEF,qBAAa,yBAAyB;;IACpC,GAAG,EAAE,YAAY,CAAC;gBAgCN,EACV,QAAQ,EACR,iBAAiB,EACjB,oBAAoB,EACpB,qBAAqB,EACrB,SAAS,EACT,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,gBAAgB,EAChB,WAAW,EACX,kBAAkB,GACnB,EAAE;QACD,QAAQ,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACxC,iBAAiB,EAAE,MAAM,UAAU,CACjC,kBAAkB,CAAC,oBAAoB,CAAC,CACzC,CAAC;QACF,oBAAoB,EAAE,MAAM,eAAe,EAAE,CAAC;QAC9C,qBAAqB,CAAC,EAAE,OAAO,CAAC;QAChC,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;QAC1B,SAAS,EAAE,8BAA8B,CAAC;QAC1C,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,uBAAuB,EAAE,uBAAuB,CAAC;QACjD,gBAAgB,EAAE,CAAC,YAAY,EAAE,eAAe,EAAE,KAAK,eAAe,EAAE,CAAC;QACzE,WAAW,EAAE,CAAC,EAAE,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,KAAK,IAAI,CAAC;QACpE,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B;IAiBD,KAAK;IAoBL,IAAI;IA8BE,MAAM,CAAC,EAAE,UAAU,EAAE,GAAE;QAAE,UAAU,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAoG3E"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
import type { AccountsController } from "@metamask/accounts-controller";
|
|
3
3
|
import EventEmitter from "events";
|
|
4
|
+
import type { TransactionControllerMessenger } from "../index.mjs";
|
|
4
5
|
import type { RemoteTransactionSource, TransactionMeta } from "../types.mjs";
|
|
5
6
|
export type IncomingTransactionOptions = {
|
|
6
7
|
includeTokenTransfers?: boolean;
|
|
@@ -11,12 +12,13 @@ export type IncomingTransactionOptions = {
|
|
|
11
12
|
export declare class IncomingTransactionHelper {
|
|
12
13
|
#private;
|
|
13
14
|
hub: EventEmitter;
|
|
14
|
-
constructor({ getCache, getCurrentAccount, getLocalTransactions, includeTokenTransfers, isEnabled, queryEntireHistory, remoteTransactionSource, trimTransactions, updateCache, updateTransactions, }: {
|
|
15
|
+
constructor({ getCache, getCurrentAccount, getLocalTransactions, includeTokenTransfers, isEnabled, messenger, queryEntireHistory, remoteTransactionSource, trimTransactions, updateCache, updateTransactions, }: {
|
|
15
16
|
getCache: () => Record<string, unknown>;
|
|
16
17
|
getCurrentAccount: () => ReturnType<AccountsController['getSelectedAccount']>;
|
|
17
18
|
getLocalTransactions: () => TransactionMeta[];
|
|
18
19
|
includeTokenTransfers?: boolean;
|
|
19
20
|
isEnabled?: () => boolean;
|
|
21
|
+
messenger: TransactionControllerMessenger;
|
|
20
22
|
queryEntireHistory?: boolean;
|
|
21
23
|
remoteTransactionSource: RemoteTransactionSource;
|
|
22
24
|
trimTransactions: (transactions: TransactionMeta[]) => TransactionMeta[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IncomingTransactionHelper.d.mts","sourceRoot":"","sources":["../../src/helpers/IncomingTransactionHelper.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sCAAsC;AAIxE,OAAO,YAAY,eAAe;
|
|
1
|
+
{"version":3,"file":"IncomingTransactionHelper.d.mts","sourceRoot":"","sources":["../../src/helpers/IncomingTransactionHelper.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sCAAsC;AAIxE,OAAO,YAAY,eAAe;AAElC,OAAO,KAAK,EAAE,8BAA8B,EAAE,qBAAW;AAEzD,OAAO,KAAK,EAAE,uBAAuB,EAAE,eAAe,EAAE,qBAAiB;AAGzE,MAAM,MAAM,0BAA0B,GAAG;IACvC,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;IAC1B,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B,CAAC;AAEF,qBAAa,yBAAyB;;IACpC,GAAG,EAAE,YAAY,CAAC;gBAgCN,EACV,QAAQ,EACR,iBAAiB,EACjB,oBAAoB,EACpB,qBAAqB,EACrB,SAAS,EACT,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,gBAAgB,EAChB,WAAW,EACX,kBAAkB,GACnB,EAAE;QACD,QAAQ,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACxC,iBAAiB,EAAE,MAAM,UAAU,CACjC,kBAAkB,CAAC,oBAAoB,CAAC,CACzC,CAAC;QACF,oBAAoB,EAAE,MAAM,eAAe,EAAE,CAAC;QAC9C,qBAAqB,CAAC,EAAE,OAAO,CAAC;QAChC,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;QAC1B,SAAS,EAAE,8BAA8B,CAAC;QAC1C,kBAAkB,CAAC,EAAE,OAAO,CAAC;QAC7B,uBAAuB,EAAE,uBAAuB,CAAC;QACjD,gBAAgB,EAAE,CAAC,YAAY,EAAE,eAAe,EAAE,KAAK,eAAe,EAAE,CAAC;QACzE,WAAW,EAAE,CAAC,EAAE,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,KAAK,IAAI,CAAC;QACpE,kBAAkB,CAAC,EAAE,OAAO,CAAC;KAC9B;IAiBD,KAAK;IAoBL,IAAI;IA8BE,MAAM,CAAC,EAAE,UAAU,EAAE,GAAE;QAAE,UAAU,CAAC,EAAE,OAAO,CAAA;KAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAoG3E"}
|
|
@@ -9,14 +9,14 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _IncomingTransactionHelper_instances, _IncomingTransactionHelper_getCache, _IncomingTransactionHelper_getCurrentAccount, _IncomingTransactionHelper_getLocalTransactions, _IncomingTransactionHelper_includeTokenTransfers, _IncomingTransactionHelper_isEnabled, _IncomingTransactionHelper_isRunning, _IncomingTransactionHelper_queryEntireHistory, _IncomingTransactionHelper_remoteTransactionSource, _IncomingTransactionHelper_timeoutId, _IncomingTransactionHelper_trimTransactions, _IncomingTransactionHelper_updateCache, _IncomingTransactionHelper_updateTransactions, _IncomingTransactionHelper_onInterval, _IncomingTransactionHelper_sortTransactionsByTime, _IncomingTransactionHelper_canStart;
|
|
12
|
+
var _IncomingTransactionHelper_instances, _IncomingTransactionHelper_getCache, _IncomingTransactionHelper_getCurrentAccount, _IncomingTransactionHelper_getLocalTransactions, _IncomingTransactionHelper_includeTokenTransfers, _IncomingTransactionHelper_isEnabled, _IncomingTransactionHelper_isRunning, _IncomingTransactionHelper_messenger, _IncomingTransactionHelper_queryEntireHistory, _IncomingTransactionHelper_remoteTransactionSource, _IncomingTransactionHelper_timeoutId, _IncomingTransactionHelper_trimTransactions, _IncomingTransactionHelper_updateCache, _IncomingTransactionHelper_updateTransactions, _IncomingTransactionHelper_onInterval, _IncomingTransactionHelper_sortTransactionsByTime, _IncomingTransactionHelper_canStart, _IncomingTransactionHelper_getInterval;
|
|
13
13
|
// This package purposefully relies on Node's EventEmitter module.
|
|
14
14
|
// eslint-disable-next-line import-x/no-nodejs-modules
|
|
15
15
|
import EventEmitter from "events";
|
|
16
16
|
import { incomingTransactionsLogger as log } from "../logger.mjs";
|
|
17
|
-
|
|
17
|
+
import { getIncomingTransactionsPollingInterval } from "../utils/feature-flags.mjs";
|
|
18
18
|
export class IncomingTransactionHelper {
|
|
19
|
-
constructor({ getCache, getCurrentAccount, getLocalTransactions, includeTokenTransfers, isEnabled, queryEntireHistory, remoteTransactionSource, trimTransactions, updateCache, updateTransactions, }) {
|
|
19
|
+
constructor({ getCache, getCurrentAccount, getLocalTransactions, includeTokenTransfers, isEnabled, messenger, queryEntireHistory, remoteTransactionSource, trimTransactions, updateCache, updateTransactions, }) {
|
|
20
20
|
_IncomingTransactionHelper_instances.add(this);
|
|
21
21
|
_IncomingTransactionHelper_getCache.set(this, void 0);
|
|
22
22
|
_IncomingTransactionHelper_getCurrentAccount.set(this, void 0);
|
|
@@ -24,6 +24,7 @@ export class IncomingTransactionHelper {
|
|
|
24
24
|
_IncomingTransactionHelper_includeTokenTransfers.set(this, void 0);
|
|
25
25
|
_IncomingTransactionHelper_isEnabled.set(this, void 0);
|
|
26
26
|
_IncomingTransactionHelper_isRunning.set(this, void 0);
|
|
27
|
+
_IncomingTransactionHelper_messenger.set(this, void 0);
|
|
27
28
|
_IncomingTransactionHelper_queryEntireHistory.set(this, void 0);
|
|
28
29
|
_IncomingTransactionHelper_remoteTransactionSource.set(this, void 0);
|
|
29
30
|
_IncomingTransactionHelper_timeoutId.set(this, void 0);
|
|
@@ -37,6 +38,7 @@ export class IncomingTransactionHelper {
|
|
|
37
38
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_includeTokenTransfers, includeTokenTransfers, "f");
|
|
38
39
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_isEnabled, isEnabled ?? (() => true), "f");
|
|
39
40
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_isRunning, false, "f");
|
|
41
|
+
__classPrivateFieldSet(this, _IncomingTransactionHelper_messenger, messenger, "f");
|
|
40
42
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_queryEntireHistory, queryEntireHistory, "f");
|
|
41
43
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_remoteTransactionSource, remoteTransactionSource, "f");
|
|
42
44
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_trimTransactions, trimTransactions, "f");
|
|
@@ -50,9 +52,10 @@ export class IncomingTransactionHelper {
|
|
|
50
52
|
if (!__classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_canStart).call(this)) {
|
|
51
53
|
return;
|
|
52
54
|
}
|
|
53
|
-
|
|
55
|
+
const interval = __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_getInterval).call(this);
|
|
56
|
+
log('Starting polling', { interval });
|
|
54
57
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
55
|
-
__classPrivateFieldSet(this, _IncomingTransactionHelper_timeoutId, setTimeout(() => __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_onInterval).call(this),
|
|
58
|
+
__classPrivateFieldSet(this, _IncomingTransactionHelper_timeoutId, setTimeout(() => __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_onInterval).call(this), interval), "f");
|
|
56
59
|
__classPrivateFieldSet(this, _IncomingTransactionHelper_isRunning, true, "f");
|
|
57
60
|
log('Started polling');
|
|
58
61
|
}
|
|
@@ -123,7 +126,7 @@ export class IncomingTransactionHelper {
|
|
|
123
126
|
this.hub.emit('transactions', newTransactions);
|
|
124
127
|
}
|
|
125
128
|
}
|
|
126
|
-
_IncomingTransactionHelper_getCache = new WeakMap(), _IncomingTransactionHelper_getCurrentAccount = new WeakMap(), _IncomingTransactionHelper_getLocalTransactions = new WeakMap(), _IncomingTransactionHelper_includeTokenTransfers = new WeakMap(), _IncomingTransactionHelper_isEnabled = new WeakMap(), _IncomingTransactionHelper_isRunning = new WeakMap(), _IncomingTransactionHelper_queryEntireHistory = new WeakMap(), _IncomingTransactionHelper_remoteTransactionSource = new WeakMap(), _IncomingTransactionHelper_timeoutId = new WeakMap(), _IncomingTransactionHelper_trimTransactions = new WeakMap(), _IncomingTransactionHelper_updateCache = new WeakMap(), _IncomingTransactionHelper_updateTransactions = new WeakMap(), _IncomingTransactionHelper_instances = new WeakSet(), _IncomingTransactionHelper_onInterval = async function _IncomingTransactionHelper_onInterval() {
|
|
129
|
+
_IncomingTransactionHelper_getCache = new WeakMap(), _IncomingTransactionHelper_getCurrentAccount = new WeakMap(), _IncomingTransactionHelper_getLocalTransactions = new WeakMap(), _IncomingTransactionHelper_includeTokenTransfers = new WeakMap(), _IncomingTransactionHelper_isEnabled = new WeakMap(), _IncomingTransactionHelper_isRunning = new WeakMap(), _IncomingTransactionHelper_messenger = new WeakMap(), _IncomingTransactionHelper_queryEntireHistory = new WeakMap(), _IncomingTransactionHelper_remoteTransactionSource = new WeakMap(), _IncomingTransactionHelper_timeoutId = new WeakMap(), _IncomingTransactionHelper_trimTransactions = new WeakMap(), _IncomingTransactionHelper_updateCache = new WeakMap(), _IncomingTransactionHelper_updateTransactions = new WeakMap(), _IncomingTransactionHelper_instances = new WeakSet(), _IncomingTransactionHelper_onInterval = async function _IncomingTransactionHelper_onInterval() {
|
|
127
130
|
try {
|
|
128
131
|
await this.update({ isInterval: true });
|
|
129
132
|
}
|
|
@@ -131,12 +134,15 @@ _IncomingTransactionHelper_getCache = new WeakMap(), _IncomingTransactionHelper_
|
|
|
131
134
|
console.error('Error while checking incoming transactions', error);
|
|
132
135
|
}
|
|
133
136
|
if (__classPrivateFieldGet(this, _IncomingTransactionHelper_isRunning, "f")) {
|
|
137
|
+
__classPrivateFieldSet(this, _IncomingTransactionHelper_timeoutId, setTimeout(
|
|
134
138
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
135
|
-
|
|
139
|
+
() => __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_onInterval).call(this), __classPrivateFieldGet(this, _IncomingTransactionHelper_instances, "m", _IncomingTransactionHelper_getInterval).call(this)), "f");
|
|
136
140
|
}
|
|
137
141
|
}, _IncomingTransactionHelper_sortTransactionsByTime = function _IncomingTransactionHelper_sortTransactionsByTime(transactions) {
|
|
138
142
|
transactions.sort((a, b) => (a.time < b.time ? -1 : 1));
|
|
139
143
|
}, _IncomingTransactionHelper_canStart = function _IncomingTransactionHelper_canStart() {
|
|
140
144
|
return __classPrivateFieldGet(this, _IncomingTransactionHelper_isEnabled, "f").call(this);
|
|
145
|
+
}, _IncomingTransactionHelper_getInterval = function _IncomingTransactionHelper_getInterval() {
|
|
146
|
+
return getIncomingTransactionsPollingInterval(__classPrivateFieldGet(this, _IncomingTransactionHelper_messenger, "f"));
|
|
141
147
|
};
|
|
142
148
|
//# sourceMappingURL=IncomingTransactionHelper.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,CAAC;IAGC,OAAO,uBAAA,IAAI,4CAAW,MAAf,IAAI,CAAa,CAAC;AAC3B,CAAC","sourcesContent":["import type { AccountsController } from '@metamask/accounts-controller';\nimport type { Hex } from '@metamask/utils';\n// This package purposefully relies on Node's EventEmitter module.\n// eslint-disable-next-line import-x/no-nodejs-modules\nimport EventEmitter from 'events';\n\nimport { incomingTransactionsLogger as log } from '../logger';\nimport type { RemoteTransactionSource, TransactionMeta } from '../types';\n\nexport type IncomingTransactionOptions = {\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n updateTransactions?: boolean;\n};\n\nconst INTERVAL = 1000 * 30; // 30 Seconds\n\nexport class IncomingTransactionHelper {\n hub: EventEmitter;\n\n readonly #getCache: () => Record<string, unknown>;\n\n readonly #getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n\n readonly #getLocalTransactions: () => TransactionMeta[];\n\n readonly #includeTokenTransfers?: boolean;\n\n readonly #isEnabled: () => boolean;\n\n #isRunning: boolean;\n\n readonly #queryEntireHistory?: boolean;\n\n readonly #remoteTransactionSource: RemoteTransactionSource;\n\n #timeoutId?: unknown;\n\n readonly #trimTransactions: (\n transactions: TransactionMeta[],\n ) => TransactionMeta[];\n\n readonly #updateCache: (fn: (cache: Record<string, unknown>) => void) => void;\n\n readonly #updateTransactions?: boolean;\n\n constructor({\n getCache,\n getCurrentAccount,\n getLocalTransactions,\n includeTokenTransfers,\n isEnabled,\n queryEntireHistory,\n remoteTransactionSource,\n trimTransactions,\n updateCache,\n updateTransactions,\n }: {\n getCache: () => Record<string, unknown>;\n getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n getLocalTransactions: () => TransactionMeta[];\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n remoteTransactionSource: RemoteTransactionSource;\n trimTransactions: (transactions: TransactionMeta[]) => TransactionMeta[];\n updateCache: (fn: (cache: Record<string, unknown>) => void) => void;\n updateTransactions?: boolean;\n }) {\n this.hub = new EventEmitter();\n\n this.#getCache = getCache;\n this.#getCurrentAccount = getCurrentAccount;\n this.#getLocalTransactions = getLocalTransactions;\n this.#includeTokenTransfers = includeTokenTransfers;\n this.#isEnabled = isEnabled ?? (() => true);\n this.#isRunning = false;\n this.#queryEntireHistory = queryEntireHistory;\n this.#remoteTransactionSource = remoteTransactionSource;\n this.#trimTransactions = trimTransactions;\n this.#updateCache = updateCache;\n this.#updateTransactions = updateTransactions;\n }\n\n start() {\n if (this.#isRunning) {\n return;\n }\n\n if (!this.#canStart()) {\n return;\n }\n\n log('Starting polling');\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#timeoutId = setTimeout(() => this.#onInterval(), INTERVAL);\n this.#isRunning = true;\n\n log('Started polling');\n }\n\n stop() {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId as number);\n }\n\n if (!this.#isRunning) {\n return;\n }\n\n this.#isRunning = false;\n\n log('Stopped polling');\n }\n\n async #onInterval() {\n try {\n await this.update({ isInterval: true });\n } catch (error) {\n console.error('Error while checking incoming transactions', error);\n }\n\n if (this.#isRunning) {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#timeoutId = setTimeout(() => this.#onInterval(), INTERVAL);\n }\n }\n\n async update({ isInterval }: { isInterval?: boolean } = {}): Promise<void> {\n log('Checking for incoming transactions', {\n isInterval: Boolean(isInterval),\n });\n\n if (!this.#canStart()) {\n return;\n }\n\n const account = this.#getCurrentAccount();\n const cache = this.#getCache();\n const includeTokenTransfers = this.#includeTokenTransfers ?? true;\n const queryEntireHistory = this.#queryEntireHistory ?? true;\n const updateTransactions = this.#updateTransactions ?? false;\n\n let remoteTransactions: TransactionMeta[] = [];\n\n try {\n remoteTransactions =\n await this.#remoteTransactionSource.fetchTransactions({\n address: account.address as Hex,\n cache,\n includeTokenTransfers,\n queryEntireHistory,\n updateCache: this.#updateCache,\n updateTransactions,\n });\n } catch (error: unknown) {\n log('Error while fetching remote transactions', error);\n return;\n }\n\n if (!remoteTransactions.length) {\n return;\n }\n\n this.#sortTransactionsByTime(remoteTransactions);\n\n log(\n 'Found potential transactions',\n remoteTransactions.length,\n remoteTransactions,\n );\n\n const localTransactions = this.#getLocalTransactions();\n\n const uniqueTransactions = remoteTransactions.filter(\n (tx) =>\n !localTransactions.some(\n (currentTx) =>\n currentTx.hash?.toLowerCase() === tx.hash?.toLowerCase() &&\n currentTx.txParams.from?.toLowerCase() ===\n tx.txParams.from?.toLowerCase() &&\n currentTx.type === tx.type,\n ),\n );\n\n if (!uniqueTransactions.length) {\n log('All transactions are already known');\n return;\n }\n\n log(\n 'Found unique transactions',\n uniqueTransactions.length,\n uniqueTransactions,\n );\n\n const trimmedTransactions = this.#trimTransactions([\n ...uniqueTransactions,\n ...localTransactions,\n ]);\n\n const uniqueTransactionIds = uniqueTransactions.map((tx) => tx.id);\n\n const newTransactions = trimmedTransactions.filter((tx) =>\n uniqueTransactionIds.includes(tx.id),\n );\n\n if (!newTransactions.length) {\n log('All unique transactions truncated due to limit');\n return;\n }\n\n log('Adding new transactions', newTransactions.length, newTransactions);\n\n this.hub.emit('transactions', newTransactions);\n }\n\n #sortTransactionsByTime(transactions: TransactionMeta[]) {\n transactions.sort((a, b) => (a.time < b.time ? -1 : 1));\n }\n\n #canStart(): boolean {\n return this.#isEnabled();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"IncomingTransactionHelper.mjs","sourceRoot":"","sources":["../../src/helpers/IncomingTransactionHelper.ts"],"names":[],"mappings":";;;;;;;;;;;;AAEA,kEAAkE;AAClE,sDAAsD;AACtD,OAAO,YAAY,eAAe;AAGlC,OAAO,EAAE,0BAA0B,IAAI,GAAG,EAAE,sBAAkB;AAE9D,OAAO,EAAE,sCAAsC,EAAE,mCAA+B;AAShF,MAAM,OAAO,yBA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C1D,CAAC;IAGC,OAAO,uBAAA,IAAI,4CAAW,MAAf,IAAI,CAAa,CAAC;AAC3B,CAAC;IAGC,OAAO,sCAAsC,CAAC,uBAAA,IAAI,4CAAW,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import type { AccountsController } from '@metamask/accounts-controller';\nimport type { Hex } from '@metamask/utils';\n// This package purposefully relies on Node's EventEmitter module.\n// eslint-disable-next-line import-x/no-nodejs-modules\nimport EventEmitter from 'events';\n\nimport type { TransactionControllerMessenger } from '..';\nimport { incomingTransactionsLogger as log } from '../logger';\nimport type { RemoteTransactionSource, TransactionMeta } from '../types';\nimport { getIncomingTransactionsPollingInterval } from '../utils/feature-flags';\n\nexport type IncomingTransactionOptions = {\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n queryEntireHistory?: boolean;\n updateTransactions?: boolean;\n};\n\nexport class IncomingTransactionHelper {\n hub: EventEmitter;\n\n readonly #getCache: () => Record<string, unknown>;\n\n readonly #getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n\n readonly #getLocalTransactions: () => TransactionMeta[];\n\n readonly #includeTokenTransfers?: boolean;\n\n readonly #isEnabled: () => boolean;\n\n #isRunning: boolean;\n\n readonly #messenger: TransactionControllerMessenger;\n\n readonly #queryEntireHistory?: boolean;\n\n readonly #remoteTransactionSource: RemoteTransactionSource;\n\n #timeoutId?: unknown;\n\n readonly #trimTransactions: (\n transactions: TransactionMeta[],\n ) => TransactionMeta[];\n\n readonly #updateCache: (fn: (cache: Record<string, unknown>) => void) => void;\n\n readonly #updateTransactions?: boolean;\n\n constructor({\n getCache,\n getCurrentAccount,\n getLocalTransactions,\n includeTokenTransfers,\n isEnabled,\n messenger,\n queryEntireHistory,\n remoteTransactionSource,\n trimTransactions,\n updateCache,\n updateTransactions,\n }: {\n getCache: () => Record<string, unknown>;\n getCurrentAccount: () => ReturnType<\n AccountsController['getSelectedAccount']\n >;\n getLocalTransactions: () => TransactionMeta[];\n includeTokenTransfers?: boolean;\n isEnabled?: () => boolean;\n messenger: TransactionControllerMessenger;\n queryEntireHistory?: boolean;\n remoteTransactionSource: RemoteTransactionSource;\n trimTransactions: (transactions: TransactionMeta[]) => TransactionMeta[];\n updateCache: (fn: (cache: Record<string, unknown>) => void) => void;\n updateTransactions?: boolean;\n }) {\n this.hub = new EventEmitter();\n\n this.#getCache = getCache;\n this.#getCurrentAccount = getCurrentAccount;\n this.#getLocalTransactions = getLocalTransactions;\n this.#includeTokenTransfers = includeTokenTransfers;\n this.#isEnabled = isEnabled ?? (() => true);\n this.#isRunning = false;\n this.#messenger = messenger;\n this.#queryEntireHistory = queryEntireHistory;\n this.#remoteTransactionSource = remoteTransactionSource;\n this.#trimTransactions = trimTransactions;\n this.#updateCache = updateCache;\n this.#updateTransactions = updateTransactions;\n }\n\n start() {\n if (this.#isRunning) {\n return;\n }\n\n if (!this.#canStart()) {\n return;\n }\n\n const interval = this.#getInterval();\n\n log('Starting polling', { interval });\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#timeoutId = setTimeout(() => this.#onInterval(), interval);\n this.#isRunning = true;\n\n log('Started polling');\n }\n\n stop() {\n if (this.#timeoutId) {\n clearTimeout(this.#timeoutId as number);\n }\n\n if (!this.#isRunning) {\n return;\n }\n\n this.#isRunning = false;\n\n log('Stopped polling');\n }\n\n async #onInterval() {\n try {\n await this.update({ isInterval: true });\n } catch (error) {\n console.error('Error while checking incoming transactions', error);\n }\n\n if (this.#isRunning) {\n this.#timeoutId = setTimeout(\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n () => this.#onInterval(),\n this.#getInterval(),\n );\n }\n }\n\n async update({ isInterval }: { isInterval?: boolean } = {}): Promise<void> {\n log('Checking for incoming transactions', {\n isInterval: Boolean(isInterval),\n });\n\n if (!this.#canStart()) {\n return;\n }\n\n const account = this.#getCurrentAccount();\n const cache = this.#getCache();\n const includeTokenTransfers = this.#includeTokenTransfers ?? true;\n const queryEntireHistory = this.#queryEntireHistory ?? true;\n const updateTransactions = this.#updateTransactions ?? false;\n\n let remoteTransactions: TransactionMeta[] = [];\n\n try {\n remoteTransactions =\n await this.#remoteTransactionSource.fetchTransactions({\n address: account.address as Hex,\n cache,\n includeTokenTransfers,\n queryEntireHistory,\n updateCache: this.#updateCache,\n updateTransactions,\n });\n } catch (error: unknown) {\n log('Error while fetching remote transactions', error);\n return;\n }\n\n if (!remoteTransactions.length) {\n return;\n }\n\n this.#sortTransactionsByTime(remoteTransactions);\n\n log(\n 'Found potential transactions',\n remoteTransactions.length,\n remoteTransactions,\n );\n\n const localTransactions = this.#getLocalTransactions();\n\n const uniqueTransactions = remoteTransactions.filter(\n (tx) =>\n !localTransactions.some(\n (currentTx) =>\n currentTx.hash?.toLowerCase() === tx.hash?.toLowerCase() &&\n currentTx.txParams.from?.toLowerCase() ===\n tx.txParams.from?.toLowerCase() &&\n currentTx.type === tx.type,\n ),\n );\n\n if (!uniqueTransactions.length) {\n log('All transactions are already known');\n return;\n }\n\n log(\n 'Found unique transactions',\n uniqueTransactions.length,\n uniqueTransactions,\n );\n\n const trimmedTransactions = this.#trimTransactions([\n ...uniqueTransactions,\n ...localTransactions,\n ]);\n\n const uniqueTransactionIds = uniqueTransactions.map((tx) => tx.id);\n\n const newTransactions = trimmedTransactions.filter((tx) =>\n uniqueTransactionIds.includes(tx.id),\n );\n\n if (!newTransactions.length) {\n log('All unique transactions truncated due to limit');\n return;\n }\n\n log('Adding new transactions', newTransactions.length, newTransactions);\n\n this.hub.emit('transactions', newTransactions);\n }\n\n #sortTransactionsByTime(transactions: TransactionMeta[]) {\n transactions.sort((a, b) => (a.time < b.time ? -1 : 1));\n }\n\n #canStart(): boolean {\n return this.#isEnabled();\n }\n\n #getInterval(): number {\n return getIncomingTransactionsPollingInterval(this.#messenger);\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getGasEstimateBuffer = exports.getGasEstimateFallback = exports.getGasFeeRandomisation = exports.getAcceleratedPollingParams = exports.getBatchSizeLimit = exports.getEIP7702UpgradeContractAddress = exports.getEIP7702ContractAddresses = exports.getEIP7702SupportedChains = exports.FeatureFlag = void 0;
|
|
3
|
+
exports.getIncomingTransactionsPollingInterval = exports.getGasEstimateBuffer = exports.getGasEstimateFallback = exports.getGasFeeRandomisation = exports.getAcceleratedPollingParams = exports.getBatchSizeLimit = exports.getEIP7702UpgradeContractAddress = exports.getEIP7702ContractAddresses = exports.getEIP7702SupportedChains = exports.FeatureFlag = void 0;
|
|
4
4
|
const utils_1 = require("@metamask/utils");
|
|
5
5
|
const signature_1 = require("./signature.cjs");
|
|
6
6
|
const utils_2 = require("./utils.cjs");
|
|
@@ -10,6 +10,7 @@ const DEFAULT_ACCELERATED_POLLING_COUNT_MAX = 10;
|
|
|
10
10
|
const DEFAULT_ACCELERATED_POLLING_INTERVAL_MS = 3 * 1000;
|
|
11
11
|
const DEFAULT_GAS_ESTIMATE_FALLBACK_BLOCK_PERCENT = 35;
|
|
12
12
|
const DEFAULT_GAS_ESTIMATE_BUFFER = 1;
|
|
13
|
+
const DEFAULT_INCOMING_TRANSACTIONS_POLLING_INTERVAL_MS = 1000 * 60 * 4; // 4 Minutes
|
|
13
14
|
/**
|
|
14
15
|
* Feature flags supporting the transaction controller.
|
|
15
16
|
*/
|
|
@@ -17,6 +18,7 @@ var FeatureFlag;
|
|
|
17
18
|
(function (FeatureFlag) {
|
|
18
19
|
FeatureFlag["EIP7702"] = "confirmations_eip_7702";
|
|
19
20
|
FeatureFlag["GasBuffer"] = "confirmations_gas_buffer";
|
|
21
|
+
FeatureFlag["IncomingTransactions"] = "confirmations_incoming_transactions";
|
|
20
22
|
FeatureFlag["Transactions"] = "confirmations_transactions";
|
|
21
23
|
})(FeatureFlag || (exports.FeatureFlag = FeatureFlag = {}));
|
|
22
24
|
const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'feature-flags');
|
|
@@ -154,6 +156,19 @@ function getGasEstimateBuffer({ chainId, isCustomRPC, isUpgradeWithDataToSelf, m
|
|
|
154
156
|
DEFAULT_GAS_ESTIMATE_BUFFER);
|
|
155
157
|
}
|
|
156
158
|
exports.getGasEstimateBuffer = getGasEstimateBuffer;
|
|
159
|
+
/**
|
|
160
|
+
* Retrieves the incoming transactions polling interval.
|
|
161
|
+
* Defaults to 4 minutes if not set.
|
|
162
|
+
*
|
|
163
|
+
* @param messenger - The controller messenger instance.
|
|
164
|
+
* @returns The incoming transactions polling interval in milliseconds.
|
|
165
|
+
*/
|
|
166
|
+
function getIncomingTransactionsPollingInterval(messenger) {
|
|
167
|
+
const featureFlags = getFeatureFlags(messenger);
|
|
168
|
+
return (featureFlags?.[FeatureFlag.IncomingTransactions]?.pollingIntervalMs ??
|
|
169
|
+
DEFAULT_INCOMING_TRANSACTIONS_POLLING_INTERVAL_MS);
|
|
170
|
+
}
|
|
171
|
+
exports.getIncomingTransactionsPollingInterval = getIncomingTransactionsPollingInterval;
|
|
157
172
|
/**
|
|
158
173
|
* Retrieves the relevant feature flags from the remote feature flag controller.
|
|
159
174
|
*
|