@metamask/transaction-controller 17.0.0 → 18.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -1
- package/dist/TransactionController.d.ts +52 -13
- package/dist/TransactionController.d.ts.map +1 -1
- package/dist/TransactionController.js +242 -106
- package/dist/TransactionController.js.map +1 -1
- package/dist/helpers/PendingTransactionTracker.d.ts +1 -1
- package/dist/helpers/PendingTransactionTracker.d.ts.map +1 -1
- package/dist/helpers/PendingTransactionTracker.js.map +1 -1
- package/dist/types.d.ts +8 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/swaps.d.ts.map +1 -1
- package/dist/utils/swaps.js +13 -0
- package/dist/utils/swaps.js.map +1 -1
- package/dist/utils/utils.d.ts +10 -2
- package/dist/utils/utils.d.ts.map +1 -1
- package/dist/utils/utils.js +28 -3
- package/dist/utils/utils.js.map +1 -1
- package/package.json +11 -11
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import type EthQuery from '@metamask/eth-query';
|
|
3
3
|
import type { BlockTracker } from '@metamask/network-controller';
|
|
4
4
|
import EventEmitter from 'events';
|
|
5
|
-
import type NonceTracker from 'nonce-tracker';
|
|
5
|
+
import type { NonceTracker } from 'nonce-tracker';
|
|
6
6
|
import type { TransactionState } from '../TransactionController';
|
|
7
7
|
import type { TransactionMeta } from '../types';
|
|
8
8
|
declare type Events = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PendingTransactionTracker.d.ts","sourceRoot":"","sources":["../../src/helpers/PendingTransactionTracker.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAEjE,OAAO,YAAY,MAAM,QAAQ,CAAC;AAClC,OAAO,KAAK,YAAY,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,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EAAC,uBAAA,IAAI,8CAAa,MAAjB,IAAI,CAAe,EAAE,uBAAuB,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAC7E,CAAC;kGAGC,SAAiB,EACjB,yBAAkC;;QAElC,OAAO,MAAM,IAAA,wBAAK,EAAC,uBAAA,IAAI,8CAAa,MAAjB,IAAI,CAAe,EAAE,gBAAgB,EAAE;YACxD,SAAS;YACT,yBAAyB;SAC1B,CAAC,CAAC;IACL,CAAC;0HAEiC,OAAe;;QAC/C,OAAO,MAAM,IAAA,wBAAK,EAAC,uBAAA,IAAI,8CAAa,MAAjB,IAAI,CAAe,EAAE,qBAAqB,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAC5E,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type { BlockTracker } from '@metamask/network-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport EventEmitter from 'events';\nimport type NonceTracker from 'nonce-tracker';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionState } from '../TransactionController';\nimport type { TransactionMeta, TransactionReceipt } from '../types';\nimport { TransactionStatus } from '../types';\n\n/**\n * We wait this many blocks before emitting a 'transaction-dropped' event\n * This is because we could be talking to a node that is out of sync\n */\nconst DROPPED_BLOCK_COUNT = 3;\n\nconst MAX_RETRY_BLOCK_DISTANCE = 50;\n\nconst KNOWN_TRANSACTION_ERRORS = [\n 'replacement transaction underpriced',\n 'known transaction',\n 'gas price too low to replace',\n 'transaction with the same hash was already imported',\n 'gateway timeout',\n 'nonce too low',\n];\n\nconst log = createModuleLogger(projectLogger, 'pending-transactions');\n\ntype SuccessfulTransactionReceipt = TransactionReceipt & {\n blockNumber: string;\n blockHash: string;\n};\n\ntype Events = {\n 'transaction-confirmed': [txMeta: TransactionMeta];\n 'transaction-dropped': [txMeta: TransactionMeta];\n 'transaction-failed': [txMeta: TransactionMeta, error: Error];\n 'transaction-updated': [txMeta: TransactionMeta, note: 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 PendingTransactionTrackerEventEmitter extends EventEmitter {\n on<T extends keyof Events>(\n eventName: T,\n listener: (...args: Events[T]) => void,\n ): this;\n\n emit<T extends keyof Events>(eventName: T, ...args: Events[T]): boolean;\n}\n\nexport class PendingTransactionTracker {\n hub: PendingTransactionTrackerEventEmitter;\n\n #approveTransaction: (transactionId: string) => Promise<void>;\n\n #blockTracker: BlockTracker;\n\n #droppedBlockCountByHash: Map<string, number>;\n\n #getChainId: () => string;\n\n #getEthQuery: () => EthQuery;\n\n #getTransactions: () => TransactionMeta[];\n\n #isResubmitEnabled: boolean;\n\n #listener: any;\n\n #nonceTracker: NonceTracker;\n\n #onStateChange: (listener: (state: TransactionState) => void) => void;\n\n #publishTransaction: (rawTx: string) => Promise<string>;\n\n #running: boolean;\n\n #beforeCheckPendingTransaction: (transactionMeta: TransactionMeta) => boolean;\n\n #beforePublish: (transactionMeta: TransactionMeta) => boolean;\n\n constructor({\n approveTransaction,\n blockTracker,\n getChainId,\n getEthQuery,\n getTransactions,\n isResubmitEnabled,\n nonceTracker,\n onStateChange,\n publishTransaction,\n hooks,\n }: {\n approveTransaction: (transactionId: string) => Promise<void>;\n blockTracker: BlockTracker;\n getChainId: () => string;\n getEthQuery: () => EthQuery;\n getTransactions: () => TransactionMeta[];\n isResubmitEnabled?: boolean;\n nonceTracker: NonceTracker;\n onStateChange: (listener: (state: TransactionState) => void) => void;\n publishTransaction: (rawTx: string) => Promise<string>;\n hooks?: {\n beforeCheckPendingTransaction?: (\n transactionMeta: TransactionMeta,\n ) => boolean;\n beforePublish?: (transactionMeta: TransactionMeta) => boolean;\n };\n }) {\n this.hub = new EventEmitter() as PendingTransactionTrackerEventEmitter;\n\n this.#approveTransaction = approveTransaction;\n this.#blockTracker = blockTracker;\n this.#droppedBlockCountByHash = new Map();\n this.#getChainId = getChainId;\n this.#getEthQuery = getEthQuery;\n this.#getTransactions = getTransactions;\n this.#isResubmitEnabled = isResubmitEnabled ?? true;\n this.#listener = this.#onLatestBlock.bind(this);\n this.#nonceTracker = nonceTracker;\n this.#onStateChange = onStateChange;\n this.#publishTransaction = publishTransaction;\n this.#running = false;\n this.#beforePublish = hooks?.beforePublish ?? (() => true);\n this.#beforeCheckPendingTransaction =\n hooks?.beforeCheckPendingTransaction ?? (() => true);\n\n this.#onStateChange((state) => {\n const pendingTransactions = this.#getPendingTransactions(\n state.transactions,\n );\n\n if (pendingTransactions.length) {\n this.#start();\n } else {\n this.#stop();\n }\n });\n }\n\n #start() {\n if (this.#running) {\n return;\n }\n\n this.#blockTracker.on('latest', this.#listener);\n this.#running = true;\n\n log('Started polling');\n }\n\n #stop() {\n if (!this.#running) {\n return;\n }\n\n this.#blockTracker.removeListener('latest', this.#listener);\n this.#running = false;\n\n log('Stopped polling');\n }\n\n async #onLatestBlock(latestBlockNumber: string) {\n const nonceGlobalLock = await this.#nonceTracker.getGlobalLock();\n\n try {\n await this.#checkTransactions();\n } catch (error) {\n /* istanbul ignore next */\n log('Failed to check transactions', error);\n } finally {\n nonceGlobalLock.releaseLock();\n }\n\n try {\n await this.#resubmitTransactions(latestBlockNumber);\n } catch (error) {\n /* istanbul ignore next */\n log('Failed to resubmit transactions', error);\n }\n }\n\n async #checkTransactions() {\n log('Checking transactions');\n\n const pendingTransactions = this.#getPendingTransactions();\n\n if (!pendingTransactions.length) {\n log('No pending transactions to check');\n return;\n }\n\n log('Found pending transactions to check', {\n count: pendingTransactions.length,\n ids: pendingTransactions.map((tx) => tx.id),\n });\n\n await Promise.all(\n pendingTransactions.map((tx) => this.#checkTransaction(tx)),\n );\n }\n\n async #resubmitTransactions(latestBlockNumber: string) {\n if (!this.#isResubmitEnabled || !this.#running) {\n return;\n }\n\n log('Resubmitting transactions');\n\n const pendingTransactions = this.#getPendingTransactions();\n\n if (!pendingTransactions.length) {\n log('No pending transactions to resubmit');\n return;\n }\n\n log('Found pending transactions to resubmit', {\n count: pendingTransactions.length,\n ids: pendingTransactions.map((tx) => tx.id),\n });\n\n for (const txMeta of pendingTransactions) {\n try {\n await this.#resubmitTransaction(txMeta, latestBlockNumber);\n } catch (error: any) {\n /* istanbul ignore next */\n const errorMessage =\n error.value?.message?.toLowerCase() || error.message.toLowerCase();\n\n if (this.#isKnownTransactionError(errorMessage)) {\n log('Ignoring known transaction error', errorMessage);\n return;\n }\n\n this.#warnTransaction(\n txMeta,\n error.message,\n 'There was an error when resubmitting this transaction.',\n );\n }\n }\n }\n\n #isKnownTransactionError(errorMessage: string) {\n return KNOWN_TRANSACTION_ERRORS.some((knownError) =>\n errorMessage.includes(knownError),\n );\n }\n\n async #resubmitTransaction(\n txMeta: TransactionMeta,\n latestBlockNumber: string,\n ) {\n if (!this.#isResubmitDue(txMeta, latestBlockNumber)) {\n return;\n }\n\n log('Resubmitting transaction', txMeta.id);\n\n const { rawTx } = txMeta;\n\n if (!this.#beforePublish(txMeta)) {\n return;\n }\n\n if (!rawTx?.length) {\n log('Approving transaction as no raw value');\n await this.#approveTransaction(txMeta.id);\n return;\n }\n\n await this.#publishTransaction(rawTx);\n\n txMeta.retryCount = (txMeta.retryCount ?? 0) + 1;\n\n this.#updateTransaction(\n txMeta,\n 'PendingTransactionTracker:transaction-retry - Retry count increased',\n );\n }\n\n #isResubmitDue(txMeta: TransactionMeta, latestBlockNumber: string): boolean {\n if (!txMeta.firstRetryBlockNumber) {\n txMeta.firstRetryBlockNumber = latestBlockNumber;\n\n this.#updateTransaction(\n txMeta,\n 'PendingTransactionTracker:#isResubmitDue - First retry block number set',\n );\n }\n\n const firstRetryBlockNumber =\n txMeta.firstRetryBlockNumber || latestBlockNumber;\n\n const blocksSinceFirstRetry =\n Number.parseInt(latestBlockNumber, 16) -\n Number.parseInt(firstRetryBlockNumber, 16);\n\n const retryCount = txMeta.retryCount || 0;\n\n // Exponential backoff to limit retries at publishing\n // Capped at ~15 minutes between retries\n const requiredBlocksSinceFirstRetry = Math.min(\n MAX_RETRY_BLOCK_DISTANCE,\n Math.pow(2, retryCount),\n );\n\n return blocksSinceFirstRetry >= requiredBlocksSinceFirstRetry;\n }\n\n async #checkTransaction(txMeta: TransactionMeta) {\n const { hash, id } = txMeta;\n\n if (!hash && this.#beforeCheckPendingTransaction(txMeta)) {\n const error = new Error(\n 'We had an error while submitting this transaction, please try again.',\n );\n\n error.name = 'NoTxHashError';\n\n this.#failTransaction(txMeta, error);\n\n return;\n }\n\n if (this.#isNonceTaken(txMeta)) {\n log('Nonce already taken', id);\n this.#dropTransaction(txMeta);\n return;\n }\n\n try {\n const receipt = await this.#getTransactionReceipt(hash);\n const isSuccess = receipt?.status === '0x1';\n\n if (receipt && !isSuccess) {\n log('Transaction receipt has failed status');\n\n this.#failTransaction(\n txMeta,\n new Error('Transaction dropped or replaced'),\n );\n\n return;\n }\n\n const { blockNumber, blockHash } = receipt || {};\n\n if (isSuccess && blockNumber && blockHash) {\n await this.#onTransactionConfirmed(txMeta, {\n ...receipt,\n blockNumber,\n blockHash,\n });\n\n return;\n }\n } catch (error: any) {\n log('Failed to check transaction', id, error);\n\n this.#warnTransaction(\n txMeta,\n error.message,\n 'There was a problem loading this transaction.',\n );\n\n return;\n }\n\n if (await this.#isTransactionDropped(txMeta)) {\n this.#dropTransaction(txMeta);\n }\n }\n\n async #onTransactionConfirmed(\n txMeta: TransactionMeta,\n receipt: SuccessfulTransactionReceipt,\n ) {\n const { id } = txMeta;\n const { blockHash } = receipt;\n\n log('Transaction confirmed', id);\n\n const { baseFeePerGas, timestamp: blockTimestamp } =\n await this.#getBlockByHash(blockHash, false);\n\n txMeta.baseFeePerGas = baseFeePerGas;\n txMeta.blockTimestamp = blockTimestamp;\n txMeta.status = TransactionStatus.confirmed;\n txMeta.txParams.gasUsed = receipt.gasUsed;\n txMeta.txReceipt = receipt;\n txMeta.verifiedOnBlockchain = true;\n\n this.#updateTransaction(\n txMeta,\n 'PendingTransactionTracker:#onTransactionConfirmed - Transaction confirmed',\n );\n\n this.hub.emit('transaction-confirmed', txMeta);\n }\n\n async #isTransactionDropped(txMeta: TransactionMeta) {\n const {\n hash,\n id,\n txParams: { nonce, from },\n } = txMeta;\n\n /* istanbul ignore next */\n if (!nonce || !hash) {\n return false;\n }\n\n const networkNextNonceHex = await this.#getNetworkTransactionCount(from);\n const networkNextNonceNumber = parseInt(networkNextNonceHex, 16);\n const nonceNumber = parseInt(nonce, 16);\n\n if (nonceNumber >= networkNextNonceNumber) {\n return false;\n }\n\n let droppedBlockCount = this.#droppedBlockCountByHash.get(hash);\n\n if (droppedBlockCount === undefined) {\n droppedBlockCount = 0;\n this.#droppedBlockCountByHash.set(hash, droppedBlockCount);\n }\n\n if (droppedBlockCount < DROPPED_BLOCK_COUNT) {\n log('Incrementing dropped block count', { id, droppedBlockCount });\n this.#droppedBlockCountByHash.set(hash, droppedBlockCount + 1);\n return false;\n }\n\n log('Hit dropped block count', id);\n\n this.#droppedBlockCountByHash.delete(hash);\n return true;\n }\n\n #isNonceTaken(txMeta: TransactionMeta): boolean {\n const { id, txParams } = txMeta;\n\n return this.#getTransactions().some(\n (tx) =>\n tx.id !== id &&\n tx.txParams.from === txParams.from &&\n tx.status === TransactionStatus.confirmed &&\n tx.txParams.nonce === txParams.nonce,\n );\n }\n\n #getPendingTransactions(transactions?: TransactionMeta[]): TransactionMeta[] {\n const currentChainId = this.#getChainId();\n\n return (transactions ?? this.#getTransactions()).filter(\n (tx) =>\n tx.status === TransactionStatus.submitted &&\n tx.chainId === currentChainId &&\n !tx.verifiedOnBlockchain,\n );\n }\n\n #warnTransaction(txMeta: TransactionMeta, error: string, message: string) {\n txMeta.warning = {\n error,\n message,\n };\n\n this.#updateTransaction(\n txMeta,\n 'PendingTransactionTracker:#warnTransaction - Warning added',\n );\n }\n\n #failTransaction(txMeta: TransactionMeta, error: Error) {\n log('Transaction failed', txMeta.id, error);\n this.hub.emit('transaction-failed', txMeta, error);\n }\n\n #dropTransaction(txMeta: TransactionMeta) {\n log('Transaction dropped', txMeta.id);\n this.hub.emit('transaction-dropped', txMeta);\n }\n\n #updateTransaction(txMeta: TransactionMeta, note: string) {\n this.hub.emit('transaction-updated', txMeta, note);\n }\n\n async #getTransactionReceipt(\n txHash?: string,\n ): Promise<TransactionReceipt | undefined> {\n return await query(this.#getEthQuery(), 'getTransactionReceipt', [txHash]);\n }\n\n async #getBlockByHash(\n blockHash: string,\n includeTransactionDetails: boolean,\n ): Promise<any> {\n return await query(this.#getEthQuery(), 'getBlockByHash', [\n blockHash,\n includeTransactionDetails,\n ]);\n }\n\n async #getNetworkTransactionCount(address: string): Promise<string> {\n return await query(this.#getEthQuery(), 'getTransactionCount', [address]);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"PendingTransactionTracker.js","sourceRoot":"","sources":["../../src/helpers/PendingTransactionTracker.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iEAAmD;AAGnD,2CAAqD;AACrD,oDAAkC;AAGlC,sCAA0C;AAG1C,oCAA6C;AAE7C;;;GAGG;AACH,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAE9B,MAAM,wBAAwB,GAAG,EAAE,CAAC;AAEpC,MAAM,wBAAwB,GAAG;IAC/B,qCAAqC;IACrC,mBAAmB;IACnB,8BAA8B;IAC9B,qDAAqD;IACrD,iBAAiB;IACjB,eAAe;CAChB,CAAC;AAEF,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,sBAAsB,CAAC,CAAC;AA0BtE,MAAa,yBAAyB;IA+BpC,YAAY,EACV,kBAAkB,EAClB,YAAY,EACZ,UAAU,EACV,WAAW,EACX,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,aAAa,EACb,kBAAkB,EAClB,KAAK,GAiBN;;;QAvDD,gEAA8D;QAE9D,0DAA4B;QAE5B,qEAA8C;QAE9C,wDAA0B;QAE1B,yDAA6B;QAE7B,6DAA0C;QAE1C,+DAA4B;QAE5B,sDAAe;QAEf,0DAA4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AC1B,CAAC,CAAC;IACL,CAAC;0HAEiC,OAAe;;QAC/C,OAAO,MAAM,IAAA,wBAAK,EAAC,uBAAA,IAAI,8CAAa,MAAjB,IAAI,CAAe,EAAE,qBAAqB,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAC5E,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type { BlockTracker } from '@metamask/network-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport EventEmitter from 'events';\nimport type { NonceTracker } from 'nonce-tracker';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionState } from '../TransactionController';\nimport type { TransactionMeta, TransactionReceipt } from '../types';\nimport { TransactionStatus } from '../types';\n\n/**\n * We wait this many blocks before emitting a 'transaction-dropped' event\n * This is because we could be talking to a node that is out of sync\n */\nconst DROPPED_BLOCK_COUNT = 3;\n\nconst MAX_RETRY_BLOCK_DISTANCE = 50;\n\nconst KNOWN_TRANSACTION_ERRORS = [\n 'replacement transaction underpriced',\n 'known transaction',\n 'gas price too low to replace',\n 'transaction with the same hash was already imported',\n 'gateway timeout',\n 'nonce too low',\n];\n\nconst log = createModuleLogger(projectLogger, 'pending-transactions');\n\ntype SuccessfulTransactionReceipt = TransactionReceipt & {\n blockNumber: string;\n blockHash: string;\n};\n\ntype Events = {\n 'transaction-confirmed': [txMeta: TransactionMeta];\n 'transaction-dropped': [txMeta: TransactionMeta];\n 'transaction-failed': [txMeta: TransactionMeta, error: Error];\n 'transaction-updated': [txMeta: TransactionMeta, note: 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 PendingTransactionTrackerEventEmitter extends EventEmitter {\n on<T extends keyof Events>(\n eventName: T,\n listener: (...args: Events[T]) => void,\n ): this;\n\n emit<T extends keyof Events>(eventName: T, ...args: Events[T]): boolean;\n}\n\nexport class PendingTransactionTracker {\n hub: PendingTransactionTrackerEventEmitter;\n\n #approveTransaction: (transactionId: string) => Promise<void>;\n\n #blockTracker: BlockTracker;\n\n #droppedBlockCountByHash: Map<string, number>;\n\n #getChainId: () => string;\n\n #getEthQuery: () => EthQuery;\n\n #getTransactions: () => TransactionMeta[];\n\n #isResubmitEnabled: boolean;\n\n #listener: any;\n\n #nonceTracker: NonceTracker;\n\n #onStateChange: (listener: (state: TransactionState) => void) => void;\n\n #publishTransaction: (rawTx: string) => Promise<string>;\n\n #running: boolean;\n\n #beforeCheckPendingTransaction: (transactionMeta: TransactionMeta) => boolean;\n\n #beforePublish: (transactionMeta: TransactionMeta) => boolean;\n\n constructor({\n approveTransaction,\n blockTracker,\n getChainId,\n getEthQuery,\n getTransactions,\n isResubmitEnabled,\n nonceTracker,\n onStateChange,\n publishTransaction,\n hooks,\n }: {\n approveTransaction: (transactionId: string) => Promise<void>;\n blockTracker: BlockTracker;\n getChainId: () => string;\n getEthQuery: () => EthQuery;\n getTransactions: () => TransactionMeta[];\n isResubmitEnabled?: boolean;\n nonceTracker: NonceTracker;\n onStateChange: (listener: (state: TransactionState) => void) => void;\n publishTransaction: (rawTx: string) => Promise<string>;\n hooks?: {\n beforeCheckPendingTransaction?: (\n transactionMeta: TransactionMeta,\n ) => boolean;\n beforePublish?: (transactionMeta: TransactionMeta) => boolean;\n };\n }) {\n this.hub = new EventEmitter() as PendingTransactionTrackerEventEmitter;\n\n this.#approveTransaction = approveTransaction;\n this.#blockTracker = blockTracker;\n this.#droppedBlockCountByHash = new Map();\n this.#getChainId = getChainId;\n this.#getEthQuery = getEthQuery;\n this.#getTransactions = getTransactions;\n this.#isResubmitEnabled = isResubmitEnabled ?? true;\n this.#listener = this.#onLatestBlock.bind(this);\n this.#nonceTracker = nonceTracker;\n this.#onStateChange = onStateChange;\n this.#publishTransaction = publishTransaction;\n this.#running = false;\n this.#beforePublish = hooks?.beforePublish ?? (() => true);\n this.#beforeCheckPendingTransaction =\n hooks?.beforeCheckPendingTransaction ?? (() => true);\n\n this.#onStateChange((state) => {\n const pendingTransactions = this.#getPendingTransactions(\n state.transactions,\n );\n\n if (pendingTransactions.length) {\n this.#start();\n } else {\n this.#stop();\n }\n });\n }\n\n #start() {\n if (this.#running) {\n return;\n }\n\n this.#blockTracker.on('latest', this.#listener);\n this.#running = true;\n\n log('Started polling');\n }\n\n #stop() {\n if (!this.#running) {\n return;\n }\n\n this.#blockTracker.removeListener('latest', this.#listener);\n this.#running = false;\n\n log('Stopped polling');\n }\n\n async #onLatestBlock(latestBlockNumber: string) {\n const nonceGlobalLock = await this.#nonceTracker.getGlobalLock();\n\n try {\n await this.#checkTransactions();\n } catch (error) {\n /* istanbul ignore next */\n log('Failed to check transactions', error);\n } finally {\n nonceGlobalLock.releaseLock();\n }\n\n try {\n await this.#resubmitTransactions(latestBlockNumber);\n } catch (error) {\n /* istanbul ignore next */\n log('Failed to resubmit transactions', error);\n }\n }\n\n async #checkTransactions() {\n log('Checking transactions');\n\n const pendingTransactions = this.#getPendingTransactions();\n\n if (!pendingTransactions.length) {\n log('No pending transactions to check');\n return;\n }\n\n log('Found pending transactions to check', {\n count: pendingTransactions.length,\n ids: pendingTransactions.map((tx) => tx.id),\n });\n\n await Promise.all(\n pendingTransactions.map((tx) => this.#checkTransaction(tx)),\n );\n }\n\n async #resubmitTransactions(latestBlockNumber: string) {\n if (!this.#isResubmitEnabled || !this.#running) {\n return;\n }\n\n log('Resubmitting transactions');\n\n const pendingTransactions = this.#getPendingTransactions();\n\n if (!pendingTransactions.length) {\n log('No pending transactions to resubmit');\n return;\n }\n\n log('Found pending transactions to resubmit', {\n count: pendingTransactions.length,\n ids: pendingTransactions.map((tx) => tx.id),\n });\n\n for (const txMeta of pendingTransactions) {\n try {\n await this.#resubmitTransaction(txMeta, latestBlockNumber);\n } catch (error: any) {\n /* istanbul ignore next */\n const errorMessage =\n error.value?.message?.toLowerCase() || error.message.toLowerCase();\n\n if (this.#isKnownTransactionError(errorMessage)) {\n log('Ignoring known transaction error', errorMessage);\n return;\n }\n\n this.#warnTransaction(\n txMeta,\n error.message,\n 'There was an error when resubmitting this transaction.',\n );\n }\n }\n }\n\n #isKnownTransactionError(errorMessage: string) {\n return KNOWN_TRANSACTION_ERRORS.some((knownError) =>\n errorMessage.includes(knownError),\n );\n }\n\n async #resubmitTransaction(\n txMeta: TransactionMeta,\n latestBlockNumber: string,\n ) {\n if (!this.#isResubmitDue(txMeta, latestBlockNumber)) {\n return;\n }\n\n log('Resubmitting transaction', txMeta.id);\n\n const { rawTx } = txMeta;\n\n if (!this.#beforePublish(txMeta)) {\n return;\n }\n\n if (!rawTx?.length) {\n log('Approving transaction as no raw value');\n await this.#approveTransaction(txMeta.id);\n return;\n }\n\n await this.#publishTransaction(rawTx);\n\n txMeta.retryCount = (txMeta.retryCount ?? 0) + 1;\n\n this.#updateTransaction(\n txMeta,\n 'PendingTransactionTracker:transaction-retry - Retry count increased',\n );\n }\n\n #isResubmitDue(txMeta: TransactionMeta, latestBlockNumber: string): boolean {\n if (!txMeta.firstRetryBlockNumber) {\n txMeta.firstRetryBlockNumber = latestBlockNumber;\n\n this.#updateTransaction(\n txMeta,\n 'PendingTransactionTracker:#isResubmitDue - First retry block number set',\n );\n }\n\n const firstRetryBlockNumber =\n txMeta.firstRetryBlockNumber || latestBlockNumber;\n\n const blocksSinceFirstRetry =\n Number.parseInt(latestBlockNumber, 16) -\n Number.parseInt(firstRetryBlockNumber, 16);\n\n const retryCount = txMeta.retryCount || 0;\n\n // Exponential backoff to limit retries at publishing\n // Capped at ~15 minutes between retries\n const requiredBlocksSinceFirstRetry = Math.min(\n MAX_RETRY_BLOCK_DISTANCE,\n Math.pow(2, retryCount),\n );\n\n return blocksSinceFirstRetry >= requiredBlocksSinceFirstRetry;\n }\n\n async #checkTransaction(txMeta: TransactionMeta) {\n const { hash, id } = txMeta;\n\n if (!hash && this.#beforeCheckPendingTransaction(txMeta)) {\n const error = new Error(\n 'We had an error while submitting this transaction, please try again.',\n );\n\n error.name = 'NoTxHashError';\n\n this.#failTransaction(txMeta, error);\n\n return;\n }\n\n if (this.#isNonceTaken(txMeta)) {\n log('Nonce already taken', id);\n this.#dropTransaction(txMeta);\n return;\n }\n\n try {\n const receipt = await this.#getTransactionReceipt(hash);\n const isSuccess = receipt?.status === '0x1';\n\n if (receipt && !isSuccess) {\n log('Transaction receipt has failed status');\n\n this.#failTransaction(\n txMeta,\n new Error('Transaction dropped or replaced'),\n );\n\n return;\n }\n\n const { blockNumber, blockHash } = receipt || {};\n\n if (isSuccess && blockNumber && blockHash) {\n await this.#onTransactionConfirmed(txMeta, {\n ...receipt,\n blockNumber,\n blockHash,\n });\n\n return;\n }\n } catch (error: any) {\n log('Failed to check transaction', id, error);\n\n this.#warnTransaction(\n txMeta,\n error.message,\n 'There was a problem loading this transaction.',\n );\n\n return;\n }\n\n if (await this.#isTransactionDropped(txMeta)) {\n this.#dropTransaction(txMeta);\n }\n }\n\n async #onTransactionConfirmed(\n txMeta: TransactionMeta,\n receipt: SuccessfulTransactionReceipt,\n ) {\n const { id } = txMeta;\n const { blockHash } = receipt;\n\n log('Transaction confirmed', id);\n\n const { baseFeePerGas, timestamp: blockTimestamp } =\n await this.#getBlockByHash(blockHash, false);\n\n txMeta.baseFeePerGas = baseFeePerGas;\n txMeta.blockTimestamp = blockTimestamp;\n txMeta.status = TransactionStatus.confirmed;\n txMeta.txParams.gasUsed = receipt.gasUsed;\n txMeta.txReceipt = receipt;\n txMeta.verifiedOnBlockchain = true;\n\n this.#updateTransaction(\n txMeta,\n 'PendingTransactionTracker:#onTransactionConfirmed - Transaction confirmed',\n );\n\n this.hub.emit('transaction-confirmed', txMeta);\n }\n\n async #isTransactionDropped(txMeta: TransactionMeta) {\n const {\n hash,\n id,\n txParams: { nonce, from },\n } = txMeta;\n\n /* istanbul ignore next */\n if (!nonce || !hash) {\n return false;\n }\n\n const networkNextNonceHex = await this.#getNetworkTransactionCount(from);\n const networkNextNonceNumber = parseInt(networkNextNonceHex, 16);\n const nonceNumber = parseInt(nonce, 16);\n\n if (nonceNumber >= networkNextNonceNumber) {\n return false;\n }\n\n let droppedBlockCount = this.#droppedBlockCountByHash.get(hash);\n\n if (droppedBlockCount === undefined) {\n droppedBlockCount = 0;\n this.#droppedBlockCountByHash.set(hash, droppedBlockCount);\n }\n\n if (droppedBlockCount < DROPPED_BLOCK_COUNT) {\n log('Incrementing dropped block count', { id, droppedBlockCount });\n this.#droppedBlockCountByHash.set(hash, droppedBlockCount + 1);\n return false;\n }\n\n log('Hit dropped block count', id);\n\n this.#droppedBlockCountByHash.delete(hash);\n return true;\n }\n\n #isNonceTaken(txMeta: TransactionMeta): boolean {\n const { id, txParams } = txMeta;\n\n return this.#getTransactions().some(\n (tx) =>\n tx.id !== id &&\n tx.txParams.from === txParams.from &&\n tx.status === TransactionStatus.confirmed &&\n tx.txParams.nonce === txParams.nonce,\n );\n }\n\n #getPendingTransactions(transactions?: TransactionMeta[]): TransactionMeta[] {\n const currentChainId = this.#getChainId();\n\n return (transactions ?? this.#getTransactions()).filter(\n (tx) =>\n tx.status === TransactionStatus.submitted &&\n tx.chainId === currentChainId &&\n !tx.verifiedOnBlockchain,\n );\n }\n\n #warnTransaction(txMeta: TransactionMeta, error: string, message: string) {\n txMeta.warning = {\n error,\n message,\n };\n\n this.#updateTransaction(\n txMeta,\n 'PendingTransactionTracker:#warnTransaction - Warning added',\n );\n }\n\n #failTransaction(txMeta: TransactionMeta, error: Error) {\n log('Transaction failed', txMeta.id, error);\n this.hub.emit('transaction-failed', txMeta, error);\n }\n\n #dropTransaction(txMeta: TransactionMeta) {\n log('Transaction dropped', txMeta.id);\n this.hub.emit('transaction-dropped', txMeta);\n }\n\n #updateTransaction(txMeta: TransactionMeta, note: string) {\n this.hub.emit('transaction-updated', txMeta, note);\n }\n\n async #getTransactionReceipt(\n txHash?: string,\n ): Promise<TransactionReceipt | undefined> {\n return await query(this.#getEthQuery(), 'getTransactionReceipt', [txHash]);\n }\n\n async #getBlockByHash(\n blockHash: string,\n includeTransactionDetails: boolean,\n ): Promise<any> {\n return await query(this.#getEthQuery(), 'getBlockByHash', [\n blockHash,\n includeTransactionDetails,\n ]);\n }\n\n async #getNetworkTransactionCount(address: string): Promise<string> {\n return await query(this.#getEthQuery(), 'getTransactionCount', [address]);\n }\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -40,6 +40,9 @@ export declare type Events = {
|
|
|
40
40
|
actionId?: string;
|
|
41
41
|
}
|
|
42
42
|
];
|
|
43
|
+
['transaction-status-update']: [{
|
|
44
|
+
transactionMeta: TransactionMeta;
|
|
45
|
+
}];
|
|
43
46
|
['transaction-submitted']: [
|
|
44
47
|
{
|
|
45
48
|
transactionMeta: TransactionMeta;
|
|
@@ -47,8 +50,9 @@ export declare type Events = {
|
|
|
47
50
|
}
|
|
48
51
|
];
|
|
49
52
|
['unapprovedTransaction']: [transactionMeta: TransactionMeta];
|
|
50
|
-
[key: `${string}:finished`]: [transactionMeta: TransactionMeta];
|
|
51
53
|
[key: `${string}:confirmed`]: [transactionMeta: TransactionMeta];
|
|
54
|
+
[key: `${string}:finished`]: [transactionMeta: TransactionMeta];
|
|
55
|
+
[key: `${string}:publish-skip`]: [tansactionMeta: TransactionMeta];
|
|
52
56
|
[key: `${string}:speedup`]: [transactionMeta: TransactionMeta];
|
|
53
57
|
};
|
|
54
58
|
/**
|
|
@@ -282,7 +286,7 @@ declare type TransactionMetaBase = {
|
|
|
282
286
|
/**
|
|
283
287
|
* The metadata of the swap transaction.
|
|
284
288
|
*/
|
|
285
|
-
swapMetaData?: Record<string,
|
|
289
|
+
swapMetaData?: Record<string, any>;
|
|
286
290
|
/**
|
|
287
291
|
* The value of the token being swapped.
|
|
288
292
|
*/
|
|
@@ -583,9 +587,9 @@ export interface TransactionReceipt {
|
|
|
583
587
|
*/
|
|
584
588
|
status?: string;
|
|
585
589
|
/**
|
|
586
|
-
* The index of this transaction in the list of transactions included in the block this transaction was mined in.
|
|
590
|
+
* The hexadecimal index of this transaction in the list of transactions included in the block this transaction was mined in.
|
|
587
591
|
*/
|
|
588
|
-
transactionIndex?:
|
|
592
|
+
transactionIndex?: string;
|
|
589
593
|
}
|
|
590
594
|
/**
|
|
591
595
|
* Represents an event that has been included in a transaction using the EVM `LOG` opcode.
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,oBAAY,MAAM,GAAG;IACnB,CAAC,0BAA0B,CAAC,EAAE,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IACpD,CAAC,kCAAkC,CAAC,EAAE;QACpC;YACE,eAAe,EAAE,eAAe,CAAC;YACjC,uBAAuB,CAAC,EAAE,eAAe,CAAC;SAC3C;KACF,CAAC;IACF,CAAC,sBAAsB,CAAC,EAAE;QACxB;YAAE,eAAe,EAAE,eAAe,CAAC;YAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;SAAE;KACxD,CAAC;IACF,CAAC,uBAAuB,CAAC,EAAE,CAAC;QAAE,eAAe,EAAE,eAAe,CAAA;KAAE,CAAC,CAAC;IAElE,CAAC,qBAAqB,CAAC,EAAE,CAAC;QAAE,eAAe,EAAE,eAAe,CAAA;KAAE,CAAC,CAAC;IAChE,CAAC,oBAAoB,CAAC,EAAE;QACtB;YACE,QAAQ,CAAC,EAAE,MAAM,CAAC;YAClB,KAAK,EAAE,MAAM,CAAC;YACd,eAAe,EAAE,eAAe,CAAC;SAClC;KACF,CAAC;IACF,CAAC,sBAAsB,CAAC,EAAE,CAAC;QAAE,eAAe,EAAE,eAAe,CAAA;KAAE,CAAC,CAAC;IACjE,CAAC,+BAA+B,CAAC,EAAE,CAAC;QAAE,eAAe,E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,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,qBAAqB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAChD,CAAC"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAoZA;;;;GAIG;AACH,IAAY,iBAWX;AAXD,WAAY,iBAAiB;IAC3B,0CAAqB,CAAA;IACrB,wFAAwF;IACxF,4CAAuB,CAAA;IACvB,4CAAuB,CAAA;IACvB,wCAAmB,CAAA;IACnB,sCAAiB,CAAA;IACjB,0CAAqB,CAAA;IACrB,sCAAiB,CAAA;IACjB,4CAAuB,CAAA;IACvB,8CAAyB,CAAA;AAC3B,CAAC,EAXW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QAW5B;AAED;;GAEG;AACH,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,6CAA6B,CAAA;IAC7B,mDAAmC,CAAA;IACnC,sCAAsB,CAAA;AACxB,CAAC,EAJW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAIvB;AAED;;GAEG;AACH,IAAY,eA+GX;AA/GD,WAAY,eAAe;IACzB;;OAEG;IACH,oCAAiB,CAAA;IAEjB;;;;OAIG;IACH,8DAA2C,CAAA;IAE3C;;OAEG;IACH,wDAAqC,CAAA;IAErC;;OAEG;IACH,6CAA0B,CAAA;IAE1B;;OAEG;IACH,2EAAwD,CAAA;IAExD;;OAEG;IACH,wCAAqB,CAAA;IAErB;;OAEG;IACH,iDAA8B,CAAA;IAE9B;;;;;OAKG;IACH,kCAAe,CAAA;IAEf;;OAEG;IACH,4CAAyB,CAAA;IAEzB;;OAEG;IACH,oCAAiB,CAAA;IAEjB;;OAEG;IACH,sDAAmC,CAAA;IAEnC;;OAEG;IACH,kCAAe,CAAA;IAEf;;OAEG;IACH,gCAAa,CAAA;IAEb;;;;;OAKG;IACH,gDAA6B,CAAA;IAE7B;;;OAGG;IACH,iDAA8B,CAAA;IAE9B;;;;;OAKG;IACH,mEAAgD,CAAA;IAEhD;;;OAGG;IACH,mDAAgC,CAAA;IAEhC;;;;OAIG;IACH,2DAAwC,CAAA;IAExC;;;OAGG;IACH,qEAAkD,CAAA;AACpD,CAAC,EA/GW,eAAe,GAAf,uBAAe,KAAf,uBAAe,QA+G1B;AAuSD;;;GAGG;AACH,IAAY,uBAsBX;AAtBD,WAAY,uBAAuB;IACjC;;OAEG;IACH,yCAAc,CAAA;IAEd;;;;OAIG;IACH,6CAAkB,CAAA;IAElB;;;;;;;OAOG;IACH,4CAAiB,CAAA;AACnB,CAAC,EAtBW,uBAAuB,GAAvB,+BAAuB,KAAvB,+BAAuB,QAsBlC;AAED;;GAEG;AACH,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,iCAAiB,CAAA;IACjB,gDAAgC,CAAA;IAChC,iCAAiB,CAAA;AACnB,CAAC,EAJW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAIvB","sourcesContent":["import type { AccessList } from '@ethereumjs/tx';\nimport type { Hex } from '@metamask/utils';\nimport type { Operation } from 'fast-json-patch';\n\nexport type Events = {\n ['incomingTransactionBlock']: [blockNumber: number];\n ['post-transaction-balance-updated']: [\n {\n transactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n },\n ];\n ['transaction-approved']: [\n { transactionMeta: TransactionMeta; actionId?: string },\n ];\n ['transaction-confirmed']: [{ transactionMeta: TransactionMeta }];\n\n ['transaction-dropped']: [{ transactionMeta: TransactionMeta }];\n ['transaction-failed']: [\n {\n actionId?: string;\n error: string;\n transactionMeta: TransactionMeta;\n },\n ];\n ['transaction-new-swap']: [{ transactionMeta: TransactionMeta }];\n ['transaction-new-swap-approval']: [{ transactionMeta: TransactionMeta }];\n ['transaction-rejected']: [\n { transactionMeta: TransactionMeta; actionId?: string },\n ];\n ['transaction-submitted']: [\n { transactionMeta: TransactionMeta; actionId?: string },\n ];\n ['unapprovedTransaction']: [transactionMeta: TransactionMeta];\n [key: `${string}:finished`]: [transactionMeta: TransactionMeta];\n [key: `${string}:confirmed`]: [transactionMeta: TransactionMeta];\n [key: `${string}:speedup`]: [transactionMeta: TransactionMeta];\n};\n\n/**\n * Representation of transaction metadata.\n */\nexport type TransactionMeta = TransactionMetaBase &\n (\n | { status: Exclude<TransactionStatus, TransactionStatus.failed> }\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 /**\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 decimals of the token being received of swap transaction.\n */\n destinationTokenDecimals?: string;\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 /**\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 * 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 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 * 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 symbol of the token being swapped.\n */\n sourceTokenSymbol?: string;\n\n /**\n * The metadata of the swap transaction.\n */\n swapMetaData?: Record<string, unknown>;\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 * The status of the transaction. Each status represents the state of the transaction internally\n * in the wallet. Some of these correspond with the state of the transaction on the network, but\n * some are wallet-specific.\n */\nexport enum TransactionStatus {\n approved = 'approved',\n /** @deprecated Determined by the clients using the transaction type. No longer used. */\n cancelled = 'cancelled',\n confirmed = 'confirmed',\n dropped = 'dropped',\n failed = 'failed',\n rejected = 'rejected',\n signed = 'signed',\n submitted = 'submitted',\n unapproved = 'unapproved',\n}\n\n/**\n * Options for wallet device.\n */\nexport enum WalletDevice {\n MM_MOBILE = 'metamask_mobile',\n MM_EXTENSION = 'metamask_extension',\n OTHER = 'other_device',\n}\n\n/**\n * The type of the transaction.\n */\nexport enum TransactionType {\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n cancel = 'cancel',\n\n /**\n * A transaction that is interacting with a smart contract's methods that we\n * have not treated as a special case, such as approve, transfer, and\n * transferfrom.\n */\n contractInteraction = 'contractInteraction',\n\n /**\n * A transaction that deployed a smart contract.\n */\n deployContract = 'contractDeployment',\n\n /**\n * A transaction for Ethereum decryption.\n */\n ethDecrypt = 'eth_decrypt',\n\n /**\n * A transaction for getting an encryption public key.\n */\n ethGetEncryptionPublicKey = 'eth_getEncryptionPublicKey',\n\n /**\n * An incoming (deposit) transaction.\n */\n incoming = 'incoming',\n\n /**\n * A transaction for personal sign.\n */\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 retry = 'retry',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n simpleSend = 'simpleSend',\n\n /**\n * A transaction that is signing a message.\n */\n sign = 'eth_sign',\n\n /**\n * A transaction that is signing typed data.\n */\n signTypedData = 'eth_signTypedData',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n smart = 'smart',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps.\n */\n swap = 'swap',\n\n /**\n * Similar to the approve type, a swap approval is a special case of ERC20\n * approve method that requests an allowance of the token to spend on behalf\n * of the user for the MetaMask Swaps contract. The first swap for any token\n * will have an accompanying swapApproval transaction.\n */\n swapApproval = 'swapApproval',\n\n /**\n * A token transaction requesting an allowance of the token to spend on\n * behalf of the user.\n */\n tokenMethodApprove = 'approve',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. The method is prefixed with safe because when calling\n * this method the contract checks to ensure that the receiver is an address\n * capable of handling the token being sent.\n */\n tokenMethodSafeTransferFrom = 'safetransferfrom',\n\n /**\n * A token transaction where the user is sending tokens that they own to\n * another address.\n */\n tokenMethodTransfer = 'transfer',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. For more information on allowances, see the approve\n * type.\n */\n tokenMethodTransferFrom = 'transferfrom',\n\n /**\n * A token transaction requesting an allowance of all of a user's tokens to\n * spend on behalf of the user.\n */\n tokenMethodSetApprovalForAll = 'setapprovalforall',\n}\n\n/**\n * Standard data concerning a transaction to be processed by the blockchain.\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 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 */\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 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 index of this transaction in the list of transactions included in the block this transaction was mined in.\n */\n transactionIndex?: number;\n}\n\n/**\n * Represents an event that has been included in a transaction using the EVM `LOG` opcode.\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 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 */\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 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 = Operation & {\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 ...Operation[],\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) => Promise<any>;\n\n/**\n * Specifies the shape of the base transaction parameters.\n * Added in EIP-2718.\n */\nexport enum TransactionEnvelopeType {\n /**\n * A legacy transaction, the very first type.\n */\n legacy = '0x0',\n\n /**\n * EIP-2930 defined the access list transaction type that allowed for\n * specifying the state that a transaction would act upon in advance and\n * theoretically save on gas fees.\n */\n accessList = '0x1',\n\n /**\n * The type introduced comes from EIP-1559, Fee Market describes the addition\n * of a baseFee to blocks that will be burned instead of distributed to\n * miners. Transactions of this type have both a maxFeePerGas (maximum total\n * amount in gwei per gas to spend on the transaction) which is inclusive of\n * the maxPriorityFeePerGas (maximum amount of gwei per gas from the\n * transaction fee to distribute to miner).\n */\n feeMarket = '0x2',\n}\n\n/**\n * The source of the gas fee parameters on a transaction.\n */\nexport enum UserFeeLevel {\n CUSTOM = 'custom',\n DAPP_SUGGESTED = 'dappSuggested',\n MEDIUM = 'medium',\n}\n\n/**\n * Initial gas values set when the transaction was first created.\n */\nexport type DefaultGasEstimates = {\n /**\n * Source of the gas fee values, such as `dappSuggested` or `medium`.\n */\n estimateType?: string;\n\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gas?: string;\n\n /**\n * Price per gas for legacy transactions.\n */\n gasPrice?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Data concerning an error while processing a transaction.\n */\nexport type TransactionError = {\n /**\n * A descriptive error name.\n */\n name: string;\n\n /**\n * A descriptive error message providing details about the encountered error.\n */\n message: string;\n\n /**\n * The stack trace associated with the error, if available.\n */\n stack?: string;\n\n /**\n * An optional error code associated with the error.\n */\n code?: string;\n\n /**\n * The rpc property holds additional information related to the error.\n */\n rpc?: unknown;\n};\n\n/**\n * Type for security alert response from transaction validator.\n */\nexport type SecurityAlertResponse = {\n reason: string;\n features?: string[];\n result_type: string;\n providerRequestsCount?: Record<string, number>;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAsZA;;;;GAIG;AACH,IAAY,iBAWX;AAXD,WAAY,iBAAiB;IAC3B,0CAAqB,CAAA;IACrB,wFAAwF;IACxF,4CAAuB,CAAA;IACvB,4CAAuB,CAAA;IACvB,wCAAmB,CAAA;IACnB,sCAAiB,CAAA;IACjB,0CAAqB,CAAA;IACrB,sCAAiB,CAAA;IACjB,4CAAuB,CAAA;IACvB,8CAAyB,CAAA;AAC3B,CAAC,EAXW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QAW5B;AAED;;GAEG;AACH,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,6CAA6B,CAAA;IAC7B,mDAAmC,CAAA;IACnC,sCAAsB,CAAA;AACxB,CAAC,EAJW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAIvB;AAED;;GAEG;AACH,IAAY,eA+GX;AA/GD,WAAY,eAAe;IACzB;;OAEG;IACH,oCAAiB,CAAA;IAEjB;;;;OAIG;IACH,8DAA2C,CAAA;IAE3C;;OAEG;IACH,wDAAqC,CAAA;IAErC;;OAEG;IACH,6CAA0B,CAAA;IAE1B;;OAEG;IACH,2EAAwD,CAAA;IAExD;;OAEG;IACH,wCAAqB,CAAA;IAErB;;OAEG;IACH,iDAA8B,CAAA;IAE9B;;;;;OAKG;IACH,kCAAe,CAAA;IAEf;;OAEG;IACH,4CAAyB,CAAA;IAEzB;;OAEG;IACH,oCAAiB,CAAA;IAEjB;;OAEG;IACH,sDAAmC,CAAA;IAEnC;;OAEG;IACH,kCAAe,CAAA;IAEf;;OAEG;IACH,gCAAa,CAAA;IAEb;;;;;OAKG;IACH,gDAA6B,CAAA;IAE7B;;;OAGG;IACH,iDAA8B,CAAA;IAE9B;;;;;OAKG;IACH,mEAAgD,CAAA;IAEhD;;;OAGG;IACH,mDAAgC,CAAA;IAEhC;;;;OAIG;IACH,2DAAwC,CAAA;IAExC;;;OAGG;IACH,qEAAkD,CAAA;AACpD,CAAC,EA/GW,eAAe,GAAf,uBAAe,KAAf,uBAAe,QA+G1B;AAuSD;;;GAGG;AACH,IAAY,uBAsBX;AAtBD,WAAY,uBAAuB;IACjC;;OAEG;IACH,yCAAc,CAAA;IAEd;;;;OAIG;IACH,6CAAkB,CAAA;IAElB;;;;;;;OAOG;IACH,4CAAiB,CAAA;AACnB,CAAC,EAtBW,uBAAuB,GAAvB,+BAAuB,KAAvB,+BAAuB,QAsBlC;AAED;;GAEG;AACH,IAAY,YAIX;AAJD,WAAY,YAAY;IACtB,iCAAiB,CAAA;IACjB,gDAAgC,CAAA;IAChC,iCAAiB,CAAA;AACnB,CAAC,EAJW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAIvB","sourcesContent":["import type { AccessList } from '@ethereumjs/tx';\nimport type { Hex } from '@metamask/utils';\nimport type { Operation } from 'fast-json-patch';\n\nexport type Events = {\n ['incomingTransactionBlock']: [blockNumber: number];\n ['post-transaction-balance-updated']: [\n {\n transactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n },\n ];\n ['transaction-approved']: [\n { transactionMeta: TransactionMeta; actionId?: string },\n ];\n ['transaction-confirmed']: [{ transactionMeta: TransactionMeta }];\n\n ['transaction-dropped']: [{ transactionMeta: TransactionMeta }];\n ['transaction-failed']: [\n {\n actionId?: string;\n error: string;\n transactionMeta: TransactionMeta;\n },\n ];\n ['transaction-new-swap']: [{ transactionMeta: TransactionMeta }];\n ['transaction-new-swap-approval']: [{ transactionMeta: TransactionMeta }];\n ['transaction-rejected']: [\n { transactionMeta: TransactionMeta; actionId?: string },\n ];\n ['transaction-status-update']: [{ transactionMeta: TransactionMeta }];\n ['transaction-submitted']: [\n { transactionMeta: TransactionMeta; actionId?: string },\n ];\n ['unapprovedTransaction']: [transactionMeta: TransactionMeta];\n [key: `${string}:confirmed`]: [transactionMeta: TransactionMeta];\n [key: `${string}:finished`]: [transactionMeta: TransactionMeta];\n [key: `${string}:publish-skip`]: [tansactionMeta: TransactionMeta];\n [key: `${string}:speedup`]: [transactionMeta: TransactionMeta];\n};\n\n/**\n * Representation of transaction metadata.\n */\nexport type TransactionMeta = TransactionMetaBase &\n (\n | { status: Exclude<TransactionStatus, TransactionStatus.failed> }\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 /**\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 decimals of the token being received of swap transaction.\n */\n destinationTokenDecimals?: string;\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 /**\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 * 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 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 * 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 symbol of the token being swapped.\n */\n sourceTokenSymbol?: string;\n\n /**\n * The metadata of the swap transaction.\n */\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 * The status of the transaction. Each status represents the state of the transaction internally\n * in the wallet. Some of these correspond with the state of the transaction on the network, but\n * some are wallet-specific.\n */\nexport enum TransactionStatus {\n approved = 'approved',\n /** @deprecated Determined by the clients using the transaction type. No longer used. */\n cancelled = 'cancelled',\n confirmed = 'confirmed',\n dropped = 'dropped',\n failed = 'failed',\n rejected = 'rejected',\n signed = 'signed',\n submitted = 'submitted',\n unapproved = 'unapproved',\n}\n\n/**\n * Options for wallet device.\n */\nexport enum WalletDevice {\n MM_MOBILE = 'metamask_mobile',\n MM_EXTENSION = 'metamask_extension',\n OTHER = 'other_device',\n}\n\n/**\n * The type of the transaction.\n */\nexport enum TransactionType {\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n cancel = 'cancel',\n\n /**\n * A transaction that is interacting with a smart contract's methods that we\n * have not treated as a special case, such as approve, transfer, and\n * transferfrom.\n */\n contractInteraction = 'contractInteraction',\n\n /**\n * A transaction that deployed a smart contract.\n */\n deployContract = 'contractDeployment',\n\n /**\n * A transaction for Ethereum decryption.\n */\n ethDecrypt = 'eth_decrypt',\n\n /**\n * A transaction for getting an encryption public key.\n */\n ethGetEncryptionPublicKey = 'eth_getEncryptionPublicKey',\n\n /**\n * An incoming (deposit) transaction.\n */\n incoming = 'incoming',\n\n /**\n * A transaction for personal sign.\n */\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 retry = 'retry',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n simpleSend = 'simpleSend',\n\n /**\n * A transaction that is signing a message.\n */\n sign = 'eth_sign',\n\n /**\n * A transaction that is signing typed data.\n */\n signTypedData = 'eth_signTypedData',\n\n /**\n * A transaction sending a network's native asset to a recipient.\n */\n smart = 'smart',\n\n /**\n * A transaction swapping one token for another through MetaMask Swaps.\n */\n swap = 'swap',\n\n /**\n * Similar to the approve type, a swap approval is a special case of ERC20\n * approve method that requests an allowance of the token to spend on behalf\n * of the user for the MetaMask Swaps contract. The first swap for any token\n * will have an accompanying swapApproval transaction.\n */\n swapApproval = 'swapApproval',\n\n /**\n * A token transaction requesting an allowance of the token to spend on\n * behalf of the user.\n */\n tokenMethodApprove = 'approve',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. The method is prefixed with safe because when calling\n * this method the contract checks to ensure that the receiver is an address\n * capable of handling the token being sent.\n */\n tokenMethodSafeTransferFrom = 'safetransferfrom',\n\n /**\n * A token transaction where the user is sending tokens that they own to\n * another address.\n */\n tokenMethodTransfer = 'transfer',\n\n /**\n * A token transaction transferring tokens from an account that the sender\n * has an allowance of. For more information on allowances, see the approve\n * type.\n */\n tokenMethodTransferFrom = 'transferfrom',\n\n /**\n * A token transaction requesting an allowance of all of a user's tokens to\n * spend on behalf of the user.\n */\n tokenMethodSetApprovalForAll = 'setapprovalforall',\n}\n\n/**\n * Standard data concerning a transaction to be processed by the blockchain.\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 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 */\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 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 */\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 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 */\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 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 = Operation & {\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 ...Operation[],\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) => Promise<any>;\n\n/**\n * Specifies the shape of the base transaction parameters.\n * Added in EIP-2718.\n */\nexport enum TransactionEnvelopeType {\n /**\n * A legacy transaction, the very first type.\n */\n legacy = '0x0',\n\n /**\n * EIP-2930 defined the access list transaction type that allowed for\n * specifying the state that a transaction would act upon in advance and\n * theoretically save on gas fees.\n */\n accessList = '0x1',\n\n /**\n * The type introduced comes from EIP-1559, Fee Market describes the addition\n * of a baseFee to blocks that will be burned instead of distributed to\n * miners. Transactions of this type have both a maxFeePerGas (maximum total\n * amount in gwei per gas to spend on the transaction) which is inclusive of\n * the maxPriorityFeePerGas (maximum amount of gwei per gas from the\n * transaction fee to distribute to miner).\n */\n feeMarket = '0x2',\n}\n\n/**\n * The source of the gas fee parameters on a transaction.\n */\nexport enum UserFeeLevel {\n CUSTOM = 'custom',\n DAPP_SUGGESTED = 'dappSuggested',\n MEDIUM = 'medium',\n}\n\n/**\n * Initial gas values set when the transaction was first created.\n */\nexport type DefaultGasEstimates = {\n /**\n * Source of the gas fee values, such as `dappSuggested` or `medium`.\n */\n estimateType?: string;\n\n /**\n * Maxmimum number of units of gas to use for this transaction.\n */\n gas?: string;\n\n /**\n * Price per gas for legacy transactions.\n */\n gasPrice?: string;\n\n /**\n * Maximum amount per gas to pay for the transaction, including the priority fee.\n */\n maxFeePerGas?: string;\n\n /**\n * Maximum amount per gas to give to validator as incentive.\n */\n maxPriorityFeePerGas?: string;\n};\n\n/**\n * Data concerning an error while processing a transaction.\n */\nexport type TransactionError = {\n /**\n * A descriptive error name.\n */\n name: string;\n\n /**\n * A descriptive error message providing details about the encountered error.\n */\n message: string;\n\n /**\n * The stack trace associated with the error, if available.\n */\n stack?: string;\n\n /**\n * An optional error code associated with the error.\n */\n code?: string;\n\n /**\n * The rpc property holds additional information related to the error.\n */\n rpc?: unknown;\n};\n\n/**\n * Type for security alert response from transaction validator.\n */\nexport type SecurityAlertResponse = {\n reason: string;\n features?: string[];\n result_type: string;\n providerRequestsCount?: Record<string, number>;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swaps.d.ts","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"swaps.d.ts","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAKhD,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAK3C;;GAEG;AACH,eAAO,MAAM,8BAA8B,OAAO,CAAC;AAEnD;;GAEG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAIjD;;GAEG;AACH,eAAO,MAAM,qBAAqB,+CACY,CAAC;AAI/C,UAAU,gBAAgB;IACxB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;CAClB;AAkDD,eAAO,MAAM,+BAA+B;;;;;;;;;;CAUlC,CAAC;AAEX,eAAO,MAAM,sBAAsB,mBAGlC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAsB,sBAAsB,CAC1C,eAAe,EAAE,eAAe,EAChC,eAAe,EAAE,eAAe,EAChC,KAAK,EAAE;IACL,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,IAAI,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;CACjC,EACD,EACE,eAAe,EACf,iBAAiB,EACjB,oBAAoB,GACrB,EAAE;IACD,eAAe,EAAE,OAAO,CAAC;IACzB,iBAAiB,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,IAAI,CAAC;IACnD,oBAAoB,EAAE,CAAC,CAAC,SAAS,MAAM,MAAM,EAC3C,SAAS,EAAE,CAAC,EACZ,GAAG,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,KACf,OAAO,CAAC;CACd,iBAyCF;AAED;;;;;;;;GAQG;AACH,wBAAsB,4BAA4B,CAChD,eAAe,EAAE,eAAe,EAChC,EACE,QAAQ,EACR,cAAc,EACd,iBAAiB,GAClB,EAAE;IACD,QAAQ,EAAE,QAAQ,CAAC;IACnB,cAAc,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,eAAe,GAAG,SAAS,CAAC;IACvE,iBAAiB,EAAE,CAAC,eAAe,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7E,GACA,OAAO,CAAC;IACT,sBAAsB,EAAE,eAAe,CAAC;IACxC,uBAAuB,CAAC,EAAE,eAAe,CAAC;CAC3C,CAAC,CAyDD"}
|
package/dist/utils/swaps.js
CHANGED
|
@@ -13,8 +13,10 @@ exports.updatePostTransactionBalance = exports.updateSwapsTransaction = exports.
|
|
|
13
13
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
14
14
|
const lodash_1 = require("lodash");
|
|
15
15
|
const constants_1 = require("../constants");
|
|
16
|
+
const logger_1 = require("../logger");
|
|
16
17
|
const types_1 = require("../types");
|
|
17
18
|
const utils_1 = require("./utils");
|
|
19
|
+
const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'swaps');
|
|
18
20
|
/**
|
|
19
21
|
* Interval in milliseconds between checks of post transaction balance
|
|
20
22
|
*/
|
|
@@ -138,9 +140,11 @@ exports.updateSwapsTransaction = updateSwapsTransaction;
|
|
|
138
140
|
*/
|
|
139
141
|
function updatePostTransactionBalance(transactionMeta, { ethQuery, getTransaction, updateTransaction, }) {
|
|
140
142
|
return __awaiter(this, void 0, void 0, function* () {
|
|
143
|
+
log('Updating post transaction balance', transactionMeta.id);
|
|
141
144
|
const transactionId = transactionMeta.id;
|
|
142
145
|
let latestTransactionMeta, approvalTransactionMeta;
|
|
143
146
|
for (let i = 0; i < exports.UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {
|
|
147
|
+
log('Querying balance', { attempt: i });
|
|
144
148
|
const postTransactionBalance = yield (0, controller_utils_1.query)(ethQuery, 'getBalance', [
|
|
145
149
|
transactionMeta.txParams.from,
|
|
146
150
|
]);
|
|
@@ -152,11 +156,20 @@ function updatePostTransactionBalance(transactionMeta, { ethQuery, getTransactio
|
|
|
152
156
|
const isDefaultTokenAddress = isSwapsDefaultTokenAddress(transactionMeta.destinationTokenAddress, transactionMeta.chainId);
|
|
153
157
|
if (!isDefaultTokenAddress ||
|
|
154
158
|
transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance) {
|
|
159
|
+
log('Finishing post balance update', {
|
|
160
|
+
isDefaultTokenAddress,
|
|
161
|
+
preTxBalance: transactionMeta.preTxBalance,
|
|
162
|
+
postTxBalance: latestTransactionMeta.postTxBalance,
|
|
163
|
+
});
|
|
155
164
|
break;
|
|
156
165
|
}
|
|
166
|
+
log('Waiting for balance to update', {
|
|
167
|
+
delay: exports.UPDATE_POST_TX_BALANCE_TIMEOUT,
|
|
168
|
+
});
|
|
157
169
|
yield sleep(exports.UPDATE_POST_TX_BALANCE_TIMEOUT);
|
|
158
170
|
}
|
|
159
171
|
updateTransaction(latestTransactionMeta, 'TransactionController#updatePostTransactionBalance - Add post transaction balance');
|
|
172
|
+
log('Completed post balance update', latestTransactionMeta === null || latestTransactionMeta === void 0 ? void 0 : latestTransactionMeta.postTxBalance);
|
|
160
173
|
return {
|
|
161
174
|
updatedTransactionMeta: latestTransactionMeta,
|
|
162
175
|
approvalTransactionMeta,
|
package/dist/utils/swaps.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swaps.js","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iEAAmD;AAEnD,mCAAuC;AAEvC,4CAAyC;AAEzC,oCAA2C;AAC3C,mCAA0D;AAE1D;;GAEG;AACU,QAAA,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACU,QAAA,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACU,QAAA,qBAAqB,GAChC,4CAA4C,CAAC;AAmB/C,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACb,CAAC;AAEF,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,cAAc;IACpB,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,wBAAwB,GAAqB;IACjD,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,uBAAuB,GAAqB;IAChD,IAAI,EAAE,WAAW;IACjB,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,2BAA2B,GAAqB;IACpD,IAAI,EAAE,YAAY;IAClB,OAAO,EAAE,6BAAqB;IAC9B,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B;IAErD,IAAA,uCAA+B,EAC7B,eAAe,EACf,+BAA+B,CAChC,CAAC;IAEF,IAAI,uBAAuB,GAAG,EAAE,IAAI,EAAE,iBAAiB,EAAS,CAAC;IACjE,uBAAuB,GAAG,IAAA,eAAM,EAAC;QAC/B,IAAI;QACJ,iBAAiB;KAClB,CAA6B,CAAC;IAC/B,IAAA,cAAK,EAAC,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAClD,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE;QACxB,OAAO,KAAK,CAAC;KACd;IAED,OAAO,CACL,OAAO;SACP,MAAA,uCAA+B,CAC7B,OAAuD,CACxD,0CAAE,OAAO,CAAA,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { CHAIN_IDS } from '../constants';\nimport type { Events, TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\nimport { validateIfTransactionUnapproved } from './utils';\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.controllerHubEmitter - Function to emit an event to the controller hub\n */\nexport async function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n controllerHubEmitter,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n controllerHubEmitter: <T extends keyof Events>(\n eventName: T,\n ...args: Events[T]\n ) => boolean;\n },\n) {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return;\n }\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n await cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return;\n }\n\n if (transactionType === TransactionType.swapApproval) {\n updateSwapApprovalTransaction(transactionMeta, swapsMeta);\n controllerHubEmitter('transaction-new-swap-approval', {\n transactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updateSwapTransaction(transactionMeta, swapsMeta);\n controllerHubEmitter('transaction-new-swap', {\n transactionMeta,\n });\n }\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n const transactionId = transactionMeta.id;\n\n let latestTransactionMeta, approvalTransactionMeta;\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n latestTransactionMeta = getTransaction(transactionId) as TransactionMeta;\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n break;\n }\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n) {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n swapTransaction = pickBy(swapTransaction) as any;\n merge(transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n) {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n merge(transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string) {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"swaps.js","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iEAAmD;AAEnD,mCAAuC;AAEvC,4CAAyC;AACzC,sCAA8D;AAE9D,oCAA2C;AAC3C,mCAA0D;AAE1D,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACU,QAAA,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG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AG,EAAE,IAAI,EAAE,iBAAiB,EAAS,CAAC;IACjE,uBAAuB,GAAG,IAAA,eAAM,EAAC;QAC/B,IAAI;QACJ,iBAAiB;KAClB,CAA6B,CAAC;IAC/B,IAAA,cAAK,EAAC,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAClD,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE;QACxB,OAAO,KAAK,CAAC;KACd;IAED,OAAO,CACL,OAAO;SACP,MAAA,uCAA+B,CAC7B,OAAuD,CACxD,0CAAE,OAAO,CAAA,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { Events, TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\nimport { validateIfTransactionUnapproved } from './utils';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.controllerHubEmitter - Function to emit an event to the controller hub\n */\nexport async function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n controllerHubEmitter,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n controllerHubEmitter: <T extends keyof Events>(\n eventName: T,\n ...args: Events[T]\n ) => boolean;\n },\n) {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return;\n }\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n await cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return;\n }\n\n if (transactionType === TransactionType.swapApproval) {\n updateSwapApprovalTransaction(transactionMeta, swapsMeta);\n controllerHubEmitter('transaction-new-swap-approval', {\n transactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updateSwapTransaction(transactionMeta, swapsMeta);\n controllerHubEmitter('transaction-new-swap', {\n transactionMeta,\n });\n }\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta, approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = getTransaction(transactionId) as TransactionMeta;\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\n });\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\n\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n) {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n swapTransaction = pickBy(swapTransaction) as any;\n merge(transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n) {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n merge(transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string) {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
package/dist/utils/utils.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Transaction as NonceTrackerTransaction } from 'nonce-tracker
|
|
1
|
+
import type { Transaction as NonceTrackerTransaction } from 'nonce-tracker';
|
|
2
2
|
import type { GasPriceValue, FeeMarketEIP1559Values } from '../TransactionController';
|
|
3
3
|
import { TransactionStatus } from '../types';
|
|
4
4
|
import type { TransactionParams, TransactionMeta, TransactionError } from '../types';
|
|
@@ -35,12 +35,13 @@ export declare function validateMinimumIncrease(proposed: string, min: string):
|
|
|
35
35
|
/**
|
|
36
36
|
* Helper function to filter and format transactions for the nonce tracker.
|
|
37
37
|
*
|
|
38
|
+
* @param currentChainId - Chain ID of the current network.
|
|
38
39
|
* @param fromAddress - Address of the account from which the transactions to filter from are sent.
|
|
39
40
|
* @param transactionStatus - Status of the transactions for which to filter.
|
|
40
41
|
* @param transactions - Array of transactionMeta objects that have been prefiltered.
|
|
41
42
|
* @returns Array of transactions formatted for the nonce tracker.
|
|
42
43
|
*/
|
|
43
|
-
export declare function getAndFormatTransactionsForNonceTracker(fromAddress: string, transactionStatus: TransactionStatus, transactions: TransactionMeta[]): NonceTrackerTransaction[];
|
|
44
|
+
export declare function getAndFormatTransactionsForNonceTracker(currentChainId: string, fromAddress: string, transactionStatus: TransactionStatus, transactions: TransactionMeta[]): NonceTrackerTransaction[];
|
|
44
45
|
/**
|
|
45
46
|
* Validates that a transaction is unapproved.
|
|
46
47
|
* Throws if the transaction is not unapproved.
|
|
@@ -59,4 +60,11 @@ export declare function normalizeTxError(error: Error & {
|
|
|
59
60
|
code?: string;
|
|
60
61
|
value?: unknown;
|
|
61
62
|
}): TransactionError;
|
|
63
|
+
/**
|
|
64
|
+
* Normalize an object containing gas fee values.
|
|
65
|
+
*
|
|
66
|
+
* @param gasFeeValues - An object containing gas fee values.
|
|
67
|
+
* @returns An object containing normalized gas fee values.
|
|
68
|
+
*/
|
|
69
|
+
export declare function normalizeGasFeeValues(gasFeeValues: GasPriceValue | FeeMarketEIP1559Values): GasPriceValue | FeeMarketEIP1559Values;
|
|
62
70
|
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,IAAI,uBAAuB,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,IAAI,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAE5E,OAAO,KAAK,EACV,aAAa,EACb,sBAAsB,EACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,EACV,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EACjB,MAAM,UAAU,CAAC;AAElB,eAAO,MAAM,kBAAkB,qCAAqC,CAAC;AAmBrE;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,iBAAiB,qBAc5D;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAOzE;AAED,eAAO,MAAM,iBAAiB,cACjB,aAAa,GAAG,sBAAsB,SAUlD,CAAC;AAEF,eAAO,MAAM,wBAAwB,eACvB,aAAa,GAAG,sBAAsB,wCAGuB,CAAC;AAE5E,eAAO,MAAM,eAAe,eACd,aAAa,GAAG,sBAAsB,+BAEE,CAAC;AAEvD,eAAO,MAAM,oBAAoB,UAAW,MAAM,QAAQ,MAAM,KAAG,MACF,CAAC;AAElE,eAAO,MAAM,6BAA6B,UACjC,MAAM,GAAG,SAAS,QACnB,MAAM,KACX,MAEF,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,UAQpE;AAED;;;;;;;;GAQG;AACH,wBAAgB,uCAAuC,CACrD,cAAc,EAAE,MAAM,EACtB,WAAW,EAAE,MAAM,EACnB,iBAAiB,EAAE,iBAAiB,EACpC,YAAY,EAAE,eAAe,EAAE,GAC9B,uBAAuB,EAAE,CAwB3B;AAED;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAC7C,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,QAQf;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,KAAK,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,GAChD,gBAAgB,CAQlB;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,aAAa,GAAG,sBAAsB,GACnD,aAAa,GAAG,sBAAsB,CAcxC"}
|
package/dist/utils/utils.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.normalizeTxError = exports.validateIfTransactionUnapproved = exports.getAndFormatTransactionsForNonceTracker = exports.validateMinimumIncrease = exports.getIncreasedPriceFromExisting = exports.getIncreasedPriceHex = exports.isGasPriceValue = exports.isFeeMarketEIP1559Values = exports.validateGasValues = exports.isEIP1559Transaction = exports.normalizeTxParams = exports.ESTIMATE_GAS_ERROR = void 0;
|
|
3
|
+
exports.normalizeGasFeeValues = exports.normalizeTxError = exports.validateIfTransactionUnapproved = exports.getAndFormatTransactionsForNonceTracker = exports.validateMinimumIncrease = exports.getIncreasedPriceFromExisting = exports.getIncreasedPriceHex = exports.isGasPriceValue = exports.isFeeMarketEIP1559Values = exports.validateGasValues = exports.isEIP1559Transaction = exports.normalizeTxParams = exports.ESTIMATE_GAS_ERROR = void 0;
|
|
4
4
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
5
5
|
const utils_1 = require("@metamask/utils");
|
|
6
6
|
const ethereumjs_util_1 = require("ethereumjs-util");
|
|
@@ -33,6 +33,9 @@ function normalizeTxParams(txParams) {
|
|
|
33
33
|
normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
|
+
if (!normalizedTxParams.value) {
|
|
37
|
+
normalizedTxParams.value = '0x0';
|
|
38
|
+
}
|
|
36
39
|
return normalizedTxParams;
|
|
37
40
|
}
|
|
38
41
|
exports.normalizeTxParams = normalizeTxParams;
|
|
@@ -90,14 +93,17 @@ exports.validateMinimumIncrease = validateMinimumIncrease;
|
|
|
90
93
|
/**
|
|
91
94
|
* Helper function to filter and format transactions for the nonce tracker.
|
|
92
95
|
*
|
|
96
|
+
* @param currentChainId - Chain ID of the current network.
|
|
93
97
|
* @param fromAddress - Address of the account from which the transactions to filter from are sent.
|
|
94
98
|
* @param transactionStatus - Status of the transactions for which to filter.
|
|
95
99
|
* @param transactions - Array of transactionMeta objects that have been prefiltered.
|
|
96
100
|
* @returns Array of transactions formatted for the nonce tracker.
|
|
97
101
|
*/
|
|
98
|
-
function getAndFormatTransactionsForNonceTracker(fromAddress, transactionStatus, transactions) {
|
|
102
|
+
function getAndFormatTransactionsForNonceTracker(currentChainId, fromAddress, transactionStatus, transactions) {
|
|
99
103
|
return transactions
|
|
100
|
-
.filter(({ status, txParams: { from } }) =>
|
|
104
|
+
.filter(({ chainId, isTransfer, status, txParams: { from } }) => !isTransfer &&
|
|
105
|
+
chainId === currentChainId &&
|
|
106
|
+
status === transactionStatus &&
|
|
101
107
|
from.toLowerCase() === fromAddress.toLowerCase())
|
|
102
108
|
.map(({ status, txParams: { from, gas, value, nonce } }) => {
|
|
103
109
|
// the only value we care about is the nonce
|
|
@@ -146,4 +152,23 @@ function normalizeTxError(error) {
|
|
|
146
152
|
};
|
|
147
153
|
}
|
|
148
154
|
exports.normalizeTxError = normalizeTxError;
|
|
155
|
+
/**
|
|
156
|
+
* Normalize an object containing gas fee values.
|
|
157
|
+
*
|
|
158
|
+
* @param gasFeeValues - An object containing gas fee values.
|
|
159
|
+
* @returns An object containing normalized gas fee values.
|
|
160
|
+
*/
|
|
161
|
+
function normalizeGasFeeValues(gasFeeValues) {
|
|
162
|
+
const normalize = (value) => typeof value === 'string' ? (0, ethereumjs_util_1.addHexPrefix)(value) : value;
|
|
163
|
+
if ('gasPrice' in gasFeeValues) {
|
|
164
|
+
return {
|
|
165
|
+
gasPrice: normalize(gasFeeValues.gasPrice),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
maxFeePerGas: normalize(gasFeeValues.maxFeePerGas),
|
|
170
|
+
maxPriorityFeePerGas: normalize(gasFeeValues.maxPriorityFeePerGas),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
exports.normalizeGasFeeValues = normalizeGasFeeValues;
|
|
149
174
|
//# sourceMappingURL=utils.js.map
|