@metamask/transaction-controller 32.0.0 → 33.0.1
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 +30 -1
- package/dist/TransactionController.js +17 -17
- package/dist/TransactionController.mjs +16 -16
- package/dist/{chunk-7MKQDZKY.js → chunk-2EU6346V.js} +3 -3
- package/dist/{chunk-Y7ENNK7L.mjs → chunk-3ZV5YEUV.mjs} +6 -5
- package/dist/chunk-3ZV5YEUV.mjs.map +1 -0
- package/dist/{chunk-AZ4WIRH3.mjs → chunk-4V4XIPCI.mjs} +5 -2
- package/dist/chunk-4V4XIPCI.mjs.map +1 -0
- package/dist/{chunk-NM6OYEPP.mjs → chunk-5ZEJT5SN.mjs} +6 -2
- package/dist/chunk-5ZEJT5SN.mjs.map +1 -0
- package/dist/{chunk-5YES3V2R.mjs → chunk-6B5BEO3R.mjs} +1 -1
- package/dist/chunk-6B5BEO3R.mjs.map +1 -0
- package/dist/{chunk-PUESYN62.js → chunk-6OLJWLKK.js} +6 -3
- package/dist/chunk-6OLJWLKK.js.map +1 -0
- package/dist/{chunk-METHOFMG.mjs → chunk-6SJYXSF3.mjs} +6 -6
- package/dist/chunk-6SJYXSF3.mjs.map +1 -0
- package/dist/{chunk-IT3SYNZ6.js → chunk-74W7X6BE.js} +1 -1
- package/dist/chunk-74W7X6BE.js.map +1 -0
- package/dist/{chunk-DLOQPH4M.js → chunk-76FONEDA.js} +4 -4
- package/dist/{chunk-EQT25RSP.js → chunk-7NMV2NPM.js} +6 -4
- package/dist/chunk-7NMV2NPM.js.map +1 -0
- package/dist/{chunk-Q6Q44V4W.js → chunk-ARZHJFVG.js} +6 -6
- package/dist/{chunk-RAOYRJ25.js → chunk-AYTU4HU5.js} +6 -6
- package/dist/chunk-AYTU4HU5.js.map +1 -0
- package/dist/{chunk-3ZRHCVVS.js → chunk-C3WC4OJ3.js} +7 -5
- package/dist/chunk-C3WC4OJ3.js.map +1 -0
- package/dist/{chunk-QZLPYOGC.mjs → chunk-EGQCE3FK.mjs} +1 -1
- package/dist/chunk-EGQCE3FK.mjs.map +1 -0
- package/dist/{chunk-CPMTUMMZ.mjs → chunk-EKJXGERC.mjs} +4 -2
- package/dist/chunk-EKJXGERC.mjs.map +1 -0
- package/dist/{chunk-AHSDUIMT.mjs → chunk-EVL6KODQ.mjs} +1 -1
- package/dist/chunk-EVL6KODQ.mjs.map +1 -0
- package/dist/{chunk-IJ5GUKRO.mjs → chunk-GNAL5HC2.mjs} +2 -2
- package/dist/{chunk-V6HVF4EN.mjs → chunk-H2KZOK3J.mjs} +3 -3
- package/dist/chunk-H2KZOK3J.mjs.map +1 -0
- package/dist/{chunk-CDF4QNJA.mjs → chunk-JXXTNVU4.mjs} +2 -2
- package/dist/{chunk-UGFBA4GV.js → chunk-OZ6UB42C.js} +5 -1
- package/dist/chunk-OZ6UB42C.js.map +1 -0
- package/dist/{chunk-J56A7UCK.mjs → chunk-Q56I5ONX.mjs} +5 -1
- package/dist/chunk-Q56I5ONX.mjs.map +1 -0
- package/dist/{chunk-UT4M4XI3.js → chunk-QH2H4W3N.js} +5 -5
- package/dist/{chunk-YXSCBWTU.js → chunk-QTKXIDGE.js} +9 -9
- package/dist/{chunk-YXSCBWTU.js.map → chunk-QTKXIDGE.js.map} +1 -1
- package/dist/{chunk-DTDTOMTB.js → chunk-RHDPOIS4.js} +6 -5
- package/dist/chunk-RHDPOIS4.js.map +1 -0
- package/dist/{chunk-VH47Q6TS.js → chunk-RXIUMVA5.js} +7 -3
- package/dist/chunk-RXIUMVA5.js.map +1 -0
- package/dist/{chunk-PBYK4OMK.js → chunk-S7Q622IS.js} +83 -71
- package/dist/chunk-S7Q622IS.js.map +1 -0
- package/dist/{chunk-NRQUBP3S.mjs → chunk-SFFTNB2X.mjs} +2 -2
- package/dist/{chunk-2TUDWNEI.mjs → chunk-UHG2LLVV.mjs} +3 -3
- package/dist/{chunk-PQCHA5KF.mjs → chunk-UKV5HIMT.mjs} +38 -26
- package/dist/chunk-UKV5HIMT.mjs.map +1 -0
- package/dist/{chunk-5KMU2IAT.js → chunk-ULD4JC3Q.js} +1 -1
- package/dist/chunk-ULD4JC3Q.js.map +1 -0
- package/dist/{chunk-G5U6ABRU.mjs → chunk-VXNPVIYL.mjs} +5 -3
- package/dist/{chunk-G5U6ABRU.mjs.map → chunk-VXNPVIYL.mjs.map} +1 -1
- package/dist/{chunk-FDUCRHYT.js → chunk-XVYXRCRL.js} +1 -1
- package/dist/chunk-XVYXRCRL.js.map +1 -0
- package/dist/errors.js +1 -1
- package/dist/errors.mjs +1 -1
- package/dist/gas-flows/DefaultGasFeeFlow.js +7 -7
- package/dist/gas-flows/DefaultGasFeeFlow.mjs +6 -6
- package/dist/gas-flows/LineaGasFeeFlow.js +8 -8
- package/dist/gas-flows/LineaGasFeeFlow.mjs +7 -7
- package/dist/gas-flows/TestGasFeeFlow.js +1 -1
- package/dist/gas-flows/TestGasFeeFlow.mjs +1 -1
- package/dist/helpers/EtherscanRemoteTransactionSource.js +4 -4
- package/dist/helpers/EtherscanRemoteTransactionSource.mjs +3 -3
- package/dist/helpers/GasFeePoller.js +4 -4
- package/dist/helpers/GasFeePoller.mjs +3 -3
- package/dist/helpers/IncomingTransactionHelper.js +2 -2
- package/dist/helpers/IncomingTransactionHelper.mjs +1 -1
- package/dist/helpers/MultichainTrackingHelper.js +5 -5
- package/dist/helpers/MultichainTrackingHelper.mjs +4 -4
- package/dist/helpers/PendingTransactionTracker.js +3 -3
- package/dist/helpers/PendingTransactionTracker.mjs +2 -2
- package/dist/index.js +17 -17
- package/dist/index.mjs +16 -16
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/TransactionController.d.ts +3 -5
- package/dist/types/TransactionController.d.ts.map +1 -1
- package/dist/types/gas-flows/DefaultGasFeeFlow.d.ts.map +1 -1
- package/dist/types/helpers/EtherscanRemoteTransactionSource.d.ts.map +1 -1
- package/dist/types/helpers/IncomingTransactionHelper.d.ts +2 -1
- package/dist/types/helpers/IncomingTransactionHelper.d.ts.map +1 -1
- package/dist/types/helpers/MultichainTrackingHelper.d.ts.map +1 -1
- package/dist/types/helpers/PendingTransactionTracker.d.ts.map +1 -1
- package/dist/types/types.d.ts +45 -9
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/utils/etherscan.d.ts.map +1 -1
- package/dist/types/utils/simulation.d.ts.map +1 -1
- package/dist/types/utils/utils.d.ts.map +1 -1
- package/dist/types.js +2 -2
- package/dist/types.mjs +1 -1
- package/dist/utils/etherscan.js +2 -2
- package/dist/utils/etherscan.mjs +1 -1
- package/dist/utils/external-transactions.js +1 -1
- package/dist/utils/external-transactions.mjs +1 -1
- package/dist/utils/gas-fees.js +6 -6
- package/dist/utils/gas-fees.mjs +5 -5
- package/dist/utils/gas-flow.js +3 -3
- package/dist/utils/gas-flow.mjs +2 -2
- package/dist/utils/simulation-api.js +1 -1
- package/dist/utils/simulation-api.mjs +1 -1
- package/dist/utils/simulation.js +3 -3
- package/dist/utils/simulation.mjs +2 -2
- package/dist/utils/swaps.js +4 -4
- package/dist/utils/swaps.mjs +3 -3
- package/dist/utils/transaction-type.js +1 -1
- package/dist/utils/transaction-type.mjs +1 -1
- package/dist/utils/utils.js +3 -3
- package/dist/utils/utils.mjs +2 -2
- package/dist/utils/validation.js +4 -4
- package/dist/utils/validation.mjs +3 -3
- package/package.json +5 -1
- package/dist/chunk-3ZRHCVVS.js.map +0 -1
- package/dist/chunk-5KMU2IAT.js.map +0 -1
- package/dist/chunk-5YES3V2R.mjs.map +0 -1
- package/dist/chunk-AHSDUIMT.mjs.map +0 -1
- package/dist/chunk-AZ4WIRH3.mjs.map +0 -1
- package/dist/chunk-CPMTUMMZ.mjs.map +0 -1
- package/dist/chunk-DTDTOMTB.js.map +0 -1
- package/dist/chunk-EQT25RSP.js.map +0 -1
- package/dist/chunk-FDUCRHYT.js.map +0 -1
- package/dist/chunk-IT3SYNZ6.js.map +0 -1
- package/dist/chunk-J56A7UCK.mjs.map +0 -1
- package/dist/chunk-METHOFMG.mjs.map +0 -1
- package/dist/chunk-NM6OYEPP.mjs.map +0 -1
- package/dist/chunk-PBYK4OMK.js.map +0 -1
- package/dist/chunk-PQCHA5KF.mjs.map +0 -1
- package/dist/chunk-PUESYN62.js.map +0 -1
- package/dist/chunk-QZLPYOGC.mjs.map +0 -1
- package/dist/chunk-RAOYRJ25.js.map +0 -1
- package/dist/chunk-UGFBA4GV.js.map +0 -1
- package/dist/chunk-V6HVF4EN.mjs.map +0 -1
- package/dist/chunk-VH47Q6TS.js.map +0 -1
- package/dist/chunk-Y7ENNK7L.mjs.map +0 -1
- /package/dist/{chunk-7MKQDZKY.js.map → chunk-2EU6346V.js.map} +0 -0
- /package/dist/{chunk-DLOQPH4M.js.map → chunk-76FONEDA.js.map} +0 -0
- /package/dist/{chunk-Q6Q44V4W.js.map → chunk-ARZHJFVG.js.map} +0 -0
- /package/dist/{chunk-IJ5GUKRO.mjs.map → chunk-GNAL5HC2.mjs.map} +0 -0
- /package/dist/{chunk-CDF4QNJA.mjs.map → chunk-JXXTNVU4.mjs.map} +0 -0
- /package/dist/{chunk-UT4M4XI3.js.map → chunk-QH2H4W3N.js.map} +0 -0
- /package/dist/{chunk-NRQUBP3S.mjs.map → chunk-SFFTNB2X.mjs.map} +0 -0
- /package/dist/{chunk-2TUDWNEI.mjs.map → chunk-UHG2LLVV.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { AccessList } from '@ethereumjs/tx';\nimport type EthQuery from '@metamask/eth-query';\nimport type { GasFeeState } from '@metamask/gas-fee-controller';\nimport type { NetworkClientId, Provider } from '@metamask/network-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Operation } from 'fast-json-patch';\n\n/**\n * Given a record, ensures that each property matches the `Json` type.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\ntype MakeJsonCompatible<T> = T extends Json\n ? T\n : {\n [K in keyof T]: T[K] extends Json ? T[K] : never;\n };\n\n/**\n * `Json` from `@metamask/utils` is defined as a recursive type alias, but\n * `Operation` is defined as an interface, and the two are not compatible with\n * each other. Therefore, this is a variant of Operation from `fast-json-patch`\n * which is guaranteed to be type-compatible with `Json`.\n */\ntype JsonCompatibleOperation = MakeJsonCompatible<Operation>;\n\n/**\n * Representation of transaction metadata.\n */\nexport type TransactionMeta = TransactionMetaBase &\n (\n | {\n status: Exclude<TransactionStatus, TransactionStatus.failed>;\n }\n | {\n status: TransactionStatus.failed;\n error: TransactionError;\n }\n );\n\n/**\n * Information about a single transaction such as status and block number.\n */\ntype TransactionMetaBase = {\n /**\n * ID of the transaction that approved the swap token transfer.\n */\n approvalTxId?: string;\n\n /**\n * Unique ID to prevent duplicate requests.\n */\n actionId?: string;\n\n /**\n * Base fee of the block as a hex value, introduced in EIP-1559.\n */\n baseFeePerGas?: Hex;\n\n /**\n * Number of the block where the transaction has been included.\n */\n blockNumber?: string;\n\n /**\n * The timestamp for when the block was collated.\n */\n blockTimestamp?: string;\n\n /**\n * Network code as per EIP-155 for this transaction.\n */\n chainId: Hex;\n\n /**\n * A string representing a name of transaction contract method.\n */\n contractMethodName?: string;\n\n /**\n * The balance of the token that is being sent.\n */\n currentTokenBalance?: string;\n\n /**\n * Unique ID for custodian transaction.\n */\n custodyId?: string;\n\n /**\n * Custodian transaction status.\n */\n custodyStatus?: string;\n\n /** The optional custom nonce override as a decimal string. */\n customNonceValue?: string;\n\n /**\n * The custom token amount is the amount set by the user.\n */\n customTokenAmount?: string;\n\n /**\n * The dapp proposed token amount.\n */\n dappProposedTokenAmount?: string;\n\n /**\n * Gas values provided by the dApp.\n */\n dappSuggestedGasFees?: DappSuggestedGasFees;\n\n /**\n * The initial gas values set when the transaction was first created.\n */\n defaultGasEstimates?: DefaultGasEstimates;\n\n /**\n * String to indicate what device the transaction was confirmed on.\n */\n deviceConfirmedOn?: WalletDevice;\n\n /**\n * The address of the token being received of swap transaction.\n */\n destinationTokenAddress?: string;\n\n /**\n * The raw amount of the destination token\n */\n destinationTokenAmount?: string;\n\n /**\n * The decimals of the token being received of swap transaction.\n */\n destinationTokenDecimals?: number;\n\n /**\n * The symbol of the token being received with swap.\n */\n destinationTokenSymbol?: string;\n\n /**\n * The estimated base fee of the transaction.\n */\n estimatedBaseFee?: string;\n\n /**\n * Which estimate level that the API suggested.\n */\n estimateSuggested?: string;\n\n /**\n * Which estimate level was used\n */\n estimateUsed?: string;\n\n /**\n * The chosen amount which will be the same as the originally proposed token\n * amount if the user does not edit the amount or will be a custom token\n * amount set by the user.\n */\n finalApprovalAmount?: string;\n\n /**\n * The number of the latest block when the transaction submit was first retried.\n */\n firstRetryBlockNumber?: string;\n\n /** Alternate EIP-1559 gas fee estimates for multiple priority levels. */\n gasFeeEstimates?: GasFeeEstimates;\n\n /** Whether the gas fee estimates have been checked at least once. */\n gasFeeEstimatesLoaded?: boolean;\n\n /**\n * A hex string of the transaction hash, used to identify the transaction on the network.\n */\n hash?: string;\n\n /**\n * A history of mutations to TransactionMeta.\n */\n history?: TransactionHistory;\n\n /**\n * Generated UUID associated with this transaction.\n */\n id: string;\n\n /**\n * Whether the transaction is a transfer.\n */\n isTransfer?: boolean;\n\n /**\n * Whether the transaction entry is generated from a user operation.\n */\n isUserOperation?: boolean;\n\n /**\n * Additional gas fees to cover the cost of persisting data on layer 1 for layer 2 networks.\n */\n layer1GasFee?: Hex;\n\n /**\n * The ID of the network client used by the transaction.\n */\n networkClientId?: NetworkClientId;\n\n /**\n * Network code as per EIP-155 for this transaction\n *\n * @deprecated Use `chainId` instead.\n */\n readonly networkID?: string;\n\n /**\n * Origin this transaction was sent from.\n */\n origin?: string;\n\n /**\n * The original dapp proposed token approval amount before edit by user.\n */\n originalApprovalAmount?: string;\n\n /**\n * The original gas estimation of the transaction.\n */\n originalGasEstimate?: string;\n\n /**\n * When we speed up a transaction, we set the type as Retry and we lose\n * information about type of transaction that is being set up, so we use\n * original type to track that information.\n */\n originalType?: TransactionType;\n\n /**\n * Account transaction balance after swap.\n */\n postTxBalance?: string;\n\n /**\n * Account transaction balance before swap.\n */\n preTxBalance?: string;\n\n /**\n * The previous gas properties before they were updated.\n */\n previousGas?: {\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gasLimit?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n };\n\n /**\n * The transaction's 'r' value as a hex string.\n */\n r?: string;\n\n /**\n * Hex representation of the underlying transaction.\n */\n rawTx?: string;\n\n /**\n * When the transaction is dropped, this is the replacement transaction hash.\n */\n replacedBy?: string;\n\n /**\n * When the transaction is dropped, this is the replacement transaction ID.\n */\n replacedById?: string;\n\n /**\n * The number of times that the transaction submit has been retried.\n */\n retryCount?: number;\n\n /**\n * The transaction's 's' value as a hex string.\n */\n s?: string;\n\n /**\n * Response from security validator.\n */\n securityAlertResponse?: SecurityAlertResponse;\n\n /**\n * Response from security provider.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n securityProviderResponse?: Record<string, any>;\n\n /**\n * An array of entries that describe the user's journey through the send flow.\n * This is purely attached to state logs for troubleshooting and support.\n */\n sendFlowHistory?: SendFlowHistoryEntry[];\n\n /**\n * Simulation data for the transaction used to predict its outcome.\n */\n simulationData?: SimulationData;\n\n /**\n * If the gas estimation fails, an object containing error and block information.\n */\n simulationFails?: {\n reason?: string;\n errorKey?: string;\n debug: {\n blockNumber?: string;\n blockGasLimit?: string;\n };\n };\n\n /**\n * The time the transaction was submitted to the network, in Unix epoch time (ms).\n */\n submittedTime?: number;\n\n /**\n * The address of the token being swapped\n */\n sourceTokenAddress?: string;\n\n /**\n * The raw amount of the source swap token\n */\n sourceTokenAmount?: string;\n\n /**\n * The decimals of the token being swapped.\n */\n sourceTokenDecimals?: number;\n\n /**\n * The symbol of the token being swapped.\n */\n sourceTokenSymbol?: string;\n\n /**\n * The address of the swap recipient.\n */\n swapAndSendRecipient?: string;\n\n /**\n * The metadata of the swap transaction.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapMetaData?: Record<string, any>;\n\n /**\n * The value of the token being swapped.\n */\n swapTokenValue?: string;\n\n /**\n * Timestamp associated with this transaction.\n */\n time: number;\n\n /**\n * Whether transaction recipient is a smart contract.\n */\n toSmartContract?: boolean;\n\n /**\n * Additional transfer information.\n */\n transferInformation?: {\n contractAddress: string;\n decimals: number;\n symbol: string;\n };\n\n /**\n * Underlying Transaction object.\n */\n txParams: TransactionParams;\n\n /**\n * Transaction receipt.\n */\n txReceipt?: TransactionReceipt;\n\n /**\n * The type of transaction such as `cancel` or `swap`.\n */\n type?: TransactionType;\n\n /**\n * The gas limit supplied by user.\n */\n userEditedGasLimit?: boolean;\n\n /**\n * Estimate level user selected.\n */\n userFeeLevel?: string;\n\n /**\n * The transaction's 'v' value as a hex string.\n */\n v?: string;\n\n /**\n * Whether the transaction is verified on the blockchain.\n */\n verifiedOnBlockchain?: boolean;\n\n /**\n * Warning information for the transaction.\n */\n warning?: {\n error: string;\n message: string;\n };\n};\n\nexport type SendFlowHistoryEntry = {\n /**\n * String to indicate user interaction information.\n */\n entry: string;\n\n /**\n * Timestamp associated with this entry.\n */\n timestamp: number;\n};\n\n/**\n * Represents the status of a transaction within the wallet.\n * Each status reflects the state of the transaction internally,\n * with some statuses corresponding to the transaction's state on the network.\n *\n * The typical transaction lifecycle follows this state machine:\n * unapproved -> approved -> signed -> submitted -> FINAL_STATE\n * where FINAL_STATE is one of: confirmed, failed, dropped, or rejected.\n */\nexport enum TransactionStatus {\n /**\n * The initial state of a transaction before user approval.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n unapproved = 'unapproved',\n\n /**\n * The transaction has been approved by the user but is not yet signed.\n * This status is usually brief but may be longer for scenarios like hardware wallet usage.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n approved = 'approved',\n\n /**\n * The transaction is signed and in the process of being submitted to the network.\n * This status is typically short-lived but can be longer for certain cases, such as smart transactions.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n signed = 'signed',\n\n /**\n * The transaction has been submitted to the network and is awaiting confirmation.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n submitted = 'submitted',\n\n /**\n * The transaction has been successfully executed and confirmed on the blockchain.\n * This is a final state.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n confirmed = 'confirmed',\n\n /**\n * The transaction encountered an error during execution on the blockchain and failed.\n * This is a final state.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n failed = 'failed',\n\n /**\n * The transaction was superseded by another transaction, resulting in its dismissal.\n * This is a final state.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n dropped = 'dropped',\n\n /**\n * The transaction was rejected by the user and not processed further.\n * This is a final state.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n rejected = 'rejected',\n\n /**\n * @deprecated This status is no longer used.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n cancelled = 'cancelled',\n}\n\n/**\n * Options for wallet device.\n */\nexport enum WalletDevice {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n MM_MOBILE = 'metamask_mobile',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n MM_EXTENSION = 'metamask_extension',\n OTHER = 'other_device',\n}\n\n/**\n * The type of the transaction.\n */\nexport enum TransactionType {\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n cancel = 'cancel',\n\n /**\n * A transaction that is interacting with a smart contract's methods that we\n * have not treated as a special case, such as approve, transfer, and\n * transferfrom.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n contractInteraction = 'contractInteraction',\n\n /**\n * A transaction that deployed a smart contract.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n deployContract = 'contractDeployment',\n\n /**\n * A transaction for Ethereum decryption.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ethDecrypt = 'eth_decrypt',\n\n /**\n * A transaction for getting an encryption public key.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ethGetEncryptionPublicKey = 'eth_getEncryptionPublicKey',\n\n /**\n * An incoming (deposit) transaction.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n incoming = 'incoming',\n\n /**\n * A transaction for personal sign.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n personalSign = 'personal_sign',\n\n /**\n * When a transaction is failed it can be retried by\n * resubmitting the same transaction with a higher gas fee. This type is also used\n * to speed up pending transactions. This is accomplished by creating a new tx with\n * the same nonce and higher gas fees.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n retry = 'retry',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n simpleSend = 'simpleSend',\n\n /**\n * A transaction that is signing typed data.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n signTypedData = 'eth_signTypedData',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n smart = 'smart',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n swap = 'swap',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps, then sending the swapped token to a recipient.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n swapAndSend = 'swapAndSend',\n\n /**\n * Similar to the approve type, a swap approval is a special case of ERC20\n * approve method that requests an allowance of the token to spend on behalf\n * of the user for the MetaMask Swaps contract. The first swap for any token\n * will have an accompanying swapApproval transaction.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n swapApproval = 'swapApproval',\n\n /**\n * A token transaction requesting an allowance of the token to spend on\n * behalf of the user.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodApprove = 'approve',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. The method is prefixed with safe because when calling\n * this method the contract checks to ensure that the receiver is an address\n * capable of handling the token being sent.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodSafeTransferFrom = 'safetransferfrom',\n\n /**\n * A token transaction where the user is sending tokens that they own to\n * another address.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodTransfer = 'transfer',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. For more information on allowances, see the approve\n * type.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodTransferFrom = 'transferfrom',\n\n /**\n * A token transaction requesting an allowance of all of a user's tokens to\n * spend on behalf of the user.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodSetApprovalForAll = 'setapprovalforall',\n\n /**\n * Increase the allowance by a given increment\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodIncreaseAllowance = 'increaseAllowance',\n}\n\n/**\n * Standard data concerning a transaction to be processed by the blockchain.\n */\nexport type TransactionParams = {\n /**\n * A list of addresses and storage keys that the transaction plans to access.\n */\n accessList?: AccessList;\n\n /**\n * Network ID as per EIP-155.\n */\n chainId?: Hex;\n\n /**\n * Data to pass with this transaction.\n */\n data?: string;\n\n /**\n * Error message for gas estimation failure.\n */\n estimateGasError?: string;\n\n /**\n * Estimated base fee for this transaction.\n */\n estimatedBaseFee?: string;\n\n /**\n * Which estimate level that the API suggested.\n */\n estimateSuggested?: string;\n\n /**\n * Which estimate level was used\n */\n estimateUsed?: string;\n\n /**\n * Address to send this transaction from.\n */\n from: string;\n\n /**\n * same as gasLimit?\n */\n gas?: string;\n\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gasLimit?: string;\n\n /**\n * Price per gas for legacy txs\n */\n gasPrice?: string;\n\n /**\n * Gas used in the transaction.\n */\n gasUsed?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority\n * fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n\n /**\n * Unique number to prevent replay attacks.\n */\n nonce?: string;\n\n /**\n * Address to send this transaction to.\n */\n to?: string;\n\n /**\n * Value associated with this transaction.\n */\n value?: string;\n\n /**\n * Type of transaction.\n * 0x0 indicates a legacy transaction.\n */\n type?: string;\n};\n\n/**\n * Standard data concerning a transaction processed by the blockchain.\n */\nexport type TransactionReceipt = {\n /**\n * The block hash of the block that this transaction was included in.\n */\n blockHash?: string;\n\n /**\n * The block number of the block that this transaction was included in.\n */\n blockNumber?: string;\n\n /**\n * Effective gas price the transaction was charged at.\n */\n effectiveGasPrice?: string;\n\n /**\n * Gas used in the transaction.\n */\n gasUsed?: string;\n\n /**\n * Total used gas in hex.\n */\n l1Fee?: string;\n\n /**\n * All the logs emitted by this transaction.\n */\n logs?: Log[];\n\n /**\n * The status of the transaction.\n */\n status?: string;\n\n /**\n * The hexadecimal index of this transaction in the list of transactions included in the block this transaction was mined in.\n */\n transactionIndex?: string;\n};\n\n/**\n * Represents an event that has been included in a transaction using the EVM `LOG` opcode.\n */\nexport type Log = {\n /**\n * Address of the contract that generated log.\n */\n address?: string;\n /**\n * List of topics for log.\n */\n topics?: string;\n};\n\n/**\n * The configuration required to fetch transaction data from a RemoteTransactionSource.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface RemoteTransactionSourceRequest {\n /**\n * The address of the account to fetch transactions for.\n */\n address: string;\n\n /**\n * The chainId of the current network.\n */\n currentChainId: Hex;\n\n /**\n * Block number to start fetching transactions from.\n */\n fromBlock?: number;\n\n /**\n * Maximum number of transactions to retrieve.\n */\n limit?: number;\n}\n\n/**\n * An object capable of fetching transaction data from a remote source.\n * Used by the IncomingTransactionHelper to retrieve remote transaction data.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface RemoteTransactionSource {\n /**\n * @param chainId - The chainId of the current network.\n * @returns Whether the remote transaction source supports the specified network.\n */\n isSupportedNetwork: (chainId: Hex) => boolean;\n\n /**\n * @returns An array of additional keys to use when caching the last fetched block number.\n */\n getLastBlockVariations?: () => string[];\n\n /**\n * @param request - A request object containing data such as the address and chain ID.\n * @returns An array of transaction metadata for the retrieved transactions.\n */\n fetchTransactions: (\n request: RemoteTransactionSourceRequest,\n ) => Promise<TransactionMeta[]>;\n}\n\n/**\n * Gas values initially suggested by the dApp.\n */\nexport type DappSuggestedGasFees = {\n gas?: string;\n gasPrice?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Gas values saved by the user for a specific chain.\n */\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SavedGasFees {\n maxBaseFee: string;\n priorityFee: string;\n}\n\n/**\n * A transaction history operation that includes a note and timestamp.\n */\ntype ExtendedHistoryOperation = JsonCompatibleOperation & {\n note?: string;\n timestamp?: number;\n};\n\n/**\n * A transaction history entry that includes the ExtendedHistoryOperation as the first element.\n */\nexport type TransactionHistoryEntry = [\n ExtendedHistoryOperation,\n ...JsonCompatibleOperation[],\n];\n\n/**\n * A transaction history that includes the transaction meta as the first element.\n * And the rest of the elements are the operation arrays that were applied to the transaction meta.\n */\nexport type TransactionHistory = [\n TransactionMeta,\n ...TransactionHistoryEntry[],\n];\n\n/**\n * Result of inferring the transaction type.\n */\nexport type InferTransactionTypeResult = {\n /**\n * The contract code, in hex format if it exists. '0x0' or\n * '0x' are also indicators of non-existent contract code.\n */\n getCodeResponse?: string | null;\n\n /**\n * The type of transaction\n */\n type: TransactionType;\n};\n\n/**\n * A function for verifying a transaction, whether it is malicious or not.\n */\nexport type SecurityProviderRequest = (\n requestData: TransactionMeta,\n messageType: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\n/**\n * Specifies the shape of the base transaction parameters.\n * Added in EIP-2718.\n */\nexport enum TransactionEnvelopeType {\n /**\n * A legacy transaction, the very first type.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n legacy = '0x0',\n\n /**\n * EIP-2930 defined the access list transaction type that allowed for\n * specifying the state that a transaction would act upon in advance and\n * theoretically save on gas fees.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n accessList = '0x1',\n\n /**\n * The type introduced comes from EIP-1559, Fee Market describes the addition\n * of a baseFee to blocks that will be burned instead of distributed to\n * miners. Transactions of this type have both a maxFeePerGas (maximum total\n * amount in gwei per gas to spend on the transaction) which is inclusive of\n * the maxPriorityFeePerGas (maximum amount of gwei per gas from the\n * transaction fee to distribute to miner).\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n feeMarket = '0x2',\n}\n\n/**\n * The source of the gas fee parameters on a transaction.\n */\nexport enum UserFeeLevel {\n CUSTOM = 'custom',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n DAPP_SUGGESTED = 'dappSuggested',\n MEDIUM = 'medium',\n}\n\n/**\n * Initial gas values set when the transaction was first created.\n */\nexport type DefaultGasEstimates = {\n /**\n * Source of the gas fee values, such as `dappSuggested` or `medium`.\n */\n estimateType?: string;\n\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gas?: string;\n\n /**\n * Price per gas for legacy transactions.\n */\n gasPrice?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Data concerning an error while processing a transaction.\n */\nexport type TransactionError = {\n /**\n * A descriptive error name.\n */\n name: string;\n\n /**\n * A descriptive error message providing details about the encountered error.\n */\n message: string;\n\n /**\n * The stack trace associated with the error, if available.\n */\n stack?: string;\n\n /**\n * An optional error code associated with the error.\n */\n code?: string;\n\n /**\n * The rpc property holds additional information related to the error.\n */\n // We are intentionally using `any` here instead of `Json` because it causes\n // `WritableDraft<TransactionMeta>` from Immer to cause TypeScript to error\n // with \"Type instantiation is excessively deep and possibly infinite\". See:\n // <https://github.com/immerjs/immer/issues/839>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc?: any;\n};\n\n/**\n * Type for security alert response from transaction validator.\n */\nexport type SecurityAlertResponse = {\n reason: string;\n features?: string[];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n result_type: string;\n providerRequestsCount?: Record<string, number>;\n};\n\n/** Alternate priority levels for which values are provided in gas fee estimates. */\nexport enum GasFeeEstimateLevel {\n Low = 'low',\n Medium = 'medium',\n High = 'high',\n}\n\n/** Type of gas fee estimate generated by a GasFeeFlow. */\nexport enum GasFeeEstimateType {\n FeeMarket = 'fee-market',\n Legacy = 'legacy',\n GasPrice = 'eth_gasPrice',\n}\n\n/** Gas fee estimates for a specific priority level. */\nexport type FeeMarketGasFeeEstimateForLevel = {\n /** Maximum amount to pay per gas. */\n maxFeePerGas: Hex;\n\n /** Maximum amount per gas to give to the validator as an incentive. */\n maxPriorityFeePerGas: Hex;\n};\n\n/** Gas fee estimates for a EIP-1559 transaction. */\nexport type FeeMarketGasFeeEstimates = {\n type: GasFeeEstimateType.FeeMarket;\n [GasFeeEstimateLevel.Low]: FeeMarketGasFeeEstimateForLevel;\n [GasFeeEstimateLevel.Medium]: FeeMarketGasFeeEstimateForLevel;\n [GasFeeEstimateLevel.High]: FeeMarketGasFeeEstimateForLevel;\n};\n\n/** Gas fee estimates for a legacy transaction. */\nexport type LegacyGasFeeEstimates = {\n type: GasFeeEstimateType.Legacy;\n [GasFeeEstimateLevel.Low]: Hex;\n [GasFeeEstimateLevel.Medium]: Hex;\n [GasFeeEstimateLevel.High]: Hex;\n};\n\n/** Gas fee estimates for a transaction retrieved with the eth_gasPrice method. */\nexport type GasPriceGasFeeEstimates = {\n type: GasFeeEstimateType.GasPrice;\n gasPrice: Hex;\n};\n\n/** Gas fee estimates for a transaction. */\nexport type GasFeeEstimates =\n | FeeMarketGasFeeEstimates\n | LegacyGasFeeEstimates\n | GasPriceGasFeeEstimates;\n\n/** Request to a gas fee flow to obtain gas fee estimates. */\nexport type GasFeeFlowRequest = {\n /** An EthQuery instance to enable queries to the associated RPC provider. */\n ethQuery: EthQuery;\n\n /** Gas fee controller data matching the chain ID of the transaction. */\n gasFeeControllerData: GasFeeState;\n\n /** The metadata of the transaction to obtain estimates for. */\n transactionMeta: TransactionMeta;\n};\n\n/** Response from a gas fee flow containing gas fee estimates. */\nexport type GasFeeFlowResponse = {\n /** The gas fee estimates for the transaction. */\n estimates: GasFeeEstimates;\n};\n\n/** A method of obtaining gas fee estimates for a specific transaction. */\nexport type GasFeeFlow = {\n /**\n * Determine if the gas fee flow supports the specified transaction.\n * @param transactionMeta - The transaction metadata.\n * @returns Whether the gas fee flow supports the transaction.\n */\n matchesTransaction(transactionMeta: TransactionMeta): boolean;\n\n /**\n * Get gas fee estimates for a specific transaction.\n * @param request - The gas fee flow request.\n * @returns The gas fee flow response containing the gas fee estimates.\n */\n getGasFees: (request: GasFeeFlowRequest) => Promise<GasFeeFlowResponse>;\n};\n\n/** Request to a layer 1 gas fee flow to obtain layer 1 fee estimate. */\nexport type Layer1GasFeeFlowRequest = {\n /** RPC Provider instance. */\n provider: Provider;\n\n /** The metadata of the transaction to obtain estimates for. */\n transactionMeta: TransactionMeta;\n};\n\n/** Response from a layer 1 gas fee flow containing layer 1 fee estimate. */\nexport type Layer1GasFeeFlowResponse = {\n /** The gas fee estimates for the transaction. */\n layer1Fee: Hex;\n};\n\n/** A method of obtaining layer 1 gas fee estimates for a specific transaction. */\nexport type Layer1GasFeeFlow = {\n /**\n * Determine if the gas fee flow supports the specified transaction.\n * @param transactionMeta - The transaction metadata.\n * @returns Whether the layer1 gas fee flow supports the transaction.\n */\n matchesTransaction(transactionMeta: TransactionMeta): boolean;\n\n /**\n * Get layer 1 gas fee estimates for a specific transaction.\n * @param request - The gas fee flow request.\n * @returns The gas fee flow response containing the layer 1 gas fee estimate.\n */\n getLayer1Fee: (\n request: Layer1GasFeeFlowRequest,\n ) => Promise<Layer1GasFeeFlowResponse>;\n};\n\n/** Simulation data concerning an update to a native or token balance. */\nexport type SimulationBalanceChange = {\n /** The balance before the transaction. */\n previousBalance: Hex;\n\n /** The balance after the transaction. */\n newBalance: Hex;\n\n /** The difference in balance. */\n difference: Hex;\n\n /** Whether the balance is increasing or decreasing. */\n isDecrease: boolean;\n};\n\n/** Token standards supported by simulation. */\nexport enum SimulationTokenStandard {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n erc20 = 'erc20',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n erc721 = 'erc721',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n erc1155 = 'erc1155',\n}\n\n/** Simulation data concerning an updated token. */\nexport type SimulationToken = {\n /** The token's contract address. */\n address: Hex;\n\n /** The standard of the token. */\n standard: SimulationTokenStandard;\n\n /** The ID of the token if supported by the standard. */\n id?: Hex;\n};\n\n/** Simulation data concerning a change to the a token balance. */\nexport type SimulationTokenBalanceChange = SimulationToken &\n SimulationBalanceChange;\n\nexport enum SimulationErrorCode {\n ChainNotSupported = 'chain-not-supported',\n Disabled = 'disabled',\n InvalidResponse = 'invalid-response',\n Reverted = 'reverted',\n}\n\n/** Error data for a failed simulation. */\nexport type SimulationError = {\n /** Error code to identify the error type. */\n code?: string | number;\n\n /** Error message to describe the error. */\n message?: string;\n};\n\n/** Simulation data for a transaction. */\nexport type SimulationData = {\n /** Error data if the simulation failed or the transaction reverted. */\n error?: SimulationError;\n\n /** Data concerning a change to the user's native balance. */\n nativeBalanceChange?: SimulationBalan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AA,gBAAa;AAYb,EAAAA,yBAAA,eAAY;AA3BF,SAAAA;AAAA,GAAA;AAiCL,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,YAAS;AAGT,EAAAA,cAAA,oBAAiB;AACjB,EAAAA,cAAA,YAAS;AALC,SAAAA;AAAA,GAAA;AAsFL,IAAK,sBAAL,kBAAKC,yBAAL;AACL,EAAAA,qBAAA,SAAM;AACN,EAAAA,qBAAA,YAAS;AACT,EAAAA,qBAAA,UAAO;AAHG,SAAAA;AAAA,GAAA;AAOL,IAAK,qBAAL,kBAAKC,wBAAL;AACL,EAAAA,oBAAA,eAAY;AACZ,EAAAA,oBAAA,YAAS;AACT,EAAAA,oBAAA,cAAW;AAHD,SAAAA;AAAA,GAAA;AAgIL,IAAK,0BAAL,kBAAKC,6BAAL;AAGL,EAAAA,yBAAA,WAAQ;AAGR,EAAAA,yBAAA,YAAS;AAGT,EAAAA,yBAAA,aAAU;AATA,SAAAA;AAAA,GAAA;AA4BL,IAAK,sBAAL,kBAAKC,yBAAL;AACL,EAAAA,qBAAA,uBAAoB;AACpB,EAAAA,qBAAA,cAAW;AACX,EAAAA,qBAAA,qBAAkB;AAClB,EAAAA,qBAAA,cAAW;AAJD,SAAAA;AAAA,GAAA;","names":["TransactionStatus","WalletDevice","TransactionType","TransactionEnvelopeType","UserFeeLevel","GasFeeEstimateLevel","GasFeeEstimateType","SimulationTokenStandard","SimulationErrorCode"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/simulation.ts"],"names":["SupportedToken"],"mappings":";;;;;;;;;;;;;;;;;AACA,SAAS,iBAAiB;AAC1B,SAAS,SAAS,aAAa;AAC/B,SAAS,UAAU,WAAW,kBAAkB;AAChD,SAAS,0BAAoC;AA4BtC,IAAK,iBAAL,kBAAKA,oBAAL;AACL,EAAAA,gBAAA,WAAQ;AACR,EAAAA,gBAAA,YAAS;AACT,EAAAA,gBAAA,aAAU;AAGV,EAAAA,g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, Result } from '@ethersproject/abi';\nimport { Interface } from '@ethersproject/abi';\nimport { hexToBN, toHex } from '@metamask/controller-utils';\nimport { abiERC20, abiERC721, abiERC1155 } from '@metamask/metamask-eth-abis';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport {\n ABI_SIMULATION_ERC20_WRAPPED,\n ABI_SIMULATION_ERC721_LEGACY,\n} from '../constants';\nimport {\n SimulationError,\n SimulationInvalidResponseError,\n SimulationRevertedError,\n} from '../errors';\nimport { projectLogger } from '../logger';\nimport type {\n SimulationBalanceChange,\n SimulationData,\n SimulationTokenBalanceChange,\n SimulationToken,\n} from '../types';\nimport { SimulationTokenStandard } from '../types';\nimport { simulateTransactions } from './simulation-api';\nimport type {\n SimulationResponseLog,\n SimulationRequestTransaction,\n SimulationResponse,\n SimulationResponseCallTrace,\n SimulationResponseTransaction,\n} from './simulation-api';\n\nexport enum SupportedToken {\n ERC20 = 'erc20',\n ERC721 = 'erc721',\n ERC1155 = 'erc1155',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ERC20_WRAPPED = 'erc20Wrapped',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ERC721_LEGACY = 'erc721Legacy',\n}\n\ntype ABI = Fragment[];\n\nexport type GetSimulationDataRequest = {\n chainId: Hex;\n from: Hex;\n to?: Hex;\n value?: Hex;\n data?: Hex;\n};\n\ntype ParsedEvent = {\n contractAddress: Hex;\n tokenStandard: SimulationTokenStandard;\n name: string;\n args: Record<string, Hex | Hex[]>;\n abi: ABI;\n};\n\nconst log = createModuleLogger(projectLogger, 'simulation');\n\nconst SUPPORTED_EVENTS = [\n 'Transfer',\n 'TransferSingle',\n 'TransferBatch',\n 'Deposit',\n 'Withdrawal',\n];\n\nconst SUPPORTED_TOKEN_ABIS = {\n [SupportedToken.ERC20]: {\n abi: abiERC20,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721]: {\n abi: abiERC721,\n standard: SimulationTokenStandard.erc721,\n },\n [SupportedToken.ERC1155]: {\n abi: abiERC1155,\n standard: SimulationTokenStandard.erc1155,\n },\n [SupportedToken.ERC20_WRAPPED]: {\n abi: ABI_SIMULATION_ERC20_WRAPPED,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721_LEGACY]: {\n abi: ABI_SIMULATION_ERC721_LEGACY,\n standard: SimulationTokenStandard.erc721,\n },\n};\n\nconst REVERTED_ERRORS = ['execution reverted', 'insufficient funds for gas'];\n\ntype BalanceTransactionMap = Map<SimulationToken, SimulationRequestTransaction>;\n\n/**\n * Generate simulation data for a transaction.\n * @param request - The transaction to simulate.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.from - The sender of the transaction.\n * @param request.to - The recipient of the transaction.\n * @param request.value - The value of the transaction.\n * @param request.data - The data of the transaction.\n * @returns The simulation data.\n */\nexport async function getSimulationData(\n request: GetSimulationDataRequest,\n): Promise<SimulationData> {\n const { chainId, from, to, value, data } = request;\n\n log('Getting simulation data', request);\n\n try {\n const response = await simulateTransactions(chainId, {\n transactions: [\n {\n data,\n from,\n maxFeePerGas: '0x0',\n maxPriorityFeePerGas: '0x0',\n to,\n value,\n },\n ],\n withCallTrace: true,\n withLogs: true,\n });\n\n const transactionError = response.transactions?.[0]?.error;\n\n if (transactionError) {\n throw new SimulationError(transactionError);\n }\n\n const nativeBalanceChange = getNativeBalanceChange(request.from, response);\n const events = getEvents(response);\n\n log('Parsed events', events);\n\n const tokenBalanceChanges = await getTokenBalanceChanges(request, events);\n\n return {\n nativeBalanceChange,\n tokenBalanceChanges,\n };\n } catch (error) {\n log('Failed to get simulation data', error, request);\n\n let simulationError = error as SimulationError;\n\n if (\n REVERTED_ERRORS.some((revertErrorMessage) =>\n simulationError.message?.includes(revertErrorMessage),\n )\n ) {\n simulationError = new SimulationRevertedError();\n }\n\n const { code, message } = simulationError;\n\n return {\n tokenBalanceChanges: [],\n error: {\n code,\n message,\n },\n };\n }\n}\n\n/**\n * Extract the native balance change from a simulation response.\n * @param userAddress - The user's account address.\n * @param response - The simulation response.\n * @returns The native balance change or undefined if unchanged.\n */\nfunction getNativeBalanceChange(\n userAddress: Hex,\n response: SimulationResponse,\n): SimulationBalanceChange | undefined {\n const transactionResponse = response.transactions[0];\n\n /* istanbul ignore next */\n if (!transactionResponse) {\n return undefined;\n }\n\n const { stateDiff } = transactionResponse;\n const previousBalance = stateDiff?.pre?.[userAddress]?.balance;\n const newBalance = stateDiff?.post?.[userAddress]?.balance;\n\n if (!previousBalance || !newBalance) {\n return undefined;\n }\n\n return getSimulationBalanceChange(previousBalance, newBalance);\n}\n\n/**\n * Extract events from a simulation response.\n * @param response - The simulation response.\n * @returns The parsed events.\n */\nexport function getEvents(response: SimulationResponse): ParsedEvent[] {\n /* istanbul ignore next */\n const logs = extractLogs(\n response.transactions[0]?.callTrace ?? ({} as SimulationResponseCallTrace),\n );\n\n log('Extracted logs', logs);\n\n const interfaces = getContractInterfaces();\n\n return logs\n .map((currentLog) => {\n const event = parseLog(currentLog, interfaces);\n\n if (!event) {\n log('Failed to parse log', currentLog);\n return undefined;\n }\n\n /* istanbul ignore next */\n const inputs = event.abi.find((e) => e.name === event.name)?.inputs;\n\n /* istanbul ignore if */\n if (!inputs) {\n log('Failed to find inputs for event', event);\n return undefined;\n }\n\n const args = parseEventArgs(event.args, inputs);\n\n return {\n contractAddress: currentLog.address,\n tokenStandard: event.standard,\n name: event.name,\n args,\n abi: event.abi,\n };\n })\n .filter((e) => e !== undefined) as ParsedEvent[];\n}\n\n/**\n * Parse event arguments using ABI input definitions.\n * @param args - The raw event arguments.\n * @param abiInputs - The ABI input definitions.\n * @returns The parsed event arguments.\n */\nfunction parseEventArgs(\n args: Result,\n abiInputs: { name: string }[],\n): Record<string, Hex | Hex[]> {\n return args.reduce((result, arg, index) => {\n const name = abiInputs[index].name.replace('_', '');\n const value = parseEventArgValue(arg);\n\n result[name] = value;\n\n return result;\n }, {});\n}\n\n/**\n * Parse an event argument value.\n * @param value - The event argument value.\n * @returns The parsed event argument value.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction parseEventArgValue(value: any): Hex | Hex[] {\n if (Array.isArray(value)) {\n return value.map(parseEventArgValue) as Hex[];\n }\n\n return (value.toHexString?.() ?? value).toLowerCase();\n}\n\n/**\n * Generate token balance changes from parsed events.\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @returns An array of token balance changes.\n */\nasync function getTokenBalanceChanges(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n): Promise<SimulationTokenBalanceChange[]> {\n const balanceTxs = getTokenBalanceTransactions(request, events);\n\n log('Generated balance transactions', [...balanceTxs.after.values()]);\n\n const transactions = [\n ...balanceTxs.before.values(),\n request,\n ...balanceTxs.after.values(),\n ];\n\n if (transactions.length === 1) {\n return [];\n }\n\n const response = await simulateTransactions(request.chainId as Hex, {\n transactions,\n });\n\n log('Balance simulation response', response);\n\n if (response.transactions.length !== transactions.length) {\n throw new SimulationInvalidResponseError();\n }\n\n let prevBalanceTxIndex = 0;\n return [...balanceTxs.after.keys()]\n .map((token, index) => {\n const previousBalanceCheckSkipped = !balanceTxs.before.get(token);\n const previousBalance = previousBalanceCheckSkipped\n ? '0x0'\n : getValueFromBalanceTransaction(\n request.from,\n token,\n // eslint-disable-next-line no-plusplus\n response.transactions[prevBalanceTxIndex++],\n );\n\n const newBalance = getValueFromBalanceTransaction(\n request.from,\n token,\n response.transactions[index + balanceTxs.before.size + 1],\n );\n\n const balanceChange = getSimulationBalanceChange(\n previousBalance,\n newBalance,\n );\n\n if (!balanceChange) {\n return undefined;\n }\n\n return {\n ...token,\n ...balanceChange,\n };\n })\n .filter((change) => change !== undefined) as SimulationTokenBalanceChange[];\n}\n\n/**\n * Generate transactions to check token balances.\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @returns A map of token balance transactions keyed by token.\n */\nfunction getTokenBalanceTransactions(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n): {\n before: BalanceTransactionMap;\n after: BalanceTransactionMap;\n} {\n const tokenKeys = new Set();\n const before = new Map();\n const after = new Map();\n\n const userEvents = events.filter(\n (event) =>\n SUPPORTED_EVENTS.includes(event.name) &&\n [event.args.from, event.args.to].includes(request.from),\n );\n\n log('Filtered user events', userEvents);\n\n for (const event of userEvents) {\n const tokenIds = getEventTokenIds(event);\n\n log('Extracted token ids', tokenIds);\n\n for (const tokenId of tokenIds) {\n const simulationToken: SimulationToken = {\n address: event.contractAddress,\n standard: event.tokenStandard,\n id: tokenId,\n };\n\n const tokenKey = JSON.stringify(simulationToken);\n\n if (tokenKeys.has(tokenKey)) {\n log(\n 'Ignoring additional event with same contract and token ID',\n simulationToken,\n );\n continue;\n }\n\n tokenKeys.add(tokenKey);\n\n const data = getBalanceTransactionData(\n event.tokenStandard,\n request.from,\n tokenId,\n );\n\n const transaction: SimulationRequestTransaction = {\n from: request.from,\n to: event.contractAddress,\n data,\n };\n\n if (skipPriorBalanceCheck(event)) {\n after.set(simulationToken, transaction);\n } else {\n before.set(simulationToken, transaction);\n after.set(simulationToken, transaction);\n }\n }\n }\n\n return { before, after };\n}\n\n/**\n * Check if an event needs to check the previous balance.\n * @param event - The parsed event.\n * @returns True if the prior balance check should be skipped.\n */\nfunction skipPriorBalanceCheck(event: ParsedEvent): boolean {\n // In the case of an NFT mint, we cannot check the NFT owner before the mint\n // as the balance check transaction would revert.\n return (\n event.name === 'Transfer' &&\n event.tokenStandard === SimulationTokenStandard.erc721 &&\n parseInt(event.args.from as string, 16) === 0\n );\n}\n\n/**\n * Extract token IDs from a parsed event.\n * @param event - The parsed event.\n * @returns An array of token IDs.\n */\nfunction getEventTokenIds(event: ParsedEvent): (Hex | undefined)[] {\n if (event.tokenStandard === SimulationTokenStandard.erc721) {\n return [event.args.tokenId as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferSingle'\n ) {\n return [event.args.id as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferBatch'\n ) {\n return event.args.ids as Hex[];\n }\n\n // ERC-20 does not have a token ID so default to undefined.\n return [undefined];\n}\n\n/**\n * Extract the value from a balance transaction response.\n * @param from - The address to check the balance of.\n * @param token - The token to check the balance of.\n * @param response - The balance transaction response.\n * @returns The value of the balance transaction.\n */\nfunction getValueFromBalanceTransaction(\n from: Hex,\n token: SimulationToken,\n response: SimulationResponseTransaction,\n): Hex {\n const normalizedReturn = normalizeReturnValue(response.return);\n\n if (token.standard === SimulationTokenStandard.erc721) {\n return normalizedReturn === from ? '0x1' : '0x0';\n }\n\n return normalizedReturn;\n}\n\n/**\n * Generate the balance transaction data for a token.\n * @param tokenStandard - The token standard.\n * @param from - The address to check the balance of.\n * @param tokenId - The token ID to check the balance of.\n * @returns The balance transaction data.\n */\nfunction getBalanceTransactionData(\n tokenStandard: SimulationTokenStandard,\n from: Hex,\n tokenId?: Hex,\n): Hex {\n switch (tokenStandard) {\n case SimulationTokenStandard.erc721:\n return new Interface(abiERC721).encodeFunctionData('ownerOf', [\n tokenId,\n ]) as Hex;\n\n case SimulationTokenStandard.erc1155:\n return new Interface(abiERC1155).encodeFunctionData('balanceOf', [\n from,\n tokenId,\n ]) as Hex;\n\n default:\n return new Interface(abiERC20).encodeFunctionData('balanceOf', [\n from,\n ]) as Hex;\n }\n}\n\n/**\n * Parse a raw event log using known ABIs.\n * @param eventLog - The raw event log.\n * @param interfaces - The contract interfaces.\n * @returns The parsed event log or undefined if it could not be parsed.\n */\nfunction parseLog(\n eventLog: SimulationResponseLog,\n interfaces: Map<SupportedToken, Interface>,\n):\n | (LogDescription & { abi: ABI; standard: SimulationTokenStandard })\n | undefined {\n const supportedTokens = Object.values(SupportedToken);\n\n for (const token of supportedTokens) {\n try {\n const contractInterface = interfaces.get(token) as Interface;\n const { abi, standard } = SUPPORTED_TOKEN_ABIS[token];\n\n return {\n ...contractInterface.parseLog(eventLog),\n abi,\n standard,\n };\n } catch (e) {\n continue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extract all logs from a call trace tree.\n * @param call - The root call trace.\n * @returns An array of logs.\n */\nfunction extractLogs(\n call: SimulationResponseCallTrace,\n): SimulationResponseLog[] {\n /* istanbul ignore next */\n const logs = call.logs ?? [];\n\n /* istanbul ignore next */\n const nestedCalls = call.calls ?? [];\n\n return [\n ...logs,\n ...nestedCalls.map((nestedCall) => extractLogs(nestedCall)).flat(),\n ];\n}\n\n/**\n * Generate balance change data from previous and new balances.\n * @param previousBalance - The previous balance.\n * @param newBalance - The new balance.\n * @returns The balance change data or undefined if unchanged.\n */\nfunction getSimulationBalanceChange(\n previousBalance: Hex,\n newBalance: Hex,\n): SimulationBalanceChange | undefined {\n const differenceBN = hexToBN(newBalance).sub(hexToBN(previousBalance));\n const isDecrease = differenceBN.isNeg();\n const difference = toHex(differenceBN.abs());\n\n if (differenceBN.isZero()) {\n log('Balance change is zero');\n return undefined;\n }\n\n return {\n previousBalance,\n newBalance,\n difference,\n isDecrease,\n };\n}\n\n/**\n * Normalize a return value.\n * @param value - The return value to normalize.\n * @returns The normalized return value.\n */\nfunction normalizeReturnValue(value: Hex): Hex {\n return toHex(hexToBN(value));\n}\n\n/**\n * Get the contract interfaces for all supported tokens.\n * @returns A map of supported tokens to their contract interfaces.\n */\nfunction getContractInterfaces(): Map<SupportedToken, Interface> {\n const supportedTokens = Object.values(SupportedToken);\n\n return new Map(\n supportedTokens.map((tokenType) => {\n const { abi } = SUPPORTED_TOKEN_ABIS[tokenType];\n const contractInterface = new Interface(abi);\n return [tokenType, contractInterface];\n }),\n );\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkAYTU4HU5js = require('./chunk-AYTU4HU5.js');
|
|
4
4
|
|
|
5
5
|
// src/utils/gas-flow.ts
|
|
6
6
|
var _controllerutils = require('@metamask/controller-utils');
|
|
@@ -15,7 +15,7 @@ function mergeGasFeeEstimates({
|
|
|
15
15
|
}) {
|
|
16
16
|
const transactionEstimateType = transactionGasFeeEstimates.type;
|
|
17
17
|
if (transactionEstimateType === "fee-market" /* FeeMarket */) {
|
|
18
|
-
return Object.values(
|
|
18
|
+
return Object.values(_chunkAYTU4HU5js.GasFeeEstimateLevel).reduce(
|
|
19
19
|
(result, level) => ({
|
|
20
20
|
...result,
|
|
21
21
|
[level]: mergeFeeMarketEstimate(
|
|
@@ -27,7 +27,7 @@ function mergeGasFeeEstimates({
|
|
|
27
27
|
);
|
|
28
28
|
}
|
|
29
29
|
if (transactionEstimateType === "legacy" /* Legacy */) {
|
|
30
|
-
return Object.values(
|
|
30
|
+
return Object.values(_chunkAYTU4HU5js.GasFeeEstimateLevel).reduce(
|
|
31
31
|
(result, level) => ({
|
|
32
32
|
...result,
|
|
33
33
|
[level]: getLegacyEstimate(transactionGasFeeEstimates, level)
|
|
@@ -64,4 +64,4 @@ function getGasPriceEstimate(transactionGasFeeEstimate) {
|
|
|
64
64
|
|
|
65
65
|
|
|
66
66
|
exports.getGasFeeFlow = getGasFeeFlow; exports.mergeGasFeeEstimates = mergeGasFeeEstimates;
|
|
67
|
-
//# sourceMappingURL=chunk-
|
|
67
|
+
//# sourceMappingURL=chunk-76FONEDA.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkXVYXRCRLjs = require('./chunk-XVYXRCRL.js');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
var _chunkUGN7PBONjs = require('./chunk-UGN7PBON.js');
|
|
@@ -27,6 +27,8 @@ var EtherscanRemoteTransactionSource = class {
|
|
|
27
27
|
includeTokenTransfers
|
|
28
28
|
} = {}) {
|
|
29
29
|
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _releaseLockAfterInterval);
|
|
30
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
31
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
30
32
|
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getResponseTransactions);
|
|
31
33
|
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _normalizeTransaction);
|
|
32
34
|
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _normalizeTokenTransaction);
|
|
@@ -36,7 +38,7 @@ var EtherscanRemoteTransactionSource = class {
|
|
|
36
38
|
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _mutex, new (0, _asyncmutex.Mutex)());
|
|
37
39
|
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _fetchNormalTransactions, async (request, etherscanRequest) => {
|
|
38
40
|
const { currentChainId } = request;
|
|
39
|
-
const etherscanTransactions = await
|
|
41
|
+
const etherscanTransactions = await _chunkXVYXRCRLjs.fetchEtherscanTransactions.call(void 0,
|
|
40
42
|
etherscanRequest
|
|
41
43
|
);
|
|
42
44
|
return _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getResponseTransactions, getResponseTransactions_fn).call(this, etherscanTransactions).map(
|
|
@@ -45,7 +47,7 @@ var EtherscanRemoteTransactionSource = class {
|
|
|
45
47
|
});
|
|
46
48
|
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _fetchTokenTransactions, async (request, etherscanRequest) => {
|
|
47
49
|
const { currentChainId } = request;
|
|
48
|
-
const etherscanTransactions = await
|
|
50
|
+
const etherscanTransactions = await _chunkXVYXRCRLjs.fetchEtherscanTokenTransactions.call(void 0,
|
|
49
51
|
etherscanRequest
|
|
50
52
|
);
|
|
51
53
|
return _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getResponseTransactions, getResponseTransactions_fn).call(this, etherscanTransactions).map(
|
|
@@ -167,4 +169,4 @@ normalizeTransactionBase_fn = function(txMeta, currentChainId) {
|
|
|
167
169
|
|
|
168
170
|
|
|
169
171
|
exports.EtherscanRemoteTransactionSource = EtherscanRemoteTransactionSource;
|
|
170
|
-
//# sourceMappingURL=chunk-
|
|
172
|
+
//# sourceMappingURL=chunk-7NMV2NPM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/helpers/EtherscanRemoteTransactionSource.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,eAAe;AAExB,SAAS,aAAa;AACtB,OAAO,QAAQ;AACf,SAAS,MAAM,cAAc;AAsB7B,IAAM,gCAAgC;AA1BtC;AA8BO,IAAM,mCAAN,MAEP;AAAA,EAOE,YAAY;AAAA,IACV;AAAA,EACF,IAAyC,CAAC,GAAG;AAuC7C;AA8CA;AAAA;AAAA;AAmBA;AAqBA;AAiBA;AAtJA;AAEA;AAEA,+BAAS,IAAI,MAAM;AAyDnB,iDAA2B,OACzB,SACA,qBACG;AACH,YAAM,EAAE,eAAe,IAAI;AAE3B,YAAM,wBAAwB,MAAM;AAAA,QAClC;AAAA,MACF;AAEA,aAAO,sBAAK,sDAAL,WAA8B,uBAAuB;AAAA,QAAI,CAAC,OAC/D,sBAAK,gDAAL,WAA2B,IAAI;AAAA,MACjC;AAAA,IACF;AAEA,gDAA0B,OACxB,SACA,qBACG;AACH,YAAM,EAAE,eAAe,IAAI;AAE3B,YAAM,wBAAwB,MAAM;AAAA,QAClC;AAAA,MACF;AAEA,aAAO,sBAAK,sDAAL,WAA8B,uBAAuB;AAAA,QAAI,CAAC,OAC/D,sBAAK,0DAAL,WAAgC,IAAI;AAAA,MACtC;AAAA,IACF;AAhFE,uBAAK,wBAAyB,yBAAyB;AACvD,uBAAK,wBAAyB;AAAA,EAChC;AAAA,EAEA,mBAAmB,SAAuB;AACxC,WAAO,OAAO,KAAK,4BAA4B,EAAE,SAAS,OAAO;AAAA,EACnE;AAAA,EAEA,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AAAA,MACR,GAAG,KAAK;AAAA,MACR,MAAM,OAAO;AAAA,IACf;AAAA,IACA,GAAI,OAAO,YAAY,MACnB,EAAE,oCAAoC,IACtC;AAAA,MACE,OAAO,IAAI,MAAM,oBAAoB;AAAA,MACrC;AAAA,IACF;AAAA,EACN;AACF;AAEA;AAAA,+BAA0B,SACxB,QACA,gBACiB;AACjB,QAAM,OAAO,sBAAK,wDAAL,WAA+B,QAAQ;AAEpD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY;AAAA,IACZ,qBAAqB;AAAA,MACnB,iBAAiB,OAAO;AAAA,MACxB,UAAU,OAAO,OAAO,YAAY;AAAA,MACpC,QAAQ,OAAO;AAAA,IACjB;AAAA,EACF;AACF;AAEA;AAAA,8BAAyB,SACvB,QACA,gBACiB;AACjB,QAAM,OAAO,SAAS,OAAO,WAAW,EAAE,IAAI;AAE9C,SAAO;AAAA,IACL,aAAa,OAAO;AAAA,IACpB,SAAS;AAAA,IACT,MAAM,OAAO;AAAA,IACb,IAAI,OAAO,EAAE,OAAO,KAAK,CAAC;AAAA,IAC1B;AAAA,IACA;AAAA,IACA,UAAU;AAAA,MACR,SAAS;AAAA,MACT,MAAM,OAAO;AAAA,MACb,KAAK,QAAQ,IAAI,GAAG,OAAO,GAAG,CAAC;AAAA,MAC/B,UAAU,QAAQ,IAAI,GAAG,OAAO,QAAQ,CAAC;AAAA,MACzC,SAAS,QAAQ,IAAI,GAAG,OAAO,OAAO,CAAC;AAAA,MACvC,OAAO,QAAQ,IAAI,GAAG,OAAO,KAAK,CAAC;AAAA,MACnC,IAAI,OAAO;AAAA,MACX,OAAO,QAAQ,IAAI,GAAG,OAAO,KAAK,CAAC;AAAA,IACrC;AAAA,IACA;AAAA,IACA,sBAAsB;AAAA,EACxB;AACF","sourcesContent":["import { BNToHex } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport BN from 'bn.js';\nimport { v1 as random } from 'uuid';\n\nimport { ETHERSCAN_SUPPORTED_NETWORKS } from '../constants';\nimport { incomingTransactionsLogger as log } from '../logger';\nimport type {\n RemoteTransactionSource,\n RemoteTransactionSourceRequest,\n TransactionMeta,\n} from '../types';\nimport { TransactionStatus, TransactionType } from '../types';\nimport {\n fetchEtherscanTokenTransactions,\n fetchEtherscanTransactions,\n} from '../utils/etherscan';\nimport type {\n EtherscanTokenTransactionMeta,\n EtherscanTransactionMeta,\n EtherscanTransactionMetaBase,\n EtherscanTransactionRequest,\n EtherscanTransactionResponse,\n} from '../utils/etherscan';\n\nconst ETHERSCAN_RATE_LIMIT_INTERVAL = 5000;\n/**\n * A RemoteTransactionSource that fetches transaction data from Etherscan.\n */\nexport class EtherscanRemoteTransactionSource\n implements RemoteTransactionSource\n{\n #includeTokenTransfers: boolean;\n\n #isTokenRequestPending: boolean;\n\n #mutex = new Mutex();\n\n constructor({\n includeTokenTransfers,\n }: { includeTokenTransfers?: boolean } = {}) {\n this.#includeTokenTransfers = includeTokenTransfers ?? true;\n this.#isTokenRequestPending = false;\n }\n\n isSupportedNetwork(chainId: Hex): boolean {\n return Object.keys(ETHERSCAN_SUPPORTED_NETWORKS).includes(chainId);\n }\n\n getLastBlockVariations(): string[] {\n return [this.#isTokenRequestPending ? 'token' : 'normal'];\n }\n\n async fetchTransactions(\n request: RemoteTransactionSourceRequest,\n ): Promise<TransactionMeta[]> {\n const releaseLock = await this.#mutex.acquire();\n const acquiredTime = Date.now();\n\n const etherscanRequest: EtherscanTransactionRequest = {\n ...request,\n chainId: request.currentChainId,\n };\n\n try {\n const transactions = this.#isTokenRequestPending\n ? await this.#fetchTokenTransactions(request, etherscanRequest)\n : await this.#fetchNormalTransactions(request, etherscanRequest);\n\n if (this.#includeTokenTransfers) {\n this.#isTokenRequestPending = !this.#isTokenRequestPending;\n }\n\n return transactions;\n } finally {\n this.#releaseLockAfterInterval(acquiredTime, releaseLock);\n }\n }\n\n #releaseLockAfterInterval(acquireTime: number, releaseLock: () => void) {\n const elapsedTime = Date.now() - acquireTime;\n const remainingTime = Math.max(\n 0,\n ETHERSCAN_RATE_LIMIT_INTERVAL - elapsedTime,\n );\n // Wait for the remaining time if it hasn't been 5 seconds yet\n if (remainingTime > 0) {\n setTimeout(releaseLock, remainingTime);\n } else {\n releaseLock();\n }\n }\n\n #fetchNormalTransactions = async (\n request: RemoteTransactionSourceRequest,\n etherscanRequest: EtherscanTransactionRequest,\n ) => {\n const { currentChainId } = request;\n\n const etherscanTransactions = await fetchEtherscanTransactions(\n etherscanRequest,\n );\n\n return this.#getResponseTransactions(etherscanTransactions).map((tx) =>\n this.#normalizeTransaction(tx, currentChainId),\n );\n };\n\n #fetchTokenTransactions = async (\n request: RemoteTransactionSourceRequest,\n etherscanRequest: EtherscanTransactionRequest,\n ) => {\n const { currentChainId } = request;\n\n const etherscanTransactions = await fetchEtherscanTokenTransactions(\n etherscanRequest,\n );\n\n return this.#getResponseTransactions(etherscanTransactions).map((tx) =>\n this.#normalizeTokenTransaction(tx, currentChainId),\n );\n };\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n #getResponseTransactions<T extends EtherscanTransactionMetaBase>(\n response: EtherscanTransactionResponse<T>,\n ): T[] {\n let result = response.result as T[];\n\n if (response.status === '0') {\n result = [];\n\n if (response.result.length) {\n log('Ignored Etherscan request error', {\n message: response.result,\n type: this.#isTokenRequestPending ? 'token' : 'normal',\n });\n }\n }\n\n return result;\n }\n\n #normalizeTransaction(\n txMeta: EtherscanTransactionMeta,\n currentChainId: Hex,\n ): TransactionMeta {\n const base = this.#normalizeTransactionBase(txMeta, currentChainId);\n\n return {\n ...base,\n txParams: {\n ...base.txParams,\n data: txMeta.input,\n },\n ...(txMeta.isError === '0'\n ? { status: TransactionStatus.confirmed }\n : {\n error: new Error('Transaction failed'),\n status: TransactionStatus.failed,\n }),\n };\n }\n\n #normalizeTokenTransaction(\n txMeta: EtherscanTokenTransactionMeta,\n currentChainId: Hex,\n ): TransactionMeta {\n const base = this.#normalizeTransactionBase(txMeta, currentChainId);\n\n return {\n ...base,\n isTransfer: true,\n transferInformation: {\n contractAddress: txMeta.contractAddress,\n decimals: Number(txMeta.tokenDecimal),\n symbol: txMeta.tokenSymbol,\n },\n };\n }\n\n #normalizeTransactionBase(\n txMeta: EtherscanTransactionMetaBase,\n currentChainId: Hex,\n ): TransactionMeta {\n const time = parseInt(txMeta.timeStamp, 10) * 1000;\n\n return {\n blockNumber: txMeta.blockNumber,\n chainId: currentChainId,\n hash: txMeta.hash,\n id: random({ msecs: time }),\n status: TransactionStatus.confirmed,\n time,\n txParams: {\n chainId: currentChainId,\n from: txMeta.from,\n gas: BNToHex(new BN(txMeta.gas)),\n gasPrice: BNToHex(new BN(txMeta.gasPrice)),\n gasUsed: BNToHex(new BN(txMeta.gasUsed)),\n nonce: BNToHex(new BN(txMeta.nonce)),\n to: txMeta.to,\n value: BNToHex(new BN(txMeta.value)),\n },\n type: TransactionType.incoming,\n verifiedOnBlockchain: false,\n };\n }\n}\n"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkQTKXIDGEjs = require('./chunk-QTKXIDGE.js');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
var _chunkS6VGOPUYjs = require('./chunk-S6VGOPUY.js');
|
|
7
7
|
|
|
8
8
|
|
|
9
|
-
var
|
|
9
|
+
var _chunkAYTU4HU5js = require('./chunk-AYTU4HU5.js');
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
@@ -48,7 +48,7 @@ var LineaGasFeeFlow = class {
|
|
|
48
48
|
return await _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getLineaGasFees, getLineaGasFees_fn).call(this, request);
|
|
49
49
|
} catch (error) {
|
|
50
50
|
log("Using default flow as fallback due to error", error);
|
|
51
|
-
return new (0,
|
|
51
|
+
return new (0, _chunkQTKXIDGEjs.DefaultGasFeeFlow)().getGasFees(request);
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
54
|
};
|
|
@@ -63,7 +63,7 @@ getLineaGasFees_fn = async function(request) {
|
|
|
63
63
|
log("Generated priority fees", _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _feesToString, feesToString_fn).call(this, priorityFees));
|
|
64
64
|
const maxFees = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getMaxFees, getMaxFees_fn).call(this, baseFees, priorityFees);
|
|
65
65
|
log("Generated max fees", _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _feesToString, feesToString_fn).call(this, maxFees));
|
|
66
|
-
const estimates = Object.values(
|
|
66
|
+
const estimates = Object.values(_chunkAYTU4HU5js.GasFeeEstimateLevel).reduce(
|
|
67
67
|
(result, level) => ({
|
|
68
68
|
...result,
|
|
69
69
|
[level]: {
|
|
@@ -110,7 +110,7 @@ getMaxFees_fn = function(baseFees, priorityFees) {
|
|
|
110
110
|
};
|
|
111
111
|
_feesToString = new WeakSet();
|
|
112
112
|
feesToString_fn = function(fees) {
|
|
113
|
-
return Object.values(
|
|
113
|
+
return Object.values(_chunkAYTU4HU5js.GasFeeEstimateLevel).map(
|
|
114
114
|
(level) => fees[level].toString(10)
|
|
115
115
|
);
|
|
116
116
|
};
|
|
@@ -118,4 +118,4 @@ feesToString_fn = function(fees) {
|
|
|
118
118
|
|
|
119
119
|
|
|
120
120
|
exports.LineaGasFeeFlow = LineaGasFeeFlow;
|
|
121
|
-
//# sourceMappingURL=chunk-
|
|
121
|
+
//# sourceMappingURL=chunk-ARZHJFVG.js.map
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/types.ts
|
|
2
2
|
var TransactionStatus = /* @__PURE__ */ ((TransactionStatus2) => {
|
|
3
|
+
TransactionStatus2["unapproved"] = "unapproved";
|
|
3
4
|
TransactionStatus2["approved"] = "approved";
|
|
4
|
-
TransactionStatus2["
|
|
5
|
+
TransactionStatus2["signed"] = "signed";
|
|
6
|
+
TransactionStatus2["submitted"] = "submitted";
|
|
5
7
|
TransactionStatus2["confirmed"] = "confirmed";
|
|
6
|
-
TransactionStatus2["dropped"] = "dropped";
|
|
7
8
|
TransactionStatus2["failed"] = "failed";
|
|
9
|
+
TransactionStatus2["dropped"] = "dropped";
|
|
8
10
|
TransactionStatus2["rejected"] = "rejected";
|
|
9
|
-
TransactionStatus2["
|
|
10
|
-
TransactionStatus2["submitted"] = "submitted";
|
|
11
|
-
TransactionStatus2["unapproved"] = "unapproved";
|
|
11
|
+
TransactionStatus2["cancelled"] = "cancelled";
|
|
12
12
|
return TransactionStatus2;
|
|
13
13
|
})(TransactionStatus || {});
|
|
14
14
|
var WalletDevice = /* @__PURE__ */ ((WalletDevice2) => {
|
|
@@ -89,4 +89,4 @@ var SimulationErrorCode = /* @__PURE__ */ ((SimulationErrorCode2) => {
|
|
|
89
89
|
|
|
90
90
|
|
|
91
91
|
exports.TransactionStatus = TransactionStatus; exports.WalletDevice = WalletDevice; exports.TransactionType = TransactionType; exports.TransactionEnvelopeType = TransactionEnvelopeType; exports.UserFeeLevel = UserFeeLevel; exports.GasFeeEstimateLevel = GasFeeEstimateLevel; exports.GasFeeEstimateType = GasFeeEstimateType; exports.SimulationTokenStandard = SimulationTokenStandard; exports.SimulationErrorCode = SimulationErrorCode;
|
|
92
|
-
//# sourceMappingURL=chunk-
|
|
92
|
+
//# sourceMappingURL=chunk-AYTU4HU5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"names":["TransactionStatus","WalletDevice","TransactionType","TransactionEnvelopeType","UserFeeLevel","GasFeeEstimateLevel","GasFeeEstimateType","SimulationTokenStandard","SimulationErrorCode"],"mappings":";AA4cO,IAAK,oBAAL,kBAAKA,uBAAL;AAML,EAAAA,mBAAA,gBAAa;AAQb,EAAAA,mBAAA,cAAW;AAQX,EAAAA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AAAA;AAAA,GAAA;AAsFL,IAAK,sBAAL,kBAAKC,yBAAL;AACL,EAAAA,qBAAA,SAAM;AACN,EAAAA,qBAAA,YAAS;AACT,EAAAA,qBAAA,UAAO;AAHG,SAAAA;AAAA,GAAA;AAOL,IAAK,qBAAL,kBAAKC,wBAAL;AACL,EAAAA,oBAAA,eAAY;AACZ,EAAAA,oBAAA,YAAS;AACT,EAAAA,oBAAA,cAAW;AAHD,SAAAA;AAAA,GAAA;AAgIL,IAAK,0BAAL,kBAAKC,6BAAL;AAGL,EAAAA,yBAAA,WAAQ;AAGR,EAAAA,yBAAA,YAAS;AAGT,EAAAA,yBAAA,aAAU;AATA,SAAAA;AAAA,GAAA;AA4BL,IAAK,sBAAL,kBAAKC,yBAAL;AACL,EAAAA,qBAAA,uBAAoB;AACpB,EAAAA,qBAAA,cAAW;AACX,EAAAA,qBAAA,qBAAkB;AAClB,EAAAA,qBAAA,cAAW;AAJD,SAAAA;AAAA,GAAA","sourcesContent":["import type { AccessList } from '@ethereumjs/tx';\nimport type EthQuery from '@metamask/eth-query';\nimport type { GasFeeState } from '@metamask/gas-fee-controller';\nimport type { NetworkClientId, Provider } from '@metamask/network-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Operation } from 'fast-json-patch';\n\n/**\n * Given a record, ensures that each property matches the `Json` type.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\ntype MakeJsonCompatible<T> = T extends Json\n ? T\n : {\n [K in keyof T]: T[K] extends Json ? T[K] : never;\n };\n\n/**\n * `Json` from `@metamask/utils` is defined as a recursive type alias, but\n * `Operation` is defined as an interface, and the two are not compatible with\n * each other. Therefore, this is a variant of Operation from `fast-json-patch`\n * which is guaranteed to be type-compatible with `Json`.\n */\ntype JsonCompatibleOperation = MakeJsonCompatible<Operation>;\n\n/**\n * Representation of transaction metadata.\n */\nexport type TransactionMeta = TransactionMetaBase &\n (\n | {\n status: Exclude<TransactionStatus, TransactionStatus.failed>;\n }\n | {\n status: TransactionStatus.failed;\n error: TransactionError;\n }\n );\n\n/**\n * Information about a single transaction such as status and block number.\n */\ntype TransactionMetaBase = {\n /**\n * ID of the transaction that approved the swap token transfer.\n */\n approvalTxId?: string;\n\n /**\n * Unique ID to prevent duplicate requests.\n */\n actionId?: string;\n\n /**\n * Base fee of the block as a hex value, introduced in EIP-1559.\n */\n baseFeePerGas?: Hex;\n\n /**\n * Number of the block where the transaction has been included.\n */\n blockNumber?: string;\n\n /**\n * The timestamp for when the block was collated.\n */\n blockTimestamp?: string;\n\n /**\n * Network code as per EIP-155 for this transaction.\n */\n chainId: Hex;\n\n /**\n * A string representing a name of transaction contract method.\n */\n contractMethodName?: string;\n\n /**\n * The balance of the token that is being sent.\n */\n currentTokenBalance?: string;\n\n /**\n * Unique ID for custodian transaction.\n */\n custodyId?: string;\n\n /**\n * Custodian transaction status.\n */\n custodyStatus?: string;\n\n /** The optional custom nonce override as a decimal string. */\n customNonceValue?: string;\n\n /**\n * The custom token amount is the amount set by the user.\n */\n customTokenAmount?: string;\n\n /**\n * The dapp proposed token amount.\n */\n dappProposedTokenAmount?: string;\n\n /**\n * Gas values provided by the dApp.\n */\n dappSuggestedGasFees?: DappSuggestedGasFees;\n\n /**\n * The initial gas values set when the transaction was first created.\n */\n defaultGasEstimates?: DefaultGasEstimates;\n\n /**\n * String to indicate what device the transaction was confirmed on.\n */\n deviceConfirmedOn?: WalletDevice;\n\n /**\n * The address of the token being received of swap transaction.\n */\n destinationTokenAddress?: string;\n\n /**\n * The raw amount of the destination token\n */\n destinationTokenAmount?: string;\n\n /**\n * The decimals of the token being received of swap transaction.\n */\n destinationTokenDecimals?: number;\n\n /**\n * The symbol of the token being received with swap.\n */\n destinationTokenSymbol?: string;\n\n /**\n * The estimated base fee of the transaction.\n */\n estimatedBaseFee?: string;\n\n /**\n * Which estimate level that the API suggested.\n */\n estimateSuggested?: string;\n\n /**\n * Which estimate level was used\n */\n estimateUsed?: string;\n\n /**\n * The chosen amount which will be the same as the originally proposed token\n * amount if the user does not edit the amount or will be a custom token\n * amount set by the user.\n */\n finalApprovalAmount?: string;\n\n /**\n * The number of the latest block when the transaction submit was first retried.\n */\n firstRetryBlockNumber?: string;\n\n /** Alternate EIP-1559 gas fee estimates for multiple priority levels. */\n gasFeeEstimates?: GasFeeEstimates;\n\n /** Whether the gas fee estimates have been checked at least once. */\n gasFeeEstimatesLoaded?: boolean;\n\n /**\n * A hex string of the transaction hash, used to identify the transaction on the network.\n */\n hash?: string;\n\n /**\n * A history of mutations to TransactionMeta.\n */\n history?: TransactionHistory;\n\n /**\n * Generated UUID associated with this transaction.\n */\n id: string;\n\n /**\n * Whether the transaction is a transfer.\n */\n isTransfer?: boolean;\n\n /**\n * Whether the transaction entry is generated from a user operation.\n */\n isUserOperation?: boolean;\n\n /**\n * Additional gas fees to cover the cost of persisting data on layer 1 for layer 2 networks.\n */\n layer1GasFee?: Hex;\n\n /**\n * The ID of the network client used by the transaction.\n */\n networkClientId?: NetworkClientId;\n\n /**\n * Network code as per EIP-155 for this transaction\n *\n * @deprecated Use `chainId` instead.\n */\n readonly networkID?: string;\n\n /**\n * Origin this transaction was sent from.\n */\n origin?: string;\n\n /**\n * The original dapp proposed token approval amount before edit by user.\n */\n originalApprovalAmount?: string;\n\n /**\n * The original gas estimation of the transaction.\n */\n originalGasEstimate?: string;\n\n /**\n * When we speed up a transaction, we set the type as Retry and we lose\n * information about type of transaction that is being set up, so we use\n * original type to track that information.\n */\n originalType?: TransactionType;\n\n /**\n * Account transaction balance after swap.\n */\n postTxBalance?: string;\n\n /**\n * Account transaction balance before swap.\n */\n preTxBalance?: string;\n\n /**\n * The previous gas properties before they were updated.\n */\n previousGas?: {\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gasLimit?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n };\n\n /**\n * The transaction's 'r' value as a hex string.\n */\n r?: string;\n\n /**\n * Hex representation of the underlying transaction.\n */\n rawTx?: string;\n\n /**\n * When the transaction is dropped, this is the replacement transaction hash.\n */\n replacedBy?: string;\n\n /**\n * When the transaction is dropped, this is the replacement transaction ID.\n */\n replacedById?: string;\n\n /**\n * The number of times that the transaction submit has been retried.\n */\n retryCount?: number;\n\n /**\n * The transaction's 's' value as a hex string.\n */\n s?: string;\n\n /**\n * Response from security validator.\n */\n securityAlertResponse?: SecurityAlertResponse;\n\n /**\n * Response from security provider.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n securityProviderResponse?: Record<string, any>;\n\n /**\n * An array of entries that describe the user's journey through the send flow.\n * This is purely attached to state logs for troubleshooting and support.\n */\n sendFlowHistory?: SendFlowHistoryEntry[];\n\n /**\n * Simulation data for the transaction used to predict its outcome.\n */\n simulationData?: SimulationData;\n\n /**\n * If the gas estimation fails, an object containing error and block information.\n */\n simulationFails?: {\n reason?: string;\n errorKey?: string;\n debug: {\n blockNumber?: string;\n blockGasLimit?: string;\n };\n };\n\n /**\n * The time the transaction was submitted to the network, in Unix epoch time (ms).\n */\n submittedTime?: number;\n\n /**\n * The address of the token being swapped\n */\n sourceTokenAddress?: string;\n\n /**\n * The raw amount of the source swap token\n */\n sourceTokenAmount?: string;\n\n /**\n * The decimals of the token being swapped.\n */\n sourceTokenDecimals?: number;\n\n /**\n * The symbol of the token being swapped.\n */\n sourceTokenSymbol?: string;\n\n /**\n * The address of the swap recipient.\n */\n swapAndSendRecipient?: string;\n\n /**\n * The metadata of the swap transaction.\n */\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapMetaData?: Record<string, any>;\n\n /**\n * The value of the token being swapped.\n */\n swapTokenValue?: string;\n\n /**\n * Timestamp associated with this transaction.\n */\n time: number;\n\n /**\n * Whether transaction recipient is a smart contract.\n */\n toSmartContract?: boolean;\n\n /**\n * Additional transfer information.\n */\n transferInformation?: {\n contractAddress: string;\n decimals: number;\n symbol: string;\n };\n\n /**\n * Underlying Transaction object.\n */\n txParams: TransactionParams;\n\n /**\n * Transaction receipt.\n */\n txReceipt?: TransactionReceipt;\n\n /**\n * The type of transaction such as `cancel` or `swap`.\n */\n type?: TransactionType;\n\n /**\n * The gas limit supplied by user.\n */\n userEditedGasLimit?: boolean;\n\n /**\n * Estimate level user selected.\n */\n userFeeLevel?: string;\n\n /**\n * The transaction's 'v' value as a hex string.\n */\n v?: string;\n\n /**\n * Whether the transaction is verified on the blockchain.\n */\n verifiedOnBlockchain?: boolean;\n\n /**\n * Warning information for the transaction.\n */\n warning?: {\n error: string;\n message: string;\n };\n};\n\nexport type SendFlowHistoryEntry = {\n /**\n * String to indicate user interaction information.\n */\n entry: string;\n\n /**\n * Timestamp associated with this entry.\n */\n timestamp: number;\n};\n\n/**\n * Represents the status of a transaction within the wallet.\n * Each status reflects the state of the transaction internally,\n * with some statuses corresponding to the transaction's state on the network.\n *\n * The typical transaction lifecycle follows this state machine:\n * unapproved -> approved -> signed -> submitted -> FINAL_STATE\n * where FINAL_STATE is one of: confirmed, failed, dropped, or rejected.\n */\nexport enum TransactionStatus {\n /**\n * The initial state of a transaction before user approval.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n unapproved = 'unapproved',\n\n /**\n * The transaction has been approved by the user but is not yet signed.\n * This status is usually brief but may be longer for scenarios like hardware wallet usage.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n approved = 'approved',\n\n /**\n * The transaction is signed and in the process of being submitted to the network.\n * This status is typically short-lived but can be longer for certain cases, such as smart transactions.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n signed = 'signed',\n\n /**\n * The transaction has been submitted to the network and is awaiting confirmation.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n submitted = 'submitted',\n\n /**\n * The transaction has been successfully executed and confirmed on the blockchain.\n * This is a final state.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n confirmed = 'confirmed',\n\n /**\n * The transaction encountered an error during execution on the blockchain and failed.\n * This is a final state.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n failed = 'failed',\n\n /**\n * The transaction was superseded by another transaction, resulting in its dismissal.\n * This is a final state.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n dropped = 'dropped',\n\n /**\n * The transaction was rejected by the user and not processed further.\n * This is a final state.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n rejected = 'rejected',\n\n /**\n * @deprecated This status is no longer used.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n cancelled = 'cancelled',\n}\n\n/**\n * Options for wallet device.\n */\nexport enum WalletDevice {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n MM_MOBILE = 'metamask_mobile',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n MM_EXTENSION = 'metamask_extension',\n OTHER = 'other_device',\n}\n\n/**\n * The type of the transaction.\n */\nexport enum TransactionType {\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n cancel = 'cancel',\n\n /**\n * A transaction that is interacting with a smart contract's methods that we\n * have not treated as a special case, such as approve, transfer, and\n * transferfrom.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n contractInteraction = 'contractInteraction',\n\n /**\n * A transaction that deployed a smart contract.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n deployContract = 'contractDeployment',\n\n /**\n * A transaction for Ethereum decryption.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ethDecrypt = 'eth_decrypt',\n\n /**\n * A transaction for getting an encryption public key.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ethGetEncryptionPublicKey = 'eth_getEncryptionPublicKey',\n\n /**\n * An incoming (deposit) transaction.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n incoming = 'incoming',\n\n /**\n * A transaction for personal sign.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n personalSign = 'personal_sign',\n\n /**\n * When a transaction is failed it can be retried by\n * resubmitting the same transaction with a higher gas fee. This type is also used\n * to speed up pending transactions. This is accomplished by creating a new tx with\n * the same nonce and higher gas fees.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n retry = 'retry',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n simpleSend = 'simpleSend',\n\n /**\n * A transaction that is signing typed data.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n signTypedData = 'eth_signTypedData',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n smart = 'smart',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n swap = 'swap',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps, then sending the swapped token to a recipient.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n swapAndSend = 'swapAndSend',\n\n /**\n * Similar to the approve type, a swap approval is a special case of ERC20\n * approve method that requests an allowance of the token to spend on behalf\n * of the user for the MetaMask Swaps contract. The first swap for any token\n * will have an accompanying swapApproval transaction.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n swapApproval = 'swapApproval',\n\n /**\n * A token transaction requesting an allowance of the token to spend on\n * behalf of the user.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodApprove = 'approve',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. The method is prefixed with safe because when calling\n * this method the contract checks to ensure that the receiver is an address\n * capable of handling the token being sent.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodSafeTransferFrom = 'safetransferfrom',\n\n /**\n * A token transaction where the user is sending tokens that they own to\n * another address.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodTransfer = 'transfer',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. For more information on allowances, see the approve\n * type.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodTransferFrom = 'transferfrom',\n\n /**\n * A token transaction requesting an allowance of all of a user's tokens to\n * spend on behalf of the user.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodSetApprovalForAll = 'setapprovalforall',\n\n /**\n * Increase the allowance by a given increment\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n tokenMethodIncreaseAllowance = 'increaseAllowance',\n}\n\n/**\n * Standard data concerning a transaction to be processed by the blockchain.\n */\nexport type TransactionParams = {\n /**\n * A list of addresses and storage keys that the transaction plans to access.\n */\n accessList?: AccessList;\n\n /**\n * Network ID as per EIP-155.\n */\n chainId?: Hex;\n\n /**\n * Data to pass with this transaction.\n */\n data?: string;\n\n /**\n * Error message for gas estimation failure.\n */\n estimateGasError?: string;\n\n /**\n * Estimated base fee for this transaction.\n */\n estimatedBaseFee?: string;\n\n /**\n * Which estimate level that the API suggested.\n */\n estimateSuggested?: string;\n\n /**\n * Which estimate level was used\n */\n estimateUsed?: string;\n\n /**\n * Address to send this transaction from.\n */\n from: string;\n\n /**\n * same as gasLimit?\n */\n gas?: string;\n\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gasLimit?: string;\n\n /**\n * Price per gas for legacy txs\n */\n gasPrice?: string;\n\n /**\n * Gas used in the transaction.\n */\n gasUsed?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority\n * fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n\n /**\n * Unique number to prevent replay attacks.\n */\n nonce?: string;\n\n /**\n * Address to send this transaction to.\n */\n to?: string;\n\n /**\n * Value associated with this transaction.\n */\n value?: string;\n\n /**\n * Type of transaction.\n * 0x0 indicates a legacy transaction.\n */\n type?: string;\n};\n\n/**\n * Standard data concerning a transaction processed by the blockchain.\n */\nexport type TransactionReceipt = {\n /**\n * The block hash of the block that this transaction was included in.\n */\n blockHash?: string;\n\n /**\n * The block number of the block that this transaction was included in.\n */\n blockNumber?: string;\n\n /**\n * Effective gas price the transaction was charged at.\n */\n effectiveGasPrice?: string;\n\n /**\n * Gas used in the transaction.\n */\n gasUsed?: string;\n\n /**\n * Total used gas in hex.\n */\n l1Fee?: string;\n\n /**\n * All the logs emitted by this transaction.\n */\n logs?: Log[];\n\n /**\n * The status of the transaction.\n */\n status?: string;\n\n /**\n * The hexadecimal index of this transaction in the list of transactions included in the block this transaction was mined in.\n */\n transactionIndex?: string;\n};\n\n/**\n * Represents an event that has been included in a transaction using the EVM `LOG` opcode.\n */\nexport type Log = {\n /**\n * Address of the contract that generated log.\n */\n address?: string;\n /**\n * List of topics for log.\n */\n topics?: string;\n};\n\n/**\n * The configuration required to fetch transaction data from a RemoteTransactionSource.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface RemoteTransactionSourceRequest {\n /**\n * The address of the account to fetch transactions for.\n */\n address: string;\n\n /**\n * The chainId of the current network.\n */\n currentChainId: Hex;\n\n /**\n * Block number to start fetching transactions from.\n */\n fromBlock?: number;\n\n /**\n * Maximum number of transactions to retrieve.\n */\n limit?: number;\n}\n\n/**\n * An object capable of fetching transaction data from a remote source.\n * Used by the IncomingTransactionHelper to retrieve remote transaction data.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface RemoteTransactionSource {\n /**\n * @param chainId - The chainId of the current network.\n * @returns Whether the remote transaction source supports the specified network.\n */\n isSupportedNetwork: (chainId: Hex) => boolean;\n\n /**\n * @returns An array of additional keys to use when caching the last fetched block number.\n */\n getLastBlockVariations?: () => string[];\n\n /**\n * @param request - A request object containing data such as the address and chain ID.\n * @returns An array of transaction metadata for the retrieved transactions.\n */\n fetchTransactions: (\n request: RemoteTransactionSourceRequest,\n ) => Promise<TransactionMeta[]>;\n}\n\n/**\n * Gas values initially suggested by the dApp.\n */\nexport type DappSuggestedGasFees = {\n gas?: string;\n gasPrice?: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Gas values saved by the user for a specific chain.\n */\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SavedGasFees {\n maxBaseFee: string;\n priorityFee: string;\n}\n\n/**\n * A transaction history operation that includes a note and timestamp.\n */\ntype ExtendedHistoryOperation = JsonCompatibleOperation & {\n note?: string;\n timestamp?: number;\n};\n\n/**\n * A transaction history entry that includes the ExtendedHistoryOperation as the first element.\n */\nexport type TransactionHistoryEntry = [\n ExtendedHistoryOperation,\n ...JsonCompatibleOperation[],\n];\n\n/**\n * A transaction history that includes the transaction meta as the first element.\n * And the rest of the elements are the operation arrays that were applied to the transaction meta.\n */\nexport type TransactionHistory = [\n TransactionMeta,\n ...TransactionHistoryEntry[],\n];\n\n/**\n * Result of inferring the transaction type.\n */\nexport type InferTransactionTypeResult = {\n /**\n * The contract code, in hex format if it exists. '0x0' or\n * '0x' are also indicators of non-existent contract code.\n */\n getCodeResponse?: string | null;\n\n /**\n * The type of transaction\n */\n type: TransactionType;\n};\n\n/**\n * A function for verifying a transaction, whether it is malicious or not.\n */\nexport type SecurityProviderRequest = (\n requestData: TransactionMeta,\n messageType: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\n/**\n * Specifies the shape of the base transaction parameters.\n * Added in EIP-2718.\n */\nexport enum TransactionEnvelopeType {\n /**\n * A legacy transaction, the very first type.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n legacy = '0x0',\n\n /**\n * EIP-2930 defined the access list transaction type that allowed for\n * specifying the state that a transaction would act upon in advance and\n * theoretically save on gas fees.\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n accessList = '0x1',\n\n /**\n * The type introduced comes from EIP-1559, Fee Market describes the addition\n * of a baseFee to blocks that will be burned instead of distributed to\n * miners. Transactions of this type have both a maxFeePerGas (maximum total\n * amount in gwei per gas to spend on the transaction) which is inclusive of\n * the maxPriorityFeePerGas (maximum amount of gwei per gas from the\n * transaction fee to distribute to miner).\n */\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n feeMarket = '0x2',\n}\n\n/**\n * The source of the gas fee parameters on a transaction.\n */\nexport enum UserFeeLevel {\n CUSTOM = 'custom',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n DAPP_SUGGESTED = 'dappSuggested',\n MEDIUM = 'medium',\n}\n\n/**\n * Initial gas values set when the transaction was first created.\n */\nexport type DefaultGasEstimates = {\n /**\n * Source of the gas fee values, such as `dappSuggested` or `medium`.\n */\n estimateType?: string;\n\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gas?: string;\n\n /**\n * Price per gas for legacy transactions.\n */\n gasPrice?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Data concerning an error while processing a transaction.\n */\nexport type TransactionError = {\n /**\n * A descriptive error name.\n */\n name: string;\n\n /**\n * A descriptive error message providing details about the encountered error.\n */\n message: string;\n\n /**\n * The stack trace associated with the error, if available.\n */\n stack?: string;\n\n /**\n * An optional error code associated with the error.\n */\n code?: string;\n\n /**\n * The rpc property holds additional information related to the error.\n */\n // We are intentionally using `any` here instead of `Json` because it causes\n // `WritableDraft<TransactionMeta>` from Immer to cause TypeScript to error\n // with \"Type instantiation is excessively deep and possibly infinite\". See:\n // <https://github.com/immerjs/immer/issues/839>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc?: any;\n};\n\n/**\n * Type for security alert response from transaction validator.\n */\nexport type SecurityAlertResponse = {\n reason: string;\n features?: string[];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n result_type: string;\n providerRequestsCount?: Record<string, number>;\n};\n\n/** Alternate priority levels for which values are provided in gas fee estimates. */\nexport enum GasFeeEstimateLevel {\n Low = 'low',\n Medium = 'medium',\n High = 'high',\n}\n\n/** Type of gas fee estimate generated by a GasFeeFlow. */\nexport enum GasFeeEstimateType {\n FeeMarket = 'fee-market',\n Legacy = 'legacy',\n GasPrice = 'eth_gasPrice',\n}\n\n/** Gas fee estimates for a specific priority level. */\nexport type FeeMarketGasFeeEstimateForLevel = {\n /** Maximum amount to pay per gas. */\n maxFeePerGas: Hex;\n\n /** Maximum amount per gas to give to the validator as an incentive. */\n maxPriorityFeePerGas: Hex;\n};\n\n/** Gas fee estimates for a EIP-1559 transaction. */\nexport type FeeMarketGasFeeEstimates = {\n type: GasFeeEstimateType.FeeMarket;\n [GasFeeEstimateLevel.Low]: FeeMarketGasFeeEstimateForLevel;\n [GasFeeEstimateLevel.Medium]: FeeMarketGasFeeEstimateForLevel;\n [GasFeeEstimateLevel.High]: FeeMarketGasFeeEstimateForLevel;\n};\n\n/** Gas fee estimates for a legacy transaction. */\nexport type LegacyGasFeeEstimates = {\n type: GasFeeEstimateType.Legacy;\n [GasFeeEstimateLevel.Low]: Hex;\n [GasFeeEstimateLevel.Medium]: Hex;\n [GasFeeEstimateLevel.High]: Hex;\n};\n\n/** Gas fee estimates for a transaction retrieved with the eth_gasPrice method. */\nexport type GasPriceGasFeeEstimates = {\n type: GasFeeEstimateType.GasPrice;\n gasPrice: Hex;\n};\n\n/** Gas fee estimates for a transaction. */\nexport type GasFeeEstimates =\n | FeeMarketGasFeeEstimates\n | LegacyGasFeeEstimates\n | GasPriceGasFeeEstimates;\n\n/** Request to a gas fee flow to obtain gas fee estimates. */\nexport type GasFeeFlowRequest = {\n /** An EthQuery instance to enable queries to the associated RPC provider. */\n ethQuery: EthQuery;\n\n /** Gas fee controller data matching the chain ID of the transaction. */\n gasFeeControllerData: GasFeeState;\n\n /** The metadata of the transaction to obtain estimates for. */\n transactionMeta: TransactionMeta;\n};\n\n/** Response from a gas fee flow containing gas fee estimates. */\nexport type GasFeeFlowResponse = {\n /** The gas fee estimates for the transaction. */\n estimates: GasFeeEstimates;\n};\n\n/** A method of obtaining gas fee estimates for a specific transaction. */\nexport type GasFeeFlow = {\n /**\n * Determine if the gas fee flow supports the specified transaction.\n * @param transactionMeta - The transaction metadata.\n * @returns Whether the gas fee flow supports the transaction.\n */\n matchesTransaction(transactionMeta: TransactionMeta): boolean;\n\n /**\n * Get gas fee estimates for a specific transaction.\n * @param request - The gas fee flow request.\n * @returns The gas fee flow response containing the gas fee estimates.\n */\n getGasFees: (request: GasFeeFlowRequest) => Promise<GasFeeFlowResponse>;\n};\n\n/** Request to a layer 1 gas fee flow to obtain layer 1 fee estimate. */\nexport type Layer1GasFeeFlowRequest = {\n /** RPC Provider instance. */\n provider: Provider;\n\n /** The metadata of the transaction to obtain estimates for. */\n transactionMeta: TransactionMeta;\n};\n\n/** Response from a layer 1 gas fee flow containing layer 1 fee estimate. */\nexport type Layer1GasFeeFlowResponse = {\n /** The gas fee estimates for the transaction. */\n layer1Fee: Hex;\n};\n\n/** A method of obtaining layer 1 gas fee estimates for a specific transaction. */\nexport type Layer1GasFeeFlow = {\n /**\n * Determine if the gas fee flow supports the specified transaction.\n * @param transactionMeta - The transaction metadata.\n * @returns Whether the layer1 gas fee flow supports the transaction.\n */\n matchesTransaction(transactionMeta: TransactionMeta): boolean;\n\n /**\n * Get layer 1 gas fee estimates for a specific transaction.\n * @param request - The gas fee flow request.\n * @returns The gas fee flow response containing the layer 1 gas fee estimate.\n */\n getLayer1Fee: (\n request: Layer1GasFeeFlowRequest,\n ) => Promise<Layer1GasFeeFlowResponse>;\n};\n\n/** Simulation data concerning an update to a native or token balance. */\nexport type SimulationBalanceChange = {\n /** The balance before the transaction. */\n previousBalance: Hex;\n\n /** The balance after the transaction. */\n newBalance: Hex;\n\n /** The difference in balance. */\n difference: Hex;\n\n /** Whether the balance is increasing or decreasing. */\n isDecrease: boolean;\n};\n\n/** Token standards supported by simulation. */\nexport enum SimulationTokenStandard {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n erc20 = 'erc20',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n erc721 = 'erc721',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n erc1155 = 'erc1155',\n}\n\n/** Simulation data concerning an updated token. */\nexport type SimulationToken = {\n /** The token's contract address. */\n address: Hex;\n\n /** The standard of the token. */\n standard: SimulationTokenStandard;\n\n /** The ID of the token if supported by the standard. */\n id?: Hex;\n};\n\n/** Simulation data concerning a change to the a token balance. */\nexport type SimulationTokenBalanceChange = SimulationToken &\n SimulationBalanceChange;\n\nexport enum SimulationErrorCode {\n ChainNotSupported = 'chain-not-supported',\n Disabled = 'disabled',\n InvalidResponse = 'invalid-response',\n Reverted = 'reverted',\n}\n\n/** Error data for a failed simulation. */\nexport type SimulationError = {\n /** Error code to identify the error type. */\n code?: string | number;\n\n /** Error message to describe the error. */\n message?: string;\n};\n\n/** Simulation data for a transaction. */\nexport type SimulationData = {\n /** Error data if the simulation failed or the transaction reverted. */\n error?: SimulationError;\n\n /** Data concerning a change to the user's native balance. */\n nativeBalanceChange?: SimulationBalanceChange;\n\n /** Data concerning a change to the user's token balances. */\n tokenBalanceChanges: SimulationTokenBalanceChange[];\n};\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkQH2H4W3Njs = require('./chunk-QH2H4W3N.js');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunk76FONEDAjs = require('./chunk-76FONEDA.js');
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
var _chunkS6VGOPUYjs = require('./chunk-S6VGOPUY.js');
|
|
@@ -20,7 +20,7 @@ var log = _utils.createModuleLogger.call(void 0, _chunkS6VGOPUYjs.projectLogger,
|
|
|
20
20
|
async function updateGasFees(request) {
|
|
21
21
|
const { txMeta } = request;
|
|
22
22
|
const initialParams = { ...txMeta.txParams };
|
|
23
|
-
const isSwap =
|
|
23
|
+
const isSwap = _chunkQH2H4W3Njs.SWAP_TRANSACTION_TYPES.includes(
|
|
24
24
|
txMeta.type
|
|
25
25
|
);
|
|
26
26
|
const savedGasFees = isSwap ? void 0 : request.getSavedGasFees(txMeta.chainId);
|
|
@@ -186,7 +186,7 @@ async function getSuggestedGasFees(request) {
|
|
|
186
186
|
if (!eip1559 && txMeta.txParams.gasPrice || eip1559 && txMeta.txParams.maxFeePerGas && txMeta.txParams.maxPriorityFeePerGas) {
|
|
187
187
|
return {};
|
|
188
188
|
}
|
|
189
|
-
const gasFeeFlow =
|
|
189
|
+
const gasFeeFlow = _chunk76FONEDAjs.getGasFeeFlow.call(void 0, txMeta, gasFeeFlows);
|
|
190
190
|
try {
|
|
191
191
|
const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });
|
|
192
192
|
const response = await gasFeeFlow.getGasFees({
|
|
@@ -206,6 +206,8 @@ async function getSuggestedGasFees(request) {
|
|
|
206
206
|
return { gasPrice: response.estimates.gasPrice };
|
|
207
207
|
default:
|
|
208
208
|
throw new Error(
|
|
209
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
210
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
209
211
|
`Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`
|
|
210
212
|
);
|
|
211
213
|
}
|
|
@@ -221,4 +223,4 @@ async function getSuggestedGasFees(request) {
|
|
|
221
223
|
|
|
222
224
|
|
|
223
225
|
exports.updateGasFees = updateGasFees; exports.gweiDecimalToWeiHex = gweiDecimalToWeiHex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W,OAAO,SAAS;AACtD,SAAO,oBAAoB,eAAe,OAAO;AACnD;AAEA,eAAe,oBACb,SAC2B;AAC3B,QAAM,EAAE,SAAS,UAAU,aAAa,oBAAoB,OAAO,IACjE;AAEF,QAAM,EAAE,gBAAgB,IAAI;AAE5B,MACG,CAAC,WAAW,OAAO,SAAS,YAC5B,WACC,OAAO,SAAS,gBAChB,OAAO,SAAS,sBAClB;AACA,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,aAAa,cAAc,QAAQ,WAAW;AAEpD,MAAI;AACF,UAAM,uBAAuB,MAAM,mBAAmB,EAAE,gBAAgB,CAAC;AAEzE,UAAM,WAAW,MAAM,WAAW,WAAW;AAAA,MAC3C;AAAA,MACA;AAAA,MACA,iBAAiB;AAAA,IACnB,CAAC;AAED,UAAM,qBAAqB,SAAS,WAAW;AAE/C,YAAQ,oBAAoB;AAAA,MAC1B;AACE,eAAO,SAAS,UAAU;AAAA,MAC5B;AACE,eAAO;AAAA,UACL,UAAU,SAAS,UAAU;AAAA,QAC/B;AAAA,MACF;AACE,eAAO,EAAE,UAAU,SAAS,UAAU,SAAS;AAAA,MACjD;AACE,cAAM,IAAI;AAAA;AAAA;AAAA,UAGR,yDAAyD,kBAAkB;AAAA,QAC7E;AAAA,IACJ;AAAA,EACF,SAAS,OAAO;AACd,QAAI,oCAAoC,KAAK;AAAA,EAC/C;AAEA,QAAM,kBAAmB,MAAM,MAAM,UAAU,UAAU;AAEzD,QAAM,WAAW,kBACb,MAAM,gBAAgB,SAAS,EAAE,CAAC,IAClC;AAEJ,SAAO,EAAE,SAAS;AACpB","sourcesContent":["/* eslint-disable jsdoc/require-jsdoc */\n\nimport {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n GasFeeFlow,\n} from '../types';\nimport { GasFeeEstimateType, UserFeeLevel } from '../types';\nimport { getGasFeeFlow } from './gas-flow';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n gasFeeFlows: GasFeeFlow[];\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getSavedGasFees: (chainId: Hex) => SavedGasFees | undefined;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n initialParams: TransactionParams;\n savedGasFees?: SavedGasFees;\n suggestedGasFees: SuggestedGasFees;\n};\n\ntype SuggestedGasFees = {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n gasPrice?: string;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap\n ? undefined\n : request.getSavedGasFees(txMeta.chainId);\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest: GetGasFeeRequest = {\n ...request,\n initialParams,\n savedGasFees,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\nexport function gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee as string);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\nasync function getSuggestedGasFees(\n request: UpdateGasFeesRequest,\n): Promise<SuggestedGasFees> {\n const { eip1559, ethQuery, gasFeeFlows, getGasFeeEstimates, txMeta } =\n request;\n\n const { networkClientId } = txMeta;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n const gasFeeFlow = getGasFeeFlow(txMeta, gasFeeFlows) as GasFeeFlow;\n\n try {\n const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });\n\n const response = await gasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n transactionMeta: txMeta,\n });\n\n const gasFeeEstimateType = response.estimates?.type;\n\n switch (gasFeeEstimateType) {\n case GasFeeEstimateType.FeeMarket:\n return response.estimates.medium;\n case GasFeeEstimateType.Legacy:\n return {\n gasPrice: response.estimates.medium,\n };\n case GasFeeEstimateType.GasPrice:\n return { gasPrice: response.estimates.gasPrice };\n default:\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`,\n );\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? add0x(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/etherscan.ts"],"sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { ETHERSCAN_SUPPORTED_NETWORKS } from '../constants';\nimport { incomingTransactionsLogger as log } from '../logger';\n\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface EtherscanTransactionMetaBase {\n blockNumber: string;\n blockHash: string;\n confirmations: string;\n contractAddress: string;\n cumulativeGasUsed: string;\n from: string;\n gas: string;\n gasPrice: string;\n gasUsed: string;\n hash: string;\n nonce: string;\n timeStamp: string;\n to: string;\n transactionIndex: string;\n value: string;\n}\n\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface EtherscanTransactionMeta extends EtherscanTransactionMetaBase {\n functionName: string;\n input: string;\n isError: string;\n methodId: string;\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n txreceipt_status: string;\n}\n\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface EtherscanTokenTransactionMeta\n extends EtherscanTransactionMetaBase {\n tokenDecimal: string;\n tokenName: string;\n tokenSymbol: string;\n}\n\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface EtherscanTransactionResponse<\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n T extends EtherscanTransactionMetaBase,\n> {\n status: '0' | '1';\n message?: string;\n result: string | T[];\n}\n\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface EtherscanTransactionRequest {\n address: string;\n chainId: Hex;\n fromBlock?: number;\n limit?: number;\n}\n\n/**\n * Retrieves transaction data from Etherscan.\n *\n * @param request - Configuration required to fetch transactions.\n * @param request.address - Address to retrieve transactions for.\n * @param request.chainId - Current chain ID used to determine subdomain and domain.\n * @param request.fromBlock - Block number to start fetching transactions from.\n * @param request.limit - Number of transactions to retrieve.\n * @returns An Etherscan response object containing the request status and an array of token transaction data.\n */\nexport async function fetchEtherscanTransactions({\n address,\n chainId,\n fromBlock,\n limit,\n}: EtherscanTransactionRequest): Promise<\n EtherscanTransactionResponse<EtherscanTransactionMeta>\n> {\n return await fetchTransactions('txlist', {\n address,\n chainId,\n fromBlock,\n limit,\n });\n}\n\n/**\n * Retrieves token transaction data from Etherscan.\n *\n * @param request - Configuration required to fetch token transactions.\n * @param request.address - Address to retrieve token transactions for.\n * @param request.chainId - Current chain ID used to determine subdomain and domain.\n * @param request.fromBlock - Block number to start fetching token transactions from.\n * @param request.limit - Number of token transactions to retrieve.\n * @returns An Etherscan response object containing the request status and an array of token transaction data.\n */\nexport async function fetchEtherscanTokenTransactions({\n address,\n chainId,\n fromBlock,\n limit,\n}: EtherscanTransactionRequest): Promise<\n EtherscanTransactionResponse<EtherscanTokenTransactionMeta>\n> {\n return await fetchTransactions('tokentx', {\n address,\n chainId,\n fromBlock,\n limit,\n });\n}\n\n/**\n * Retrieves transaction data from Etherscan from a specific endpoint.\n *\n * @param action - The Etherscan endpoint to use.\n * @param options - Options bag.\n * @param options.address - Address to retrieve transactions for.\n * @param options.chainId - Current chain ID used to determine subdomain and domain.\n * @param options.fromBlock - Block number to start fetching transactions from.\n * @param options.limit - Number of transactions to retrieve.\n * @returns An object containing the request status and an array of transaction data.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nasync function fetchTransactions<T extends EtherscanTransactionMetaBase>(\n action: string,\n {\n address,\n chainId,\n fromBlock,\n limit,\n }: {\n address: string;\n chainId: Hex;\n fromBlock?: number;\n limit?: number;\n },\n): Promise<EtherscanTransactionResponse<T>> {\n const urlParams = {\n module: 'account',\n address,\n startBlock: fromBlock?.toString(),\n offset: limit?.toString(),\n sort: 'desc',\n };\n\n const etherscanTxUrl = getEtherscanApiUrl(chainId, {\n ...urlParams,\n action,\n });\n\n log('Sending Etherscan request', etherscanTxUrl);\n\n const response = (await handleFetch(\n etherscanTxUrl,\n )) as EtherscanTransactionResponse<T>;\n\n return response;\n}\n\n/**\n * Return a URL that can be used to fetch data from Etherscan.\n *\n * @param chainId - Current chain ID used to determine subdomain and domain.\n * @param urlParams - The parameters used to construct the URL.\n * @returns URL to access Etherscan data.\n */\nfunction getEtherscanApiUrl(\n chainId: Hex,\n urlParams: Record<string, string | undefined>,\n): string {\n const apiUrl = getEtherscanApiHost(chainId);\n let url = `${apiUrl}/api?`;\n\n for (const paramKey of Object.keys(urlParams)) {\n const value = urlParams[paramKey];\n\n if (!value) {\n continue;\n }\n\n url += `${paramKey}=${value}&`;\n }\n\n url += 'tag=latest&page=1';\n\n return url;\n}\n\n/**\n * Return the host url used to fetch data from Etherscan.\n *\n * @param chainId - Current chain ID used to determine subdomain and domain.\n * @returns host URL to access Etherscan data.\n */\nexport function getEtherscanApiHost(chainId: Hex) {\n // @ts-expect-error We account for `chainId` not being a property below\n const networkInfo = ETHERSCAN_SUPPORTED_NETWORKS[chainId];\n\n if (!networkInfo) {\n throw new Error(`Etherscan does not support chain with ID: ${chainId}`);\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `https://${networkInfo.subdomain}.${networkInfo.domain}`;\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,mBAAmB;AAmF5B,eAAsB,2BAA2B;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAEE;AACA,SAAO,MAAM,kBAAkB,UAAU;AAAA,IACvC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAYA,eAAsB,gCAAgC;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAEE;AACA,SAAO,MAAM,kBAAkB,WAAW;AAAA,IACxC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAeA,eAAe,kBACb,QACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAM0C;AAC1C,QAAM,YAAY;AAAA,IAChB,QAAQ;AAAA,IACR;AAAA,IACA,YAAY,WAAW,SAAS;AAAA,IAChC,QAAQ,OAAO,SAAS;AAAA,IACxB,MAAM;AAAA,EACR;AAEA,QAAM,iBAAiB,mBAAmB,SAAS;AAAA,IACjD,GAAG;AAAA,IACH;AAAA,EACF,CAAC;AAED,6BAAI,6BAA6B,cAAc;AAE/C,QAAM,WAAY,MAAM;AAAA,IACtB;AAAA,EACF;AAEA,SAAO;AACT;AASA,SAAS,mBACP,SACA,WACQ;AACR,QAAM,SAAS,oBAAoB,OAAO;AAC1C,MAAI,MAAM,GAAG,MAAM;AAEnB,aAAW,YAAY,OAAO,KAAK,SAAS,GAAG;AAC7C,UAAM,QAAQ,UAAU,QAAQ;AAEhC,QAAI,CAAC,OAAO;AACV;AAAA,IACF;AAEA,WAAO,GAAG,QAAQ,IAAI,KAAK;AAAA,EAC7B;AAEA,SAAO;AAEP,SAAO;AACT;AAQO,SAAS,oBAAoB,SAAc;AAEhD,QAAM,cAAc,6BAA6B,OAAO;AAExD,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI,MAAM,6CAA6C,OAAO,EAAE;AAAA,EACxE;AAIA,SAAO,WAAW,YAAY,SAAS,IAAI,YAAY,MAAM;AAC/D;","names":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
fetchEtherscanTokenTransactions,
|
|
3
3
|
fetchEtherscanTransactions
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-EGQCE3FK.mjs";
|
|
5
5
|
import {
|
|
6
6
|
ETHERSCAN_SUPPORTED_NETWORKS
|
|
7
7
|
} from "./chunk-O6ZZVIFH.mjs";
|
|
@@ -27,6 +27,8 @@ var EtherscanRemoteTransactionSource = class {
|
|
|
27
27
|
includeTokenTransfers
|
|
28
28
|
} = {}) {
|
|
29
29
|
__privateAdd(this, _releaseLockAfterInterval);
|
|
30
|
+
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
31
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
30
32
|
__privateAdd(this, _getResponseTransactions);
|
|
31
33
|
__privateAdd(this, _normalizeTransaction);
|
|
32
34
|
__privateAdd(this, _normalizeTokenTransaction);
|
|
@@ -167,4 +169,4 @@ normalizeTransactionBase_fn = function(txMeta, currentChainId) {
|
|
|
167
169
|
export {
|
|
168
170
|
EtherscanRemoteTransactionSource
|
|
169
171
|
};
|
|
170
|
-
//# sourceMappingURL=chunk-
|
|
172
|
+
//# sourceMappingURL=chunk-EKJXGERC.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/helpers/EtherscanRemoteTransactionSource.ts"],"sourcesContent":["import { BNToHex } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport BN from 'bn.js';\nimport { v1 as random } from 'uuid';\n\nimport { ETHERSCAN_SUPPORTED_NETWORKS } from '../constants';\nimport { incomingTransactionsLogger as log } from '../logger';\nimport type {\n RemoteTransactionSource,\n RemoteTransactionSourceRequest,\n TransactionMeta,\n} from '../types';\nimport { TransactionStatus, TransactionType } from '../types';\nimport {\n fetchEtherscanTokenTransactions,\n fetchEtherscanTransactions,\n} from '../utils/etherscan';\nimport type {\n EtherscanTokenTransactionMeta,\n EtherscanTransactionMeta,\n EtherscanTransactionMetaBase,\n EtherscanTransactionRequest,\n EtherscanTransactionResponse,\n} from '../utils/etherscan';\n\nconst ETHERSCAN_RATE_LIMIT_INTERVAL = 5000;\n/**\n * A RemoteTransactionSource that fetches transaction data from Etherscan.\n */\nexport class EtherscanRemoteTransactionSource\n implements RemoteTransactionSource\n{\n #includeTokenTransfers: boolean;\n\n #isTokenRequestPending: boolean;\n\n #mutex = new Mutex();\n\n constructor({\n includeTokenTransfers,\n }: { includeTokenTransfers?: boolean } = {}) {\n this.#includeTokenTransfers = includeTokenTransfers ?? true;\n this.#isTokenRequestPending = false;\n }\n\n isSupportedNetwork(chainId: Hex): boolean {\n return Object.keys(ETHERSCAN_SUPPORTED_NETWORKS).includes(chainId);\n }\n\n getLastBlockVariations(): string[] {\n return [this.#isTokenRequestPending ? 'token' : 'normal'];\n }\n\n async fetchTransactions(\n request: RemoteTransactionSourceRequest,\n ): Promise<TransactionMeta[]> {\n const releaseLock = await this.#mutex.acquire();\n const acquiredTime = Date.now();\n\n const etherscanRequest: EtherscanTransactionRequest = {\n ...request,\n chainId: request.currentChainId,\n };\n\n try {\n const transactions = this.#isTokenRequestPending\n ? await this.#fetchTokenTransactions(request, etherscanRequest)\n : await this.#fetchNormalTransactions(request, etherscanRequest);\n\n if (this.#includeTokenTransfers) {\n this.#isTokenRequestPending = !this.#isTokenRequestPending;\n }\n\n return transactions;\n } finally {\n this.#releaseLockAfterInterval(acquiredTime, releaseLock);\n }\n }\n\n #releaseLockAfterInterval(acquireTime: number, releaseLock: () => void) {\n const elapsedTime = Date.now() - acquireTime;\n const remainingTime = Math.max(\n 0,\n ETHERSCAN_RATE_LIMIT_INTERVAL - elapsedTime,\n );\n // Wait for the remaining time if it hasn't been 5 seconds yet\n if (remainingTime > 0) {\n setTimeout(releaseLock, remainingTime);\n } else {\n releaseLock();\n }\n }\n\n #fetchNormalTransactions = async (\n request: RemoteTransactionSourceRequest,\n etherscanRequest: EtherscanTransactionRequest,\n ) => {\n const { currentChainId } = request;\n\n const etherscanTransactions = await fetchEtherscanTransactions(\n etherscanRequest,\n );\n\n return this.#getResponseTransactions(etherscanTransactions).map((tx) =>\n this.#normalizeTransaction(tx, currentChainId),\n );\n };\n\n #fetchTokenTransactions = async (\n request: RemoteTransactionSourceRequest,\n etherscanRequest: EtherscanTransactionRequest,\n ) => {\n const { currentChainId } = request;\n\n const etherscanTransactions = await fetchEtherscanTokenTransactions(\n etherscanRequest,\n );\n\n return this.#getResponseTransactions(etherscanTransactions).map((tx) =>\n this.#normalizeTokenTransaction(tx, currentChainId),\n );\n };\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n #getResponseTransactions<T extends EtherscanTransactionMetaBase>(\n response: EtherscanTransactionResponse<T>,\n ): T[] {\n let result = response.result as T[];\n\n if (response.status === '0') {\n result = [];\n\n if (response.result.length) {\n log('Ignored Etherscan request error', {\n message: response.result,\n type: this.#isTokenRequestPending ? 'token' : 'normal',\n });\n }\n }\n\n return result;\n }\n\n #normalizeTransaction(\n txMeta: EtherscanTransactionMeta,\n currentChainId: Hex,\n ): TransactionMeta {\n const base = this.#normalizeTransactionBase(txMeta, currentChainId);\n\n return {\n ...base,\n txParams: {\n ...base.txParams,\n data: txMeta.input,\n },\n ...(txMeta.isError === '0'\n ? { status: TransactionStatus.confirmed }\n : {\n error: new Error('Transaction failed'),\n status: TransactionStatus.failed,\n }),\n };\n }\n\n #normalizeTokenTransaction(\n txMeta: EtherscanTokenTransactionMeta,\n currentChainId: Hex,\n ): TransactionMeta {\n const base = this.#normalizeTransactionBase(txMeta, currentChainId);\n\n return {\n ...base,\n isTransfer: true,\n transferInformation: {\n contractAddress: txMeta.contractAddress,\n decimals: Number(txMeta.tokenDecimal),\n symbol: txMeta.tokenSymbol,\n },\n };\n }\n\n #normalizeTransactionBase(\n txMeta: EtherscanTransactionMetaBase,\n currentChainId: Hex,\n ): TransactionMeta {\n const time = parseInt(txMeta.timeStamp, 10) * 1000;\n\n return {\n blockNumber: txMeta.blockNumber,\n chainId: currentChainId,\n hash: txMeta.hash,\n id: random({ msecs: time }),\n status: TransactionStatus.confirmed,\n time,\n txParams: {\n chainId: currentChainId,\n from: txMeta.from,\n gas: BNToHex(new BN(txMeta.gas)),\n gasPrice: BNToHex(new BN(txMeta.gasPrice)),\n gasUsed: BNToHex(new BN(txMeta.gasUsed)),\n nonce: BNToHex(new BN(txMeta.nonce)),\n to: txMeta.to,\n value: BNToHex(new BN(txMeta.value)),\n },\n type: TransactionType.incoming,\n verifiedOnBlockchain: false,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,eAAe;AAExB,SAAS,aAAa;AACtB,OAAO,QAAQ;AACf,SAAS,MAAM,cAAc;AAsB7B,IAAM,gCAAgC;AA1BtC;AA8BO,IAAM,mCAAN,MAEP;AAAA,EAOE,YAAY;AAAA,IACV;AAAA,EACF,IAAyC,CAAC,GAAG;AAuC7C;AA8CA;AAAA;AAAA;AAmBA;AAqBA;AAiBA;AAtJA;AAEA;AAEA,+BAAS,IAAI,MAAM;AAyDnB,iDAA2B,OACzB,SACA,qBACG;AACH,YAAM,EAAE,eAAe,IAAI;AAE3B,YAAM,wBAAwB,MAAM;AAAA,QAClC;AAAA,MACF;AAEA,aAAO,sBAAK,sDAAL,WAA8B,uBAAuB;AAAA,QAAI,CAAC,OAC/D,sBAAK,gDAAL,WAA2B,IAAI;AAAA,MACjC;AAAA,IACF;AAEA,gDAA0B,OACxB,SACA,qBACG;AACH,YAAM,EAAE,eAAe,IAAI;AAE3B,YAAM,wBAAwB,MAAM;AAAA,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