diff --git a/.eslintrc.js b/.eslintrc.js index ad7822de4..fa671eecc 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -16,6 +16,7 @@ module.exports = { 'dist/**/*', 'node_modules/**/*', 'jest-coverage/**/*', + 'coverage/**/*', ], overrides: [ /** diff --git a/app/scripts/controllers/detect-tokens.js b/app/scripts/controllers/detect-tokens.js index f888888e0..a53bee096 100644 --- a/app/scripts/controllers/detect-tokens.js +++ b/app/scripts/controllers/detect-tokens.js @@ -5,8 +5,8 @@ import { STATIC_MAINNET_TOKEN_LIST } from '../../../shared/constants/tokens'; import { isTokenDetectionEnabledForNetwork } from '../../../shared/modules/network.utils'; import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils'; import { - ASSET_TYPES, - TOKEN_STANDARDS, + AssetType, + TokenStandard, } from '../../../shared/constants/transaction'; import { EVENT, EVENT_NAMES } from '../../../shared/constants/metametrics'; @@ -171,8 +171,8 @@ export default class DetectTokensController { category: EVENT.CATEGORIES.WALLET, properties: { tokens: eventTokensDetails, - token_standard: TOKEN_STANDARDS.ERC20, - asset_type: ASSET_TYPES.TOKEN, + token_standard: TokenStandard.ERC20, + asset_type: AssetType.token, }, }); await this.tokensController.addDetectedTokens(tokensWithBalance, { diff --git a/app/scripts/controllers/incoming-transactions.js b/app/scripts/controllers/incoming-transactions.js index 361399483..f74957c50 100644 --- a/app/scripts/controllers/incoming-transactions.js +++ b/app/scripts/controllers/incoming-transactions.js @@ -6,8 +6,8 @@ import { bnToHex, previousValueComparator } from '../lib/util'; import getFetchWithTimeout from '../../../shared/modules/fetch-with-timeout'; import { - TRANSACTION_TYPES, - TRANSACTION_STATUSES, + TransactionType, + TransactionStatus, } from '../../../shared/constants/transaction'; import { CHAIN_IDS, @@ -277,8 +277,8 @@ export default class IncomingTransactionsController { const time = parseInt(etherscanTransaction.timeStamp, 10) * 1000; const status = etherscanTransaction.isError === '0' - ? TRANSACTION_STATUSES.CONFIRMED - : TRANSACTION_STATUSES.FAILED; + ? TransactionStatus.confirmed + : TransactionStatus.failed; const txParams = { from: etherscanTransaction.from, gas: bnToHex(new BN(etherscanTransaction.gas)), @@ -307,7 +307,7 @@ export default class IncomingTransactionsController { time, txParams, hash: etherscanTransaction.hash, - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, }; } } diff --git a/app/scripts/controllers/incoming-transactions.test.js b/app/scripts/controllers/incoming-transactions.test.js index 2675c62ce..48bea442a 100644 --- a/app/scripts/controllers/incoming-transactions.test.js +++ b/app/scripts/controllers/incoming-transactions.test.js @@ -12,8 +12,8 @@ import { NETWORK_IDS, } from '../../../shared/constants/network'; import { - TRANSACTION_TYPES, - TRANSACTION_STATUSES, + TransactionType, + TransactionStatus, } from '../../../shared/constants/transaction'; import { MILLISECOND } from '../../../shared/constants/time'; @@ -313,9 +313,9 @@ describe('IncomingTransactionsController', function () { hash: '0xfake', metamaskNetworkId: NETWORK_IDS.GOERLI, chainId: CHAIN_IDS.GOERLI, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, time: 16000000000000000, - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, txParams: { from: '0xfake', gas: '0x0', @@ -330,9 +330,9 @@ describe('IncomingTransactionsController', function () { hash: '0xfakeeip1559', metamaskNetworkId: NETWORK_IDS.GOERLI, chainId: CHAIN_IDS.GOERLI, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, time: 16000000000000000, - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, txParams: { from: '0xfake', gas: '0x0', @@ -616,9 +616,9 @@ describe('IncomingTransactionsController', function () { hash: '0xfake', metamaskNetworkId: NETWORK_IDS.GOERLI, chainId: CHAIN_IDS.GOERLI, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, time: 16000000000000000, - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, txParams: { from: '0xfake', gas: '0x0', @@ -759,9 +759,9 @@ describe('IncomingTransactionsController', function () { hash: '0xfake', metamaskNetworkId: NETWORK_IDS.GOERLI, chainId: CHAIN_IDS.GOERLI, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, time: 16000000000000000, - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, txParams: { from: '0xfake', gas: '0x0', @@ -1238,7 +1238,7 @@ describe('IncomingTransactionsController', function () { id: 54321, metamaskNetworkId: NETWORK_IDS.GOERLI, chainId: CHAIN_IDS.GOERLI, - status: TRANSACTION_STATUSES.FAILED, + status: TransactionStatus.failed, time: 4444000, txParams: { from: '0xa', @@ -1249,7 +1249,7 @@ describe('IncomingTransactionsController', function () { value: '0xf', }, hash: '0xg', - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, }); }); @@ -1285,7 +1285,7 @@ describe('IncomingTransactionsController', function () { id: 54321, metamaskNetworkId: NETWORK_IDS.GOERLI, chainId: CHAIN_IDS.GOERLI, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, time: 4444000, txParams: { from: '0xa', @@ -1296,7 +1296,7 @@ describe('IncomingTransactionsController', function () { value: '0xf', }, hash: '0xg', - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, }); }); @@ -1333,7 +1333,7 @@ describe('IncomingTransactionsController', function () { id: 54321, metamaskNetworkId: NETWORK_IDS.GOERLI, chainId: CHAIN_IDS.GOERLI, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, time: 4444000, txParams: { from: '0xa', @@ -1345,7 +1345,7 @@ describe('IncomingTransactionsController', function () { value: '0xf', }, hash: '0xg', - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, }); }); }); diff --git a/app/scripts/controllers/transactions/index.js b/app/scripts/controllers/transactions/index.js index 4c02f4374..c90f3c527 100644 --- a/app/scripts/controllers/transactions/index.js +++ b/app/scripts/controllers/transactions/index.js @@ -18,12 +18,12 @@ import { getChainType, } from '../../lib/util'; import { - TRANSACTION_STATUSES, - TRANSACTION_TYPES, - TRANSACTION_APPROVAL_AMOUNT_TYPE, - TOKEN_STANDARDS, - TRANSACTION_ENVELOPE_TYPES, - TRANSACTION_EVENTS, + TransactionStatus, + TransactionType, + TokenStandard, + TransactionEnvelopeType, + TransactionMetaMetricsEvent, + TransactionApprovalAmountType, } from '../../../../shared/constants/transaction'; import { METAMASK_CONTROLLER_EVENTS } from '../../metamask-controller'; import { @@ -65,23 +65,22 @@ const MAX_MEMSTORE_TX_LIST_SIZE = 100; // Number of transactions (by unique nonc const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000; const SWAP_TRANSACTION_TYPES = [ - TRANSACTION_TYPES.SWAP, - TRANSACTION_TYPES.SWAP_APPROVAL, + TransactionType.swap, + TransactionType.swapApproval, ]; // Only certain types of transactions should be allowed to be specified when // adding a new unapproved transaction. const VALID_UNAPPROVED_TRANSACTION_TYPES = [ ...SWAP_TRANSACTION_TYPES, - TRANSACTION_TYPES.SIMPLE_SEND, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, - TRANSACTION_TYPES.CONTRACT_INTERACTION, + TransactionType.simpleSend, + TransactionType.tokenMethodTransfer, + TransactionType.tokenMethodTransferFrom, + TransactionType.contractInteraction, ]; /** * @typedef {import('../../../../shared/constants/transaction').TransactionMeta} TransactionMeta - * @typedef {import('../../../../shared/constants/transaction').TransactionMetaMetricsEventString} TransactionMetaMetricsEventString */ const METRICS_STATUS_FAILED = 'failed on-chain'; @@ -309,7 +308,7 @@ export default class TransactionController extends EventEmitter { this.emit(`${txMeta.id}:unapproved`, txMeta); this._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.ADDED, + TransactionMetaMetricsEvent.added, txMeta.actionId, ); } @@ -349,9 +348,9 @@ export default class TransactionController extends EventEmitter { `${initialTxMeta.id}:finished`, (finishedTxMeta) => { switch (finishedTxMeta.status) { - case TRANSACTION_STATUSES.SUBMITTED: + case TransactionStatus.submitted: return resolve(finishedTxMeta.hash); - case TRANSACTION_STATUSES.REJECTED: + case TransactionStatus.rejected: return reject( cleanErrorStack( ethErrors.provider.userRejectedRequest( @@ -359,7 +358,7 @@ export default class TransactionController extends EventEmitter { ), ), ); - case TRANSACTION_STATUSES.FAILED: + case TransactionStatus.failed: return reject( cleanErrorStack( ethErrors.rpc.internal(finishedTxMeta.err.message), @@ -400,7 +399,7 @@ export default class TransactionController extends EventEmitter { _isUnapprovedTransaction(txId) { return ( this.txStateManager.getTransaction(txId).status === - TRANSACTION_STATUSES.UNAPPROVED + TransactionStatus.unapproved ); } @@ -872,7 +871,7 @@ export default class TransactionController extends EventEmitter { */ async addTxGasDefaults(txMeta, getCodeResponse) { const eip1559Compatibility = - txMeta.txParams.type !== TRANSACTION_ENVELOPE_TYPES.LEGACY && + txMeta.txParams.type !== TransactionEnvelopeType.legacy && (await this.getEIP1559Compatibility()); const { gasPrice: defaultGasPrice, @@ -1073,7 +1072,7 @@ export default class TransactionController extends EventEmitter { return {}; } else if ( txMeta.txParams.to && - txMeta.type === TRANSACTION_TYPES.SIMPLE_SEND && + txMeta.type === TransactionType.simpleSend && chainType !== 'custom' && !txMeta.txParams.data ) { @@ -1219,8 +1218,8 @@ export default class TransactionController extends EventEmitter { }, previousGasParams, loadingDefaults: false, - status: TRANSACTION_STATUSES.APPROVED, - type: TRANSACTION_TYPES.CANCEL, + status: TransactionStatus.approved, + type: TransactionType.cancel, actionId, }); @@ -1276,8 +1275,8 @@ export default class TransactionController extends EventEmitter { }, previousGasParams, loadingDefaults: false, - status: TRANSACTION_STATUSES.APPROVED, - type: TRANSACTION_TYPES.RETRY, + status: TransactionStatus.approved, + type: TransactionType.retry, originalType: originalTxMeta.type, actionId, }); @@ -1372,7 +1371,7 @@ export default class TransactionController extends EventEmitter { await this.publishTransaction(txId, rawTx, actionId); this._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.APPROVED, + TransactionMetaMetricsEvent.approved, actionId, ); // must set transaction to submitted/failed before releasing lock @@ -1443,8 +1442,8 @@ export default class TransactionController extends EventEmitter { // add network/chain id const chainId = this.getChainId(); const type = isEIP1559Transaction({ txParams: normalizedTxParams }) - ? TRANSACTION_ENVELOPE_TYPES.FEE_MARKET - : TRANSACTION_ENVELOPE_TYPES.LEGACY; + ? TransactionEnvelopeType.feeMarket + : TransactionEnvelopeType.legacy; const txParams = { ...normalizedTxParams, type, @@ -1472,8 +1471,8 @@ export default class TransactionController extends EventEmitter { // add network/chain id const chainId = this.getChainId(); const type = isEIP1559Transaction(txMeta) - ? TRANSACTION_ENVELOPE_TYPES.FEE_MARKET - : TRANSACTION_ENVELOPE_TYPES.LEGACY; + ? TransactionEnvelopeType.feeMarket + : TransactionEnvelopeType.legacy; const txParams = { ...txMeta.txParams, type, @@ -1514,7 +1513,7 @@ export default class TransactionController extends EventEmitter { async publishTransaction(txId, rawTx, actionId) { const txMeta = this.txStateManager.getTransaction(txId); txMeta.rawTx = rawTx; - if (txMeta.type === TRANSACTION_TYPES.SWAP) { + if (txMeta.type === TransactionType.swap) { const preTxBalance = await this.query.getBalance(txMeta.txParams.from); txMeta.preTxBalance = preTxBalance.toString(16); } @@ -1539,7 +1538,7 @@ export default class TransactionController extends EventEmitter { this._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.SUBMITTED, + TransactionMetaMetricsEvent.submitted, actionId, ); } @@ -1629,7 +1628,7 @@ export default class TransactionController extends EventEmitter { this._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.FINALIZED, + TransactionMetaMetricsEvent.finalized, undefined, metricsParams, ); @@ -1639,7 +1638,7 @@ export default class TransactionController extends EventEmitter { 'transactions#confirmTransaction - add txReceipt', ); - if (txMeta.type === TRANSACTION_TYPES.SWAP) { + if (txMeta.type === TransactionType.swap) { await this.updatePostTxBalance({ txMeta, txId, @@ -1690,7 +1689,7 @@ export default class TransactionController extends EventEmitter { this._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.FINALIZED, + TransactionMetaMetricsEvent.finalized, undefined, metricsParams, ); @@ -1700,7 +1699,7 @@ export default class TransactionController extends EventEmitter { 'transactions#confirmTransaction - add txReceipt', ); - if (txMeta.type === TRANSACTION_TYPES.SWAP) { + if (txMeta.type === TransactionType.swap) { await this.updatePostTxBalance({ txMeta, txId, @@ -1723,7 +1722,7 @@ export default class TransactionController extends EventEmitter { this.txStateManager.setTxStatusRejected(txId); this._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.REJECTED, + TransactionMetaMetricsEvent.rejected, actionId, ); } @@ -1747,7 +1746,7 @@ export default class TransactionController extends EventEmitter { * * @param {number} transactionId - The transaction id to create the event * fragment for - * @param {valueOf} event - event type to create + * @param {valueOf} event - event type to create * @param {string} actionId - actionId passed from UI */ async createTransactionEventFragment(transactionId, event, actionId) { @@ -1816,7 +1815,7 @@ export default class TransactionController extends EventEmitter { this.txStateManager .getTransactions({ searchCriteria: { - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, loadingDefaults: true, }, }) @@ -1843,7 +1842,7 @@ export default class TransactionController extends EventEmitter { this.txStateManager .getTransactions({ searchCriteria: { - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, }, }) .forEach((txMeta) => { @@ -1934,7 +1933,7 @@ export default class TransactionController extends EventEmitter { 'transactions/pending-tx-tracker#event: tx:confirmed reference to confirmed txHash with same nonce', ); // Drop any transaction that wasn't previously failed (off chain failure) - if (otherTxMeta.status !== TRANSACTION_STATUSES.FAILED) { + if (otherTxMeta.status !== TransactionStatus.failed) { this._dropTransaction(otherTxMeta.id); } }); @@ -2079,8 +2078,7 @@ export default class TransactionController extends EventEmitter { finalApprovalAmount, ) { if ( - transactionApprovalAmountType === - TRANSACTION_APPROVAL_AMOUNT_TYPE.CUSTOM && + transactionApprovalAmountType === TransactionApprovalAmountType.custom && originalApprovalAmount && finalApprovalAmount ) { @@ -2105,10 +2103,9 @@ export default class TransactionController extends EventEmitter { currentTokenBalance, ) { if ( - (transactionApprovalAmountType === - TRANSACTION_APPROVAL_AMOUNT_TYPE.CUSTOM || + (transactionApprovalAmountType === TransactionApprovalAmountType.custom || transactionApprovalAmountType === - TRANSACTION_APPROVAL_AMOUNT_TYPE.DAPP_PROPOSED) && + TransactionApprovalAmountType.dappProposed) && dappProposedTokenAmount && currentTokenBalance ) { @@ -2222,15 +2219,15 @@ export default class TransactionController extends EventEmitter { } const contractInteractionTypes = [ - TRANSACTION_TYPES.CONTRACT_INTERACTION, - TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, - TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM, - TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, - TRANSACTION_TYPES.SMART, - TRANSACTION_TYPES.SWAP, - TRANSACTION_TYPES.SWAP_APPROVAL, + TransactionType.contractInteraction, + TransactionType.tokenMethodApprove, + TransactionType.tokenMethodSafeTransferFrom, + TransactionType.tokenMethodSetApprovalForAll, + TransactionType.tokenMethodTransfer, + TransactionType.tokenMethodTransferFrom, + TransactionType.smart, + TransactionType.swap, + TransactionType.swapApproval, ].includes(type); const contractMethodNames = { @@ -2241,29 +2238,27 @@ export default class TransactionController extends EventEmitter { let transactionContractMethod; let transactionApprovalAmountVsProposedRatio; let transactionApprovalAmountVsBalanceRatio; - let transactionType = TRANSACTION_TYPES.SIMPLE_SEND; - if (type === TRANSACTION_TYPES.CANCEL) { - transactionType = TRANSACTION_TYPES.CANCEL; - } else if (type === TRANSACTION_TYPES.RETRY) { + let transactionType = TransactionType.simpleSend; + if (type === TransactionType.cancel) { + transactionType = TransactionType.cancel; + } else if (type === TransactionType.retry) { transactionType = originalType; - } else if (type === TRANSACTION_TYPES.DEPLOY_CONTRACT) { - transactionType = TRANSACTION_TYPES.DEPLOY_CONTRACT; + } else if (type === TransactionType.deployContract) { + transactionType = TransactionType.deployContract; } else if (contractInteractionTypes) { - transactionType = TRANSACTION_TYPES.CONTRACT_INTERACTION; + transactionType = TransactionType.contractInteraction; transactionContractMethod = contractMethodName; if ( transactionContractMethod === contractMethodNames.APPROVE && - tokenStandard === TOKEN_STANDARDS.ERC20 + tokenStandard === TokenStandard.ERC20 ) { if (dappProposedTokenAmount === '0' || customTokenAmount === '0') { - transactionApprovalAmountType = - TRANSACTION_APPROVAL_AMOUNT_TYPE.REVOKE; + transactionApprovalAmountType = TransactionApprovalAmountType.revoke; } else if (customTokenAmount) { - transactionApprovalAmountType = - TRANSACTION_APPROVAL_AMOUNT_TYPE.CUSTOM; + transactionApprovalAmountType = TransactionApprovalAmountType.custom; } else if (dappProposedTokenAmount) { transactionApprovalAmountType = - TRANSACTION_APPROVAL_AMOUNT_TYPE.DAPP_PROPOSED; + TransactionApprovalAmountType.dappProposed; } transactionApprovalAmountVsProposedRatio = this._allowanceAmountInRelationToDappProposedValue( @@ -2283,17 +2278,17 @@ export default class TransactionController extends EventEmitter { const replacedTxMeta = this._getTransaction(replacedById); const TRANSACTION_REPLACEMENT_METHODS = { - RETRY: TRANSACTION_TYPES.RETRY, - CANCEL: TRANSACTION_TYPES.CANCEL, + RETRY: TransactionType.retry, + CANCEL: TransactionType.cancel, SAME_NONCE: 'other', }; let transactionReplaced; if (extraParams?.dropped) { transactionReplaced = TRANSACTION_REPLACEMENT_METHODS.SAME_NONCE; - if (replacedTxMeta?.type === TRANSACTION_TYPES.CANCEL) { + if (replacedTxMeta?.type === TransactionType.cancel) { transactionReplaced = TRANSACTION_REPLACEMENT_METHODS.CANCEL; - } else if (replacedTxMeta?.type === TRANSACTION_TYPES.RETRY) { + } else if (replacedTxMeta?.type === TransactionType.retry) { transactionReplaced = TRANSACTION_REPLACEMENT_METHODS.RETRY; } } @@ -2311,7 +2306,7 @@ export default class TransactionController extends EventEmitter { asset_type: assetType, token_standard: tokenStandard, transaction_type: transactionType, - transaction_speed_up: type === TRANSACTION_TYPES.RETRY, + transaction_speed_up: type === TransactionType.retry, }; if (transactionContractMethod === contractMethodNames.APPROVE) { @@ -2354,7 +2349,7 @@ export default class TransactionController extends EventEmitter { * new event fragment is created with the appropriate payload. * * @param {TransactionMeta} txMeta - Transaction meta object - * @param {TransactionMetaMetricsEventString} event - The event type that + * @param {TransactionMetaMetricsEvent} event - The event type that * triggered fragment creation * @param {object} properties - properties to include in the fragment * @param {object} [sensitiveProperties] - sensitive properties to include in @@ -2369,8 +2364,8 @@ export default class TransactionController extends EventEmitter { actionId, ) { const isSubmitted = [ - TRANSACTION_EVENTS.FINALIZED, - TRANSACTION_EVENTS.SUBMITTED, + TransactionMetaMetricsEvent.finalized, + TransactionMetaMetricsEvent.submitted, ].includes(event); const uniqueIdentifier = `transaction-${ isSubmitted ? 'submitted' : 'added' @@ -2391,12 +2386,12 @@ export default class TransactionController extends EventEmitter { // edits the transactions gas params we can record that property and // then get analytics on the number of transactions in which gas edits // occur. - case TRANSACTION_EVENTS.ADDED: + case TransactionMetaMetricsEvent.added: this.createEventFragment({ category: EVENT.CATEGORIES.TRANSACTIONS, - initialEvent: TRANSACTION_EVENTS.ADDED, - successEvent: TRANSACTION_EVENTS.APPROVED, - failureEvent: TRANSACTION_EVENTS.REJECTED, + initialEvent: TransactionMetaMetricsEvent.added, + successEvent: TransactionMetaMetricsEvent.approved, + failureEvent: TransactionMetaMetricsEvent.rejected, properties, sensitiveProperties, persist: true, @@ -2412,12 +2407,12 @@ export default class TransactionController extends EventEmitter { // includes this change. A migration would have also helped here but this // implementation hardens against other possible bugs where a fragment // does not exist. - case TRANSACTION_EVENTS.APPROVED: - case TRANSACTION_EVENTS.REJECTED: + case TransactionMetaMetricsEvent.approved: + case TransactionMetaMetricsEvent.rejected: this.createEventFragment({ category: EVENT.CATEGORIES.TRANSACTIONS, - successEvent: TRANSACTION_EVENTS.APPROVED, - failureEvent: TRANSACTION_EVENTS.REJECTED, + successEvent: TransactionMetaMetricsEvent.approved, + failureEvent: TransactionMetaMetricsEvent.rejected, properties, sensitiveProperties, persist: true, @@ -2435,11 +2430,11 @@ export default class TransactionController extends EventEmitter { // supplemental data to show user intent. Such as when they open the // cancel UI but don't submit. We can record that this happened and add // properties to the transaction event. - case TRANSACTION_EVENTS.SUBMITTED: + case TransactionMetaMetricsEvent.submitted: this.createEventFragment({ category: EVENT.CATEGORIES.TRANSACTIONS, - initialEvent: TRANSACTION_EVENTS.SUBMITTED, - successEvent: TRANSACTION_EVENTS.FINALIZED, + initialEvent: TransactionMetaMetricsEvent.submitted, + successEvent: TransactionMetaMetricsEvent.finalized, properties, sensitiveProperties, persist: true, @@ -2455,10 +2450,10 @@ export default class TransactionController extends EventEmitter { // that includes this change. A migration would have also helped here but // this implementation hardens against other possible bugs where a // fragment does not exist. - case TRANSACTION_EVENTS.FINALIZED: + case TransactionMetaMetricsEvent.finalized: this.createEventFragment({ category: EVENT.CATEGORIES.TRANSACTIONS, - successEvent: TRANSACTION_EVENTS.FINALIZED, + successEvent: TransactionMetaMetricsEvent.finalized, properties, sensitiveProperties, persist: true, @@ -2477,7 +2472,7 @@ export default class TransactionController extends EventEmitter { * events. * * @param {object} txMeta - the txMeta object - * @param {TransactionMetaMetricsEventString} event - the name of the transaction event + * @param {TransactionMetaMetricsEvent} event - the name of the transaction event * @param {string} actionId - actionId passed from UI * @param {object} extraParams - optional props and values to include in sensitiveProperties */ @@ -2508,14 +2503,14 @@ export default class TransactionController extends EventEmitter { switch (event) { // If the user approves a transaction, finalize the transaction added // event fragment. - case TRANSACTION_EVENTS.APPROVED: + case TransactionMetaMetricsEvent.approved: id = `transaction-added-${txMeta.id}`; this.updateEventFragment(id, { properties, sensitiveProperties }); this.finalizeEventFragment(id); break; // If the user rejects a transaction, finalize the transaction added // event fragment. with the abandoned flag set. - case TRANSACTION_EVENTS.REJECTED: + case TransactionMetaMetricsEvent.rejected: id = `transaction-added-${txMeta.id}`; this.updateEventFragment(id, { properties, sensitiveProperties }); this.finalizeEventFragment(id, { @@ -2524,7 +2519,7 @@ export default class TransactionController extends EventEmitter { break; // When a transaction is finalized, also finalize the transaction // submitted event fragment. - case TRANSACTION_EVENTS.FINALIZED: + case TransactionMetaMetricsEvent.finalized: id = `transaction-submitted-${txMeta.id}`; this.updateEventFragment(id, { properties, sensitiveProperties }); this.finalizeEventFragment(`transaction-submitted-${txMeta.id}`); @@ -2555,7 +2550,7 @@ export default class TransactionController extends EventEmitter { const txMeta = this.txStateManager.getTransaction(txId); this._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.FINALIZED, + TransactionMetaMetricsEvent.finalized, actionId, { error: error.message, @@ -2568,7 +2563,7 @@ export default class TransactionController extends EventEmitter { const txMeta = this.txStateManager.getTransaction(txId); this._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.FINALIZED, + TransactionMetaMetricsEvent.finalized, undefined, { dropped: true, diff --git a/app/scripts/controllers/transactions/index.test.js b/app/scripts/controllers/transactions/index.test.js index db0c6a496..d0f149686 100644 --- a/app/scripts/controllers/transactions/index.test.js +++ b/app/scripts/controllers/transactions/index.test.js @@ -12,12 +12,12 @@ import { import mockEstimates from '../../../../test/data/mock-estimates.json'; import { EVENT } from '../../../../shared/constants/metametrics'; import { - TRANSACTION_STATUSES, - TRANSACTION_TYPES, - TRANSACTION_ENVELOPE_TYPES, - TRANSACTION_EVENTS, - ASSET_TYPES, - TOKEN_STANDARDS, + TransactionStatus, + TransactionType, + TransactionEnvelopeType, + TransactionMetaMetricsEvent, + AssetType, + TokenStandard, } from '../../../../shared/constants/transaction'; import { SECOND } from '../../../../shared/constants/time'; @@ -128,7 +128,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -138,7 +138,7 @@ describe('Transaction Controller', function () { }, { id: 2, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -148,7 +148,7 @@ describe('Transaction Controller', function () { }, { id: 3, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -167,7 +167,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -177,7 +177,7 @@ describe('Transaction Controller', function () { }, { id: 2, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -187,7 +187,7 @@ describe('Transaction Controller', function () { }, { id: 3, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -211,63 +211,63 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 0, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, txParams, history: [{}], }, { id: 1, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, txParams, history: [{}], }, { id: 2, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, txParams, history: [{}], }, { id: 3, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams, history: [{}], }, { id: 4, - status: TRANSACTION_STATUSES.REJECTED, + status: TransactionStatus.rejected, metamaskNetworkId: currentNetworkId, txParams, history: [{}], }, { id: 5, - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: currentNetworkId, txParams, history: [{}], }, { id: 6, - status: TRANSACTION_STATUSES.SIGNED, + status: TransactionStatus.signed, metamaskNetworkId: currentNetworkId, txParams, history: [{}], }, { id: 7, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, txParams, history: [{}], }, { id: 8, - status: TRANSACTION_STATUSES.FAILED, + status: TransactionStatus.failed, metamaskNetworkId: currentNetworkId, txParams, history: [{}], @@ -288,7 +288,7 @@ describe('Transaction Controller', function () { to: '0xc684832530fcbddae4b4230a47e991ddcec2831d', }; txMeta = { - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, id: 1, metamaskNetworkId: currentNetworkId, txParams, @@ -520,7 +520,7 @@ describe('Transaction Controller', function () { {}, { actionId: 12345 }, ); - assert.equal(cancelTxMeta.type, TRANSACTION_TYPES.CANCEL); + assert.equal(cancelTxMeta.type, TransactionType.cancel); const memTxMeta = txController.txStateManager.getTransaction( cancelTxMeta.id, ); @@ -579,7 +579,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -629,7 +629,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -679,7 +679,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -729,12 +729,12 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, }, history: [{}], }, @@ -744,7 +744,7 @@ describe('Transaction Controller', function () { txParams: { from: '0xc684832530fcbddae4b4230a47e991ddcec2831d', to: '0xc684832530fcbddae4b4230a47e991ddcec2831d', - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, }, history: [{}], }; @@ -783,7 +783,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -912,7 +912,7 @@ describe('Transaction Controller', function () { it('should emit updates', function (done) { const txMeta = { id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -950,7 +950,7 @@ describe('Transaction Controller', function () { it('should call _trackTransactionMetricsEvent with the correct params', function () { const txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: fromAccount.address, to: '0x1678a085c290ebd122dc42cba69373b5953b831d', @@ -958,7 +958,7 @@ describe('Transaction Controller', function () { gas: '0x7b0d', nonce: '0x4b', }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, transaction_envelope_type: TRANSACTION_ENVELOPE_TYPE_NAMES.LEGACY, origin: ORIGIN_METAMASK, chainId: currentChainId, @@ -975,7 +975,7 @@ describe('Transaction Controller', function () { ); assert.equal( trackTransactionMetricsEventSpy.getCall(0).args[1], - TRANSACTION_EVENTS.ADDED, + TransactionMetaMetricsEvent.added, ); }); }); @@ -985,7 +985,7 @@ describe('Transaction Controller', function () { const originalValue = '0x01'; const txMeta = { id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS_TWO, @@ -1023,7 +1023,7 @@ describe('Transaction Controller', function () { assert.equal(result.hash, originalValue); assert.equal( result.status, - TRANSACTION_STATUSES.SUBMITTED, + TransactionStatus.submitted, 'should have reached the submitted status.', ); signStub.restore(); @@ -1036,7 +1036,7 @@ describe('Transaction Controller', function () { txController.addTransaction( { id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1055,7 +1055,7 @@ describe('Transaction Controller', function () { it('should update and approve transactions', async function () { const txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: fromAccount.address, to: '0x1678a085c290ebd122dc42cba69373b5953b831d', @@ -1068,7 +1068,7 @@ describe('Transaction Controller', function () { txController.txStateManager.addTransaction(txMeta); const approvalPromise = txController.updateAndApproveTransaction(txMeta); const tx = txController.txStateManager.getTransaction(1); - assert.equal(tx.status, TRANSACTION_STATUSES.APPROVED); + assert.equal(tx.status, TransactionStatus.approved); await approvalPromise; }); }); @@ -1085,7 +1085,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 0, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, @@ -1095,7 +1095,7 @@ describe('Transaction Controller', function () { }, { id: 1, - status: TRANSACTION_STATUSES.REJECTED, + status: TransactionStatus.rejected, txParams: { to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, @@ -1105,7 +1105,7 @@ describe('Transaction Controller', function () { }, { id: 2, - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, txParams: { to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, @@ -1115,7 +1115,7 @@ describe('Transaction Controller', function () { }, { id: 3, - status: TRANSACTION_STATUSES.SIGNED, + status: TransactionStatus.signed, txParams: { to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, @@ -1125,7 +1125,7 @@ describe('Transaction Controller', function () { }, { id: 4, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, txParams: { to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, @@ -1135,7 +1135,7 @@ describe('Transaction Controller', function () { }, { id: 5, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, @@ -1145,7 +1145,7 @@ describe('Transaction Controller', function () { }, { id: 6, - status: TRANSACTION_STATUSES.FAILED, + status: TransactionStatus.failed, txParams: { to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, @@ -1159,7 +1159,7 @@ describe('Transaction Controller', function () { try { assert.equal( status, - TRANSACTION_STATUSES.REJECTED, + TransactionStatus.rejected, 'status should be rejected', ); assert.equal(txId, 0, 'id should e 0'); @@ -1219,7 +1219,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, txParams, history: [{}], @@ -1250,7 +1250,7 @@ describe('Transaction Controller', function () { { gasPrice: previousGasParams.gasPrice, type }, { gasPrice: '0xa', - type: TRANSACTION_TYPES.RETRY, + type: TransactionType.retry, }, ); }); @@ -1273,7 +1273,7 @@ describe('Transaction Controller', function () { { gasPrice: previousGasParams.gasPrice, type }, { gasPrice: '0xa', - type: TRANSACTION_TYPES.RETRY, + type: TransactionType.retry, }, ); }); @@ -1339,7 +1339,7 @@ describe('Transaction Controller', function () { it('sets txParams.type to 0x0 (non-EIP-1559)', async function () { txController.txStateManager._addTransactionsToState([ { - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, id: 1, metamaskNetworkId: currentNetworkId, history: [{}], @@ -1362,7 +1362,7 @@ describe('Transaction Controller', function () { .returns(true); txController.txStateManager._addTransactionsToState([ { - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, id: 2, metamaskNetworkId: currentNetworkId, history: [{}], @@ -1390,7 +1390,7 @@ describe('Transaction Controller', function () { '0x2a5523c6fa98b47b7d9b6c8320179785150b42a16bcff36b398c5062b65657e8'; txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { gas: '0x7b0d', to: VALID_ADDRESS, @@ -1416,7 +1416,7 @@ describe('Transaction Controller', function () { await txController.publishTransaction(txMeta.id, rawTx); const publishedTx = txController.txStateManager.getTransaction(1); assert.equal(publishedTx.hash, hash); - assert.equal(publishedTx.status, TRANSACTION_STATUSES.SUBMITTED); + assert.equal(publishedTx.status, TransactionStatus.submitted); }); it('should ignore the error "Transaction Failed: known transaction" and be as usual', async function () { @@ -1432,7 +1432,7 @@ describe('Transaction Controller', function () { publishedTx.hash, '0x2cc5a25744486f7383edebbf32003e5a66e18135799593d6b5cdd2bb43674f09', ); - assert.equal(publishedTx.status, TRANSACTION_STATUSES.SUBMITTED); + assert.equal(publishedTx.status, TransactionStatus.submitted); }); it('should call _trackTransactionMetricsEvent with the correct params', async function () { @@ -1447,7 +1447,7 @@ describe('Transaction Controller', function () { ); assert.equal( trackTransactionMetricsEventSpy.getCall(0).args[1], - TRANSACTION_EVENTS.SUBMITTED, + TransactionMetaMetricsEvent.submitted, ); }); }); @@ -1457,7 +1457,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, history: [{}], txParams: { @@ -1468,7 +1468,7 @@ describe('Transaction Controller', function () { }, { id: 2, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, history: [{}], txParams: { @@ -1479,7 +1479,7 @@ describe('Transaction Controller', function () { }, { id: 3, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, history: [{}], txParams: { @@ -1490,7 +1490,7 @@ describe('Transaction Controller', function () { }, { id: 4, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, history: [{}], txParams: { @@ -1501,7 +1501,7 @@ describe('Transaction Controller', function () { }, { id: 5, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, history: [{}], txParams: { @@ -1512,7 +1512,7 @@ describe('Transaction Controller', function () { }, { id: 6, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, history: [{}], txParams: { @@ -1523,7 +1523,7 @@ describe('Transaction Controller', function () { }, { id: 7, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, history: [{}], txParams: { @@ -1538,12 +1538,12 @@ describe('Transaction Controller', function () { const droppedTxs = txController.txStateManager.getTransactions({ searchCriteria: { nonce: '0x01', - status: TRANSACTION_STATUSES.DROPPED, + status: TransactionStatus.dropped, }, }); assert.equal( confirmedTx.status, - TRANSACTION_STATUSES.CONFIRMED, + TransactionStatus.confirmed, 'the confirmedTx should remain confirmed', ); assert.equal(droppedTxs.length, 6, 'their should be 6 dropped txs'); @@ -1555,7 +1555,7 @@ describe('Transaction Controller', function () { txController.txStateManager._addTransactionsToState([ { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1564,7 +1564,7 @@ describe('Transaction Controller', function () { }, { id: 2, - status: TRANSACTION_STATUSES.REJECTED, + status: TransactionStatus.rejected, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1574,7 +1574,7 @@ describe('Transaction Controller', function () { }, { id: 3, - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1584,7 +1584,7 @@ describe('Transaction Controller', function () { }, { id: 4, - status: TRANSACTION_STATUSES.SIGNED, + status: TransactionStatus.signed, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1594,7 +1594,7 @@ describe('Transaction Controller', function () { }, { id: 5, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1604,7 +1604,7 @@ describe('Transaction Controller', function () { }, { id: 6, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1614,7 +1614,7 @@ describe('Transaction Controller', function () { }, { id: 7, - status: TRANSACTION_STATUSES.FAILED, + status: TransactionStatus.failed, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1632,11 +1632,11 @@ describe('Transaction Controller', function () { .getPendingTransactions() .map((tx) => tx.status); assert.ok( - states.includes(TRANSACTION_STATUSES.APPROVED), + states.includes(TransactionStatus.approved), 'includes approved', ); assert.ok( - states.includes(TRANSACTION_STATUSES.SUBMITTED), + states.includes(TransactionStatus.submitted), 'includes submitted', ); }); @@ -1677,7 +1677,7 @@ describe('Transaction Controller', function () { before(function () { txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: fromAccount.address, to: '0x1678a085c290ebd122dc42cba69373b5953b831d', @@ -1685,7 +1685,7 @@ describe('Transaction Controller', function () { gas: '0x7b0d', nonce: '0x4b', }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, origin: ORIGIN_METAMASK, chainId: currentChainId, time: 1624408066355, @@ -1714,10 +1714,10 @@ describe('Transaction Controller', function () { network: '5', referrer: ORIGIN_METAMASK, source: EVENT.SOURCE.TRANSACTION.USER, - transaction_type: TRANSACTION_TYPES.SIMPLE_SEND, + transaction_type: TransactionType.simpleSend, account_type: 'MetaMask', - asset_type: ASSET_TYPES.NATIVE, - token_standard: TOKEN_STANDARDS.NONE, + asset_type: AssetType.native, + token_standard: TokenStandard.none, device_model: 'N/A', transaction_speed_up: false, }, @@ -1736,7 +1736,7 @@ describe('Transaction Controller', function () { await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.ADDED, + TransactionMetaMetricsEvent.added, actionId, ); assert.equal(createEventFragmentSpy.callCount, 1); @@ -1751,7 +1751,7 @@ describe('Transaction Controller', function () { fragmentExists = true; await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.REJECTED, + TransactionMetaMetricsEvent.rejected, actionId, ); assert.equal(createEventFragmentSpy.callCount, 0); @@ -1769,7 +1769,7 @@ describe('Transaction Controller', function () { fragmentExists = true; await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.APPROVED, + TransactionMetaMetricsEvent.approved, actionId, ); assert.equal(createEventFragmentSpy.callCount, 0); @@ -1800,10 +1800,10 @@ describe('Transaction Controller', function () { network: '5', referrer: ORIGIN_METAMASK, source: EVENT.SOURCE.TRANSACTION.USER, - transaction_type: TRANSACTION_TYPES.SIMPLE_SEND, + transaction_type: TransactionType.simpleSend, account_type: 'MetaMask', - asset_type: ASSET_TYPES.NATIVE, - token_standard: TOKEN_STANDARDS.NONE, + asset_type: AssetType.native, + token_standard: TokenStandard.none, device_model: 'N/A', transaction_speed_up: false, }, @@ -1822,7 +1822,7 @@ describe('Transaction Controller', function () { await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.SUBMITTED, + TransactionMetaMetricsEvent.submitted, actionId, ); assert.equal(createEventFragmentSpy.callCount, 1); @@ -1837,7 +1837,7 @@ describe('Transaction Controller', function () { fragmentExists = true; await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.FINALIZED, + TransactionMetaMetricsEvent.finalized, actionId, ); assert.equal(createEventFragmentSpy.callCount, 0); @@ -1858,7 +1858,7 @@ describe('Transaction Controller', function () { before(function () { txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: fromAccount.address, to: '0x1678a085c290ebd122dc42cba69373b5953b831d', @@ -1866,7 +1866,7 @@ describe('Transaction Controller', function () { gas: '0x7b0d', nonce: '0x4b', }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, origin: 'other', chainId: currentChainId, time: 1624408066355, @@ -1895,10 +1895,10 @@ describe('Transaction Controller', function () { network: '5', referrer: 'other', source: EVENT.SOURCE.TRANSACTION.DAPP, - transaction_type: TRANSACTION_TYPES.SIMPLE_SEND, + transaction_type: TransactionType.simpleSend, account_type: 'MetaMask', - asset_type: ASSET_TYPES.NATIVE, - token_standard: TOKEN_STANDARDS.NONE, + asset_type: AssetType.native, + token_standard: TokenStandard.none, device_model: 'N/A', transaction_speed_up: false, }, @@ -1917,7 +1917,7 @@ describe('Transaction Controller', function () { await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.ADDED, + TransactionMetaMetricsEvent.added, actionId, ); assert.equal(createEventFragmentSpy.callCount, 1); @@ -1933,7 +1933,7 @@ describe('Transaction Controller', function () { await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.REJECTED, + TransactionMetaMetricsEvent.rejected, actionId, ); assert.equal(createEventFragmentSpy.callCount, 0); @@ -1952,7 +1952,7 @@ describe('Transaction Controller', function () { await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.APPROVED, + TransactionMetaMetricsEvent.approved, actionId, ); assert.equal(createEventFragmentSpy.callCount, 0); @@ -1983,10 +1983,10 @@ describe('Transaction Controller', function () { network: '5', referrer: 'other', source: EVENT.SOURCE.TRANSACTION.DAPP, - transaction_type: TRANSACTION_TYPES.SIMPLE_SEND, + transaction_type: TransactionType.simpleSend, account_type: 'MetaMask', - asset_type: ASSET_TYPES.NATIVE, - token_standard: TOKEN_STANDARDS.NONE, + asset_type: AssetType.native, + token_standard: TokenStandard.none, device_model: 'N/A', transaction_speed_up: false, }, @@ -2005,7 +2005,7 @@ describe('Transaction Controller', function () { await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.SUBMITTED, + TransactionMetaMetricsEvent.submitted, actionId, ); assert.equal(createEventFragmentSpy.callCount, 1); @@ -2021,7 +2021,7 @@ describe('Transaction Controller', function () { await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.FINALIZED, + TransactionMetaMetricsEvent.finalized, actionId, ); assert.equal(createEventFragmentSpy.callCount, 0); @@ -2040,7 +2040,7 @@ describe('Transaction Controller', function () { it('should create missing fragments when events happen out of order or are missing', async function () { const txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: fromAccount.address, to: '0x1678a085c290ebd122dc42cba69373b5953b831d', @@ -2048,7 +2048,7 @@ describe('Transaction Controller', function () { gas: '0x7b0d', nonce: '0x4b', }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, origin: 'other', chainId: currentChainId, time: 1624408066355, @@ -2070,10 +2070,10 @@ describe('Transaction Controller', function () { network: '5', referrer: 'other', source: EVENT.SOURCE.TRANSACTION.DAPP, - transaction_type: TRANSACTION_TYPES.SIMPLE_SEND, + transaction_type: TransactionType.simpleSend, account_type: 'MetaMask', - asset_type: ASSET_TYPES.NATIVE, - token_standard: TOKEN_STANDARDS.NONE, + asset_type: AssetType.native, + token_standard: TokenStandard.none, device_model: 'N/A', transaction_speed_up: false, }, @@ -2089,7 +2089,7 @@ describe('Transaction Controller', function () { }; await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.APPROVED, + TransactionMetaMetricsEvent.approved, actionId, ); assert.equal(createEventFragmentSpy.callCount, 1); @@ -2108,7 +2108,7 @@ describe('Transaction Controller', function () { it('should call _trackMetaMetricsEvent with the correct payload (extra params)', async function () { const txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: fromAccount.address, to: '0x1678a085c290ebd122dc42cba69373b5953b831d', @@ -2116,7 +2116,7 @@ describe('Transaction Controller', function () { gas: '0x7b0d', nonce: '0x4b', }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, origin: 'other', chainId: currentChainId, time: 1624408066355, @@ -2134,14 +2134,14 @@ describe('Transaction Controller', function () { network: '5', referrer: 'other', source: EVENT.SOURCE.TRANSACTION.DAPP, - transaction_type: TRANSACTION_TYPES.SIMPLE_SEND, + transaction_type: TransactionType.simpleSend, chain_id: '0x5', eip_1559_version: '0', gas_edit_attempted: 'none', gas_edit_type: 'none', account_type: 'MetaMask', - asset_type: ASSET_TYPES.NATIVE, - token_standard: TOKEN_STANDARDS.NONE, + asset_type: AssetType.native, + token_standard: TokenStandard.none, device_model: 'N/A', transaction_speed_up: false, }, @@ -2160,7 +2160,7 @@ describe('Transaction Controller', function () { await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.ADDED, + TransactionMetaMetricsEvent.added, actionId, { baz: 3.0, @@ -2178,7 +2178,7 @@ describe('Transaction Controller', function () { it('should call _trackMetaMetricsEvent with the correct payload (EIP-1559)', async function () { const txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: fromAccount.address, to: '0x1678a085c290ebd122dc42cba69373b5953b831d', @@ -2189,7 +2189,7 @@ describe('Transaction Controller', function () { estimateSuggested: GAS_RECOMMENDATIONS.MEDIUM, estimateUsed: GAS_RECOMMENDATIONS.HIGH, }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, origin: 'other', chainId: currentChainId, time: 1624408066355, @@ -2216,10 +2216,10 @@ describe('Transaction Controller', function () { network: '5', referrer: 'other', source: EVENT.SOURCE.TRANSACTION.DAPP, - transaction_type: TRANSACTION_TYPES.SIMPLE_SEND, + transaction_type: TransactionType.simpleSend, account_type: 'MetaMask', - asset_type: ASSET_TYPES.NATIVE, - token_standard: TOKEN_STANDARDS.NONE, + asset_type: AssetType.native, + token_standard: TokenStandard.none, device_model: 'N/A', transaction_speed_up: false, }, @@ -2244,7 +2244,7 @@ describe('Transaction Controller', function () { await txController._trackTransactionMetricsEvent( txMeta, - TRANSACTION_EVENTS.ADDED, + TransactionMetaMetricsEvent.added, actionId, { baz: 3.0, @@ -2334,7 +2334,7 @@ describe('Transaction Controller', function () { txStateManager = txController.txStateManager; txStateManager.addTransaction({ id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { gasLimit: '0x001', @@ -2374,7 +2374,7 @@ describe('Transaction Controller', function () { // test update maxPriorityFeePerGas txStateManager.addTransaction({ id: '2', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { maxPriorityFeePerGas: '0x003', @@ -2392,7 +2392,7 @@ describe('Transaction Controller', function () { // test update maxFeePerGas txStateManager.addTransaction({ id: '3', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { maxPriorityFeePerGas: '0x003', @@ -2474,7 +2474,7 @@ describe('Transaction Controller', function () { it('should not update and should throw error if status is not type "unapproved"', function () { txStateManager.addTransaction({ id: '4', - status: TRANSACTION_STATUSES.DROPPED, + status: TransactionStatus.dropped, metamaskNetworkId: currentNetworkId, txParams: { maxPriorityFeePerGas: '0x007', @@ -2492,7 +2492,7 @@ describe('Transaction Controller', function () { }), Error, `TransactionsController: Can only call updateTransactionGasFees on an unapproved transaction. - Current tx status: ${TRANSACTION_STATUSES.DROPPED}`, + Current tx status: ${TransactionStatus.dropped}`, ); const transaction = txStateManager.getTransaction('4'); @@ -2536,7 +2536,7 @@ describe('Transaction Controller', function () { txStateManager = txController.txStateManager; txStateManager.addTransaction({ id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { gas: '0x001', @@ -2567,14 +2567,14 @@ describe('Transaction Controller', function () { result.txParams.data, '0xa9059cbb000000000000000000000000e18035bf8712672935fdb4e5e431b1a0183d2dfc0000000000000000000000000000000000000000000000000de0b6b3a7640000', ); - assert.equal(result.type, TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER); + assert.equal(result.type, TransactionType.tokenMethodTransfer); }); it('updates editible params when type changes from token transfer to simple send', async function () { // test update gasFees txStateManager.addTransaction({ id: '2', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { gas: '0x001', @@ -2589,7 +2589,7 @@ describe('Transaction Controller', function () { estimateUsed: '0x005', estimatedBaseFee: '0x006', decEstimatedBaseFee: '6', - type: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + type: TransactionType.tokenMethodTransfer, userEditedGasLimit: '0x008', userFeeLevel: 'medium', }); @@ -2598,14 +2598,14 @@ describe('Transaction Controller', function () { }); const result = txStateManager.getTransaction('2'); assert.equal(result.txParams.data, '0x'); - assert.equal(result.type, TRANSACTION_TYPES.SIMPLE_SEND); + assert.equal(result.type, TransactionType.simpleSend); }); it('updates editible params when type changes from simpleSend to contract interaction', async function () { // test update gasFees txStateManager.addTransaction({ id: '3', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { gas: '0x001', @@ -2619,7 +2619,7 @@ describe('Transaction Controller', function () { estimateUsed: '0x005', estimatedBaseFee: '0x006', decEstimatedBaseFee: '6', - type: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + type: TransactionType.tokenMethodTransfer, userEditedGasLimit: '0x008', userFeeLevel: 'medium', }); @@ -2629,7 +2629,7 @@ describe('Transaction Controller', function () { }); const result = txStateManager.getTransaction('3'); assert.equal(result.txParams.data, '0x123'); - assert.equal(result.type, TRANSACTION_TYPES.CONTRACT_INTERACTION); + assert.equal(result.type, TransactionType.contractInteraction); }); it('updates editible params when type does not change', async function () { @@ -2645,7 +2645,7 @@ describe('Transaction Controller', function () { assert.equal(result.txParams.from, VALID_ADDRESS_TWO); assert.equal(result.txParams.to, VALID_ADDRESS); assert.equal(result.txParams.gasPrice, '0x002'); - assert.equal(result.type, TRANSACTION_TYPES.SIMPLE_SEND); + assert.equal(result.type, TransactionType.simpleSend); }); }); }); diff --git a/app/scripts/controllers/transactions/lib/util.js b/app/scripts/controllers/transactions/lib/util.js index 328703138..2aac34fad 100644 --- a/app/scripts/controllers/transactions/lib/util.js +++ b/app/scripts/controllers/transactions/lib/util.js @@ -1,8 +1,8 @@ import { ethErrors } from 'eth-rpc-errors'; import { addHexPrefix } from '../../../lib/util'; import { - TRANSACTION_ENVELOPE_TYPES, - TRANSACTION_STATUSES, + TransactionEnvelopeType, + TransactionStatus, } from '../../../../../shared/constants/transaction'; import { isEIP1559Transaction } from '../../../../../shared/modules/transaction.utils'; import { isValidHexAddress } from '../../../../../shared/modules/hexstring-utils'; @@ -103,10 +103,10 @@ function ensureProperTransactionEnvelopeTypeProvided(txParams, field) { case 'maxPriorityFeePerGas': if ( txParams.type && - txParams.type !== TRANSACTION_ENVELOPE_TYPES.FEE_MARKET + txParams.type !== TransactionEnvelopeType.feeMarket ) { throw ethErrors.rpc.invalidParams( - `Invalid transaction envelope type: specified type "${txParams.type}" but including maxFeePerGas and maxPriorityFeePerGas requires type: "${TRANSACTION_ENVELOPE_TYPES.FEE_MARKET}"`, + `Invalid transaction envelope type: specified type "${txParams.type}" but including maxFeePerGas and maxPriorityFeePerGas requires type: "${TransactionEnvelopeType.feeMarket}"`, ); } break; @@ -114,7 +114,7 @@ function ensureProperTransactionEnvelopeTypeProvided(txParams, field) { default: if ( txParams.type && - txParams.type === TRANSACTION_ENVELOPE_TYPES.FEE_MARKET + txParams.type === TransactionEnvelopeType.feeMarket ) { throw ethErrors.rpc.invalidParams( `Invalid transaction envelope type: specified type "${txParams.type}" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`, @@ -274,7 +274,7 @@ export const validateConfirmedExternalTransaction = ({ '"txMeta" or "txMeta.txParams" is missing', ); } - if (txMeta.status !== TRANSACTION_STATUSES.CONFIRMED) { + if (txMeta.status !== TransactionStatus.confirmed) { throw ethErrors.rpc.invalidParams( 'External transaction status should be "confirmed"', ); @@ -309,10 +309,10 @@ export const validateConfirmedExternalTransaction = ({ */ export function getFinalStates() { return [ - TRANSACTION_STATUSES.REJECTED, // the user has responded no! - TRANSACTION_STATUSES.CONFIRMED, // the tx has been included in a block. - TRANSACTION_STATUSES.FAILED, // the tx failed for some reason, included on tx data. - TRANSACTION_STATUSES.DROPPED, // the tx nonce was already used + TransactionStatus.rejected, // the user has responded no! + TransactionStatus.confirmed, // the tx has been included in a block. + TransactionStatus.failed, // the tx failed for some reason, included on tx data. + TransactionStatus.dropped, // the tx nonce was already used ]; } diff --git a/app/scripts/controllers/transactions/lib/util.test.js b/app/scripts/controllers/transactions/lib/util.test.js index 6c162ef4e..1aaf81ccf 100644 --- a/app/scripts/controllers/transactions/lib/util.test.js +++ b/app/scripts/controllers/transactions/lib/util.test.js @@ -1,5 +1,5 @@ import { strict as assert } from 'assert'; -import { TRANSACTION_ENVELOPE_TYPES } from '../../../../../shared/constants/transaction'; +import { TransactionEnvelopeType } from '../../../../../shared/constants/transaction'; import { BURN_ADDRESS } from '../../../../../shared/modules/hexstring-utils'; import { GAS_RECOMMENDATIONS } from '../../../../../shared/constants/gas'; import * as txUtils from './util'; @@ -56,7 +56,7 @@ describe('txUtils', function () { it('should error when specifying incorrect type', function () { const txParams = { gasPrice: '0x1', - type: TRANSACTION_ENVELOPE_TYPES.FEE_MARKET, + type: TransactionEnvelopeType.feeMarket, to: BURN_ADDRESS, }; @@ -134,7 +134,7 @@ describe('txUtils', function () { it('should validate if gasPrice is set with a type of "0x0"', function () { const txParams = { gasPrice: '0x1', - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, to: BURN_ADDRESS, }; assert.doesNotThrow(() => txUtils.validateTxParams(txParams)); @@ -145,7 +145,7 @@ describe('txUtils', function () { it('should error when specifying incorrect type', function () { const txParams = { maxFeePerGas: '0x1', - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, to: BURN_ADDRESS, }; @@ -206,7 +206,7 @@ describe('txUtils', function () { it('should validate if maxFeePerGas is set with a type of "0x2"', function () { const txParams = { maxFeePerGas: '0x1', - type: TRANSACTION_ENVELOPE_TYPES.FEE_MARKET, + type: TransactionEnvelopeType.feeMarket, to: BURN_ADDRESS, }; assert.doesNotThrow(() => txUtils.validateTxParams(txParams)); @@ -217,7 +217,7 @@ describe('txUtils', function () { it('should error when specifying incorrect type', function () { const txParams = { maxPriorityFeePerGas: '0x1', - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, to: BURN_ADDRESS, }; @@ -278,7 +278,7 @@ describe('txUtils', function () { it('should validate if maxPriorityFeePerGas is set with a type of "0x2"', function () { const txParams = { maxPriorityFeePerGas: '0x1', - type: TRANSACTION_ENVELOPE_TYPES.FEE_MARKET, + type: TransactionEnvelopeType.feeMarket, to: BURN_ADDRESS, }; assert.doesNotThrow(() => txUtils.validateTxParams(txParams)); diff --git a/app/scripts/controllers/transactions/pending-tx-tracker.js b/app/scripts/controllers/transactions/pending-tx-tracker.js index e5a56b8ab..6252727c3 100644 --- a/app/scripts/controllers/transactions/pending-tx-tracker.js +++ b/app/scripts/controllers/transactions/pending-tx-tracker.js @@ -1,7 +1,7 @@ import EventEmitter from 'safe-event-emitter'; import log from 'loglevel'; import EthQuery from 'ethjs-query'; -import { TRANSACTION_STATUSES } from '../../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../../shared/constants/transaction'; import { ERROR_SUBMITTING } from './tx-state-manager'; /** @@ -174,7 +174,7 @@ export default class PendingTransactionTracker extends EventEmitter { const txId = txMeta.id; // Only check submitted txs - if (txMeta.status !== TRANSACTION_STATUSES.SUBMITTED) { + if (txMeta.status !== TransactionStatus.submitted) { return; } diff --git a/app/scripts/controllers/transactions/pending-tx-tracker.test.js b/app/scripts/controllers/transactions/pending-tx-tracker.test.js index 572837fe7..7bbed9687 100644 --- a/app/scripts/controllers/transactions/pending-tx-tracker.test.js +++ b/app/scripts/controllers/transactions/pending-tx-tracker.test.js @@ -1,7 +1,7 @@ import { strict as assert } from 'assert'; import sinon from 'sinon'; import BN from 'bn.js'; -import { TRANSACTION_STATUSES } from '../../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../../shared/constants/transaction'; import PendingTransactionTracker from './pending-tx-tracker'; describe('PendingTransactionTracker', function () { @@ -155,7 +155,7 @@ describe('PendingTransactionTracker', function () { const txMeta = { id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.SIGNED, + status: TransactionStatus.signed, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', @@ -212,7 +212,7 @@ describe('PendingTransactionTracker', function () { const txMeta = { id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.SIGNED, + status: TransactionStatus.signed, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', @@ -256,7 +256,7 @@ describe('PendingTransactionTracker', function () { const txMeta = { id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.SIGNED, + status: TransactionStatus.signed, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', @@ -302,7 +302,7 @@ describe('PendingTransactionTracker', function () { const txMeta = { id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.SIGNED, + status: TransactionStatus.signed, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', @@ -401,7 +401,7 @@ describe('PendingTransactionTracker', function () { await pendingTxTracker._checkIfTxWasDropped({ id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', @@ -433,7 +433,7 @@ describe('PendingTransactionTracker', function () { const dropped = await pendingTxTracker._checkIfTxWasDropped({ id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', @@ -453,7 +453,7 @@ describe('PendingTransactionTracker', function () { { id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', @@ -465,7 +465,7 @@ describe('PendingTransactionTracker', function () { { id: 2, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x2', @@ -510,7 +510,7 @@ describe('PendingTransactionTracker', function () { { id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', @@ -522,7 +522,7 @@ describe('PendingTransactionTracker', function () { { id: 2, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x2', @@ -568,7 +568,7 @@ describe('PendingTransactionTracker', function () { const txMeta = { id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', @@ -640,7 +640,7 @@ describe('PendingTransactionTracker', function () { pendingTxTracker.once('tx:failed', listeners.failed); pendingTxTracker.once('tx:warning', listeners.warning); await pendingTxTracker._checkPendingTx({ - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, history: [{}], txParams: { nonce: '0x1' }, id: '456', @@ -684,7 +684,7 @@ describe('PendingTransactionTracker', function () { await pendingTxTracker._checkPendingTx({ id: '2', history: [{}], - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d' }, }); @@ -706,7 +706,7 @@ describe('PendingTransactionTracker', function () { it("should emit 'tx:dropped' if another tx with the same nonce succeeds", async function () { const txs = [ { - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, history: [{}], txParams: { nonce: '0x1' }, id: '456', @@ -714,7 +714,7 @@ describe('PendingTransactionTracker', function () { hash: '0xbad', }, { - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, history: [{}], txParams: { nonce: '0x1' }, id: '123', @@ -763,7 +763,7 @@ describe('PendingTransactionTracker', function () { const txMeta = { id: 1, hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb', - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d', nonce: '0x1', diff --git a/app/scripts/controllers/transactions/tx-state-manager.js b/app/scripts/controllers/transactions/tx-state-manager.js index 07d19736e..bd8e38051 100644 --- a/app/scripts/controllers/transactions/tx-state-manager.js +++ b/app/scripts/controllers/transactions/tx-state-manager.js @@ -3,7 +3,7 @@ import { ObservableStore } from '@metamask/obs-store'; import log from 'loglevel'; import { values, keyBy, mapValues, omitBy, pickBy, sortBy } from 'lodash'; import createId from '../../../../shared/modules/random-id'; -import { TRANSACTION_STATUSES } from '../../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../../shared/constants/transaction'; import { METAMASK_CONTROLLER_EVENTS } from '../../metamask-controller'; import { transactionMatchesNetwork } from '../../../../shared/modules/transaction.utils'; import { ORIGIN_METAMASK } from '../../../../shared/constants/app'; @@ -127,7 +127,7 @@ export default class TransactionStateManager extends EventEmitter { return { id: createId(), time: new Date().getTime(), - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: netId, originalGasEstimate: opts.txParams?.gas, userEditedGasLimit: false, @@ -153,7 +153,7 @@ export default class TransactionStateManager extends EventEmitter { return pickBy( this.store.getState().transactions, (transaction) => - transaction.status === TRANSACTION_STATUSES.UNAPPROVED && + transaction.status === TransactionStatus.unapproved && transactionMatchesNetwork(transaction, chainId, network), ); } @@ -167,7 +167,7 @@ export default class TransactionStateManager extends EventEmitter { * @returns {TransactionMeta[]} the filtered list of transactions */ getApprovedTransactions(address) { - const searchCriteria = { status: TRANSACTION_STATUSES.APPROVED }; + const searchCriteria = { status: TransactionStatus.approved }; if (address) { searchCriteria.from = address; } @@ -183,7 +183,7 @@ export default class TransactionStateManager extends EventEmitter { * @returns {TransactionMeta[]} the filtered list of transactions */ getPendingTransactions(address) { - const searchCriteria = { status: TRANSACTION_STATUSES.SUBMITTED }; + const searchCriteria = { status: TransactionStatus.submitted }; if (address) { searchCriteria.from = address; } @@ -199,7 +199,7 @@ export default class TransactionStateManager extends EventEmitter { * @returns {TransactionMeta[]} the filtered list of transactions */ getConfirmedTransactions(address) { - const searchCriteria = { status: TRANSACTION_STATUSES.CONFIRMED }; + const searchCriteria = { status: TransactionStatus.confirmed }; if (address) { searchCriteria.from = address; } @@ -509,7 +509,7 @@ export default class TransactionStateManager extends EventEmitter { * @param {number} txId - the target TransactionMeta's Id */ setTxStatusRejected(txId) { - this._setTransactionStatus(txId, TRANSACTION_STATUSES.REJECTED); + this._setTransactionStatus(txId, TransactionStatus.rejected); this._deleteTransaction(txId); } @@ -519,7 +519,7 @@ export default class TransactionStateManager extends EventEmitter { * @param {number} txId - the target TransactionMeta's Id */ setTxStatusUnapproved(txId) { - this._setTransactionStatus(txId, TRANSACTION_STATUSES.UNAPPROVED); + this._setTransactionStatus(txId, TransactionStatus.unapproved); } /** @@ -528,7 +528,7 @@ export default class TransactionStateManager extends EventEmitter { * @param {number} txId - the target TransactionMeta's Id */ setTxStatusApproved(txId) { - this._setTransactionStatus(txId, TRANSACTION_STATUSES.APPROVED); + this._setTransactionStatus(txId, TransactionStatus.approved); } /** @@ -537,7 +537,7 @@ export default class TransactionStateManager extends EventEmitter { * @param {number} txId - the target TransactionMeta's Id */ setTxStatusSigned(txId) { - this._setTransactionStatus(txId, TRANSACTION_STATUSES.SIGNED); + this._setTransactionStatus(txId, TransactionStatus.signed); } /** @@ -550,7 +550,7 @@ export default class TransactionStateManager extends EventEmitter { const txMeta = this.getTransaction(txId); txMeta.submittedTime = new Date().getTime(); this.updateTransaction(txMeta, 'txStateManager - add submitted time stamp'); - this._setTransactionStatus(txId, TRANSACTION_STATUSES.SUBMITTED); + this._setTransactionStatus(txId, TransactionStatus.submitted); } /** @@ -559,7 +559,7 @@ export default class TransactionStateManager extends EventEmitter { * @param {number} txId - the target TransactionMeta's Id */ setTxStatusConfirmed(txId) { - this._setTransactionStatus(txId, TRANSACTION_STATUSES.CONFIRMED); + this._setTransactionStatus(txId, TransactionStatus.confirmed); } /** @@ -568,7 +568,7 @@ export default class TransactionStateManager extends EventEmitter { * @param {number} txId - the target TransactionMeta's Id */ setTxStatusDropped(txId) { - this._setTransactionStatus(txId, TRANSACTION_STATUSES.DROPPED); + this._setTransactionStatus(txId, TransactionStatus.dropped); } /** @@ -592,7 +592,7 @@ export default class TransactionStateManager extends EventEmitter { 'transactions:tx-state-manager#fail - add error', ); - this._setTransactionStatus(txId, TRANSACTION_STATUSES.FAILED); + this._setTransactionStatus(txId, TransactionStatus.failed); } /** @@ -626,7 +626,7 @@ export default class TransactionStateManager extends EventEmitter { this.store.updateState({ transactions: omitBy( this.store.getState().transactions, - (transaction) => transaction.status === TRANSACTION_STATUSES.UNAPPROVED, + (transaction) => transaction.status === TransactionStatus.unapproved, ), }); } @@ -683,9 +683,9 @@ export default class TransactionStateManager extends EventEmitter { this.emit(`tx:status-update`, txId, status); if ( [ - TRANSACTION_STATUSES.SUBMITTED, - TRANSACTION_STATUSES.REJECTED, - TRANSACTION_STATUSES.FAILED, + TransactionStatus.submitted, + TransactionStatus.rejected, + TransactionStatus.failed, ].includes(status) ) { this.emit(`${txMeta.id}:finished`, txMeta); diff --git a/app/scripts/controllers/transactions/tx-state-manager.test.js b/app/scripts/controllers/transactions/tx-state-manager.test.js index f1354d146..677f59334 100644 --- a/app/scripts/controllers/transactions/tx-state-manager.test.js +++ b/app/scripts/controllers/transactions/tx-state-manager.test.js @@ -1,8 +1,8 @@ import { strict as assert } from 'assert'; import sinon from 'sinon'; import { - TRANSACTION_STATUSES, - TRANSACTION_TYPES, + TransactionStatus, + TransactionType, } from '../../../../shared/constants/transaction'; import { CHAIN_IDS, NETWORK_IDS } from '../../../../shared/constants/network'; import { GAS_LIMITS } from '../../../../shared/constants/gas'; @@ -20,7 +20,7 @@ function generateTransactions( to, from, status, - type = TRANSACTION_TYPES.SIMPLE_SEND, + type = TransactionType.simpleSend, nonce = (i) => `${i}`, }, ) { @@ -63,7 +63,7 @@ describe('TransactionStateManager', function () { it('sets the tx status to signed', function () { const tx = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -75,13 +75,13 @@ describe('TransactionStateManager', function () { const result = txStateManager.getTransactions(); assert.ok(Array.isArray(result)); assert.equal(result.length, 1); - assert.equal(result[0].status, TRANSACTION_STATUSES.SIGNED); + assert.equal(result[0].status, TransactionStatus.signed); }); it('should emit a signed event to signal the execution of callback', function () { const tx = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -105,7 +105,7 @@ describe('TransactionStateManager', function () { it('sets the tx status to rejected and removes it from history', function () { const tx = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -122,7 +122,7 @@ describe('TransactionStateManager', function () { it('should emit a rejected event to signal the execution of callback', function () { const tx = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -159,7 +159,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x0', }, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, }; const confirmedTx = { @@ -171,7 +171,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x3', }, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, }; const txm = new TxStateManager({ @@ -198,7 +198,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x0', }, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, }; const unapprovedTx1 = { @@ -210,7 +210,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x1', }, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, }; const approvedTx2 = { @@ -222,7 +222,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x2', }, - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, }; const confirmedTx3 = { @@ -234,7 +234,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x3', }, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, }; const txm = new TxStateManager({ @@ -266,7 +266,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x0', }, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, }; const submittedTx0Dupe = { id: 1, @@ -277,7 +277,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x0', }, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, }; const unapprovedTx1 = { @@ -290,7 +290,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x1', }, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, }; const approvedTx2 = { @@ -302,7 +302,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x2', }, - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, }; const approvedTx2Dupe = { id: 4, @@ -314,7 +314,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x2', }, - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, }; const failedTx3 = { @@ -326,7 +326,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x3', }, - status: TRANSACTION_STATUSES.FAILED, + status: TransactionStatus.failed, }; const failedTx3Dupe = { id: 6, @@ -338,7 +338,7 @@ describe('TransactionStateManager', function () { to: '0xRecipient', nonce: '0x3', }, - status: TRANSACTION_STATUSES.FAILED, + status: TransactionStatus.failed, }; const txm = new TxStateManager({ @@ -371,61 +371,61 @@ describe('TransactionStateManager', function () { const txMetas = [ { id: 0, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: VALID_ADDRESS, to: VALID_ADDRESS_TWO }, metamaskNetworkId: currentNetworkId, }, { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: VALID_ADDRESS, to: VALID_ADDRESS_TWO }, metamaskNetworkId: currentNetworkId, }, { id: 2, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: VALID_ADDRESS, to: VALID_ADDRESS_TWO }, metamaskNetworkId: currentNetworkId, }, { id: 3, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: VALID_ADDRESS_TWO, to: VALID_ADDRESS }, metamaskNetworkId: currentNetworkId, }, { id: 4, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: VALID_ADDRESS_TWO, to: VALID_ADDRESS }, metamaskNetworkId: currentNetworkId, }, { id: 5, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: VALID_ADDRESS, to: VALID_ADDRESS_TWO }, metamaskNetworkId: currentNetworkId, }, { id: 6, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: VALID_ADDRESS, to: VALID_ADDRESS_TWO }, metamaskNetworkId: currentNetworkId, }, { id: 7, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: VALID_ADDRESS_TWO, to: VALID_ADDRESS }, metamaskNetworkId: currentNetworkId, }, { id: 8, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: VALID_ADDRESS_TWO, to: VALID_ADDRESS }, metamaskNetworkId: currentNetworkId, }, { id: 9, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: VALID_ADDRESS_TWO, to: VALID_ADDRESS }, metamaskNetworkId: currentNetworkId, }, @@ -434,7 +434,7 @@ describe('TransactionStateManager', function () { let searchCriteria; searchCriteria = { - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, from: VALID_ADDRESS, }; assert.equal( @@ -443,7 +443,7 @@ describe('TransactionStateManager', function () { `getTransactions - ${JSON.stringify(searchCriteria)}`, ); searchCriteria = { - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, to: VALID_ADDRESS, }; assert.equal( @@ -452,7 +452,7 @@ describe('TransactionStateManager', function () { `getTransactions - ${JSON.stringify(searchCriteria)}`, ); searchCriteria = { - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, from: VALID_ADDRESS_TWO, }; assert.equal( @@ -460,7 +460,7 @@ describe('TransactionStateManager', function () { 3, `getTransactions - ${JSON.stringify(searchCriteria)}`, ); - searchCriteria = { status: TRANSACTION_STATUSES.CONFIRMED }; + searchCriteria = { status: TransactionStatus.confirmed }; assert.equal( txStateManager.getTransactions({ searchCriteria }).length, 5, @@ -479,7 +479,7 @@ describe('TransactionStateManager', function () { `getTransactions - ${JSON.stringify(searchCriteria)}`, ); searchCriteria = { - status: (status) => status !== TRANSACTION_STATUSES.CONFIRMED, + status: (status) => status !== TransactionStatus.confirmed, }; assert.equal( txStateManager.getTransactions({ searchCriteria }).length, @@ -493,7 +493,7 @@ describe('TransactionStateManager', function () { it('adds a tx returned in getTransactions', function () { const tx = { id: 1, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -523,7 +523,7 @@ describe('TransactionStateManager', function () { for (const value of invalidValues) { const tx = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { ...validTxParams, @@ -544,7 +544,7 @@ describe('TransactionStateManager', function () { it('does not override txs from other networks', function () { const tx = { id: 1, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -553,7 +553,7 @@ describe('TransactionStateManager', function () { }; const tx2 = { id: 2, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: otherNetworkId, txParams: { to: VALID_ADDRESS, @@ -576,7 +576,7 @@ describe('TransactionStateManager', function () { chainId: currentChainId, to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, }); txs.forEach((tx) => txStateManager.addTransaction(tx)); const result = txStateManager.getTransactions(); @@ -590,7 +590,7 @@ describe('TransactionStateManager', function () { chainId: currentChainId, to: VALID_ADDRESS, from: VALID_ADDRESS_TWO, - status: TRANSACTION_STATUSES.REJECTED, + status: TransactionStatus.rejected, }); txs.forEach((tx) => txStateManager.addTransaction(tx)); const result = txStateManager.getTransactions(); @@ -611,8 +611,8 @@ describe('TransactionStateManager', function () { from: VALID_ADDRESS_TWO, status: (i) => i === 0 - ? TRANSACTION_STATUSES.UNAPPROVED - : TRANSACTION_STATUSES.CONFIRMED, + ? TransactionStatus.unapproved + : TransactionStatus.confirmed, }, ); txs.forEach((tx) => txStateManager.addTransaction(tx)); @@ -625,7 +625,7 @@ describe('TransactionStateManager', function () { assert.equal(result[0].id, 0, 'first tx should still be there'); assert.equal( result[0].status, - TRANSACTION_STATUSES.UNAPPROVED, + TransactionStatus.unapproved, 'first tx should be unapproved', ); assert.equal(result[1].id, 2, 'early txs truncated'); @@ -645,11 +645,9 @@ describe('TransactionStateManager', function () { from: VALID_ADDRESS_TWO, nonce: (i) => (i === 1 ? `0` : `${i}`), status: (i) => - i === 0 - ? TRANSACTION_STATUSES.DROPPED - : TRANSACTION_STATUSES.CONFIRMED, + i === 0 ? TransactionStatus.dropped : TransactionStatus.confirmed, type: (i) => - i === 1 ? TRANSACTION_TYPES.CANCEL : TRANSACTION_TYPES.SIMPLE_SEND, + i === 1 ? TransactionType.cancel : TransactionType.simpleSend, }); txs.forEach((tx) => txStateManager.addTransaction(tx)); const result = txStateManager.getTransactions(); @@ -658,8 +656,8 @@ describe('TransactionStateManager', function () { assert.equal( result.some( (tx) => - tx.status === TRANSACTION_STATUSES.DROPPED || - tx.status === TRANSACTION_TYPES.CANCEL, + tx.status === TransactionStatus.dropped || + tx.status === TransactionType.cancel, ), false, 'the cancel and dropped transactions should not be present in the result', @@ -687,12 +685,12 @@ describe('TransactionStateManager', function () { nonce: (i) => ([0, 1, 4, 5].includes(i) ? '0' : `${i}`), status: (i) => i === 0 || i === 4 - ? TRANSACTION_STATUSES.DROPPED - : TRANSACTION_STATUSES.CONFIRMED, + ? TransactionStatus.dropped + : TransactionStatus.confirmed, type: (i) => i === 1 || i === 5 - ? TRANSACTION_TYPES.CANCEL - : TRANSACTION_TYPES.SIMPLE_SEND, + ? TransactionType.cancel + : TransactionType.simpleSend, }); txs.forEach((tx) => txStateManager.addTransaction(tx)); const result = txStateManager.getTransactions({ @@ -734,12 +732,12 @@ describe('TransactionStateManager', function () { }, status: (i) => i === 0 || i === 4 - ? TRANSACTION_STATUSES.DROPPED - : TRANSACTION_STATUSES.CONFIRMED, + ? TransactionStatus.dropped + : TransactionStatus.confirmed, type: (i) => i === 1 || i === 5 - ? TRANSACTION_TYPES.CANCEL - : TRANSACTION_TYPES.SIMPLE_SEND, + ? TransactionType.cancel + : TransactionType.simpleSend, }); txs.forEach((tx) => txStateManager.addTransaction(tx)); const result = txStateManager.getTransactions({ @@ -754,7 +752,7 @@ describe('TransactionStateManager', function () { it('replaces the tx with the same id', function () { txStateManager.addTransaction({ id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -763,7 +761,7 @@ describe('TransactionStateManager', function () { }); txStateManager.addTransaction({ id: '2', - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -791,7 +789,7 @@ describe('TransactionStateManager', function () { txStateManager.addTransaction({ id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: validTxParams, }); @@ -822,7 +820,7 @@ describe('TransactionStateManager', function () { const txMeta = { id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { from: VALID_ADDRESS_TWO, @@ -898,7 +896,7 @@ describe('TransactionStateManager', function () { it('does NOT add empty history items', function () { const txMeta = { id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { from: VALID_ADDRESS_TWO, @@ -917,7 +915,7 @@ describe('TransactionStateManager', function () { it('should set tx status to failed if updating after error submitting', function () { const txMeta = { id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { from: VALID_ADDRESS_TWO, @@ -979,7 +977,7 @@ describe('TransactionStateManager', function () { it('should set transaction status to failed', function () { const txMeta = { id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { from: VALID_ADDRESS_TWO, @@ -1026,7 +1024,7 @@ describe('TransactionStateManager', function () { it('returns unapproved txs in a hash', function () { txStateManager.addTransaction({ id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1035,7 +1033,7 @@ describe('TransactionStateManager', function () { }); txStateManager.addTransaction({ id: '2', - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1044,7 +1042,7 @@ describe('TransactionStateManager', function () { }); const result = txStateManager.getUnapprovedTxList(); assert.equal(typeof result, 'object'); - assert.equal(result['1'].status, TRANSACTION_STATUSES.UNAPPROVED); + assert.equal(result['1'].status, TransactionStatus.unapproved); assert.equal(result['2'], undefined); }); }); @@ -1053,7 +1051,7 @@ describe('TransactionStateManager', function () { it('returns a tx with the requested id', function () { txStateManager.addTransaction({ id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1062,7 +1060,7 @@ describe('TransactionStateManager', function () { }); txStateManager.addTransaction({ id: '2', - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, metamaskNetworkId: currentNetworkId, txParams: { to: VALID_ADDRESS, @@ -1071,11 +1069,11 @@ describe('TransactionStateManager', function () { }); assert.equal( txStateManager.getTransaction('1').status, - TRANSACTION_STATUSES.UNAPPROVED, + TransactionStatus.unapproved, ); assert.equal( txStateManager.getTransaction('2').status, - TRANSACTION_STATUSES.CONFIRMED, + TransactionStatus.confirmed, ); }); }); @@ -1088,19 +1086,19 @@ describe('TransactionStateManager', function () { const txMetas = [ { id: 0, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: specificAddress, to: otherAddress }, metamaskNetworkId: currentNetworkId, }, { id: 1, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: otherAddress, to: specificAddress }, metamaskNetworkId: currentNetworkId, }, { id: 2, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: otherAddress, to: specificAddress }, metamaskNetworkId: currentNetworkId, }, @@ -1124,19 +1122,19 @@ describe('TransactionStateManager', function () { const txMetas = [ { id: 0, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: specificAddress, to: otherAddress }, metamaskNetworkId: currentNetworkId, }, { id: 1, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: specificAddress, to: otherAddress }, metamaskNetworkId: otherNetworkId, }, { id: 2, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: specificAddress, to: otherAddress }, metamaskNetworkId: otherNetworkId, }, @@ -1319,25 +1317,25 @@ describe('TransactionStateManager', function () { const txMetas = [ { id: 0, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: VALID_ADDRESS, to: VALID_ADDRESS_TWO }, metamaskNetworkId: currentNetworkId, }, { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: VALID_ADDRESS, to: VALID_ADDRESS_TWO }, metamaskNetworkId: currentNetworkId, }, { id: 2, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: VALID_ADDRESS, to: VALID_ADDRESS_TWO }, metamaskNetworkId: otherNetworkId, }, { id: 3, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: VALID_ADDRESS, to: VALID_ADDRESS_TWO }, metamaskNetworkId: otherNetworkId, }, @@ -1349,7 +1347,7 @@ describe('TransactionStateManager', function () { const unapprovedTxList = txStateManager .getTransactions({ filterToCurrentNetwork: false }) - .filter((tx) => tx.status === TRANSACTION_STATUSES.UNAPPROVED); + .filter((tx) => tx.status === TransactionStatus.unapproved); assert.equal(unapprovedTxList.length, 0); }); diff --git a/app/scripts/lib/message-manager.test.js b/app/scripts/lib/message-manager.test.js index 7045b6588..9a326d000 100644 --- a/app/scripts/lib/message-manager.test.js +++ b/app/scripts/lib/message-manager.test.js @@ -1,4 +1,4 @@ -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import MessageManager from './message-manager'; describe('Message Manager', () => { @@ -22,7 +22,7 @@ describe('Message Manager', () => { it('adds a Msg returned in getMsgList', () => { const Msg = { id: 1, - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: 'unit test', }; messageManager.addMsg(Msg); @@ -45,7 +45,7 @@ describe('Message Manager', () => { const result = messageManager.messages; expect(Array.isArray(result)).toStrictEqual(true); expect(result).toHaveLength(1); - expect(result[0].status).toStrictEqual(TRANSACTION_STATUSES.APPROVED); + expect(result[0].status).toStrictEqual(TransactionStatus.approved); }); }); @@ -61,7 +61,7 @@ describe('Message Manager', () => { const result = messageManager.messages; expect(Array.isArray(result)).toStrictEqual(true); expect(result).toHaveLength(1); - expect(result[0].status).toStrictEqual(TRANSACTION_STATUSES.REJECTED); + expect(result[0].status).toStrictEqual(TransactionStatus.rejected); }); }); @@ -74,7 +74,7 @@ describe('Message Manager', () => { }); messageManager.addMsg({ id: '2', - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: 'unit test', }); messageManager._updateMsg({ @@ -97,7 +97,7 @@ describe('Message Manager', () => { }); messageManager.addMsg({ id: '2', - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: 'unit test', }); const result = messageManager.getUnapprovedMsgs(); @@ -116,12 +116,12 @@ describe('Message Manager', () => { }); messageManager.addMsg({ id: '2', - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: 'unit test', }); expect(messageManager.getMsg('1').status).toStrictEqual('unapproved'); expect(messageManager.getMsg('2').status).toStrictEqual( - TRANSACTION_STATUSES.APPROVED, + TransactionStatus.approved, ); }); }); diff --git a/app/scripts/lib/middleware/pending.test.js b/app/scripts/lib/middleware/pending.test.js index d3068bf54..68b3ad185 100644 --- a/app/scripts/lib/middleware/pending.test.js +++ b/app/scripts/lib/middleware/pending.test.js @@ -1,5 +1,5 @@ import { GAS_LIMITS } from '../../../../shared/constants/gas'; -import { TRANSACTION_ENVELOPE_TYPES } from '../../../../shared/constants/transaction'; +import { TransactionEnvelopeType } from '../../../../shared/constants/transaction'; import { txMetaStub } from '../../../../test/stub/tx-meta-stub'; import { createPendingNonceMiddleware, @@ -71,7 +71,7 @@ describe('PendingNonceMiddleware', () => { hash: '0x2cc5a25744486f7383edebbf32003e5a66e18135799593d6b5cdd2bb43674f09', input: '0x', nonce: '0x5', - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, to: '0xf231d46dd78806e1dd93442cf33c7671f8538748', transactionIndex: null, value: '0x0', diff --git a/app/scripts/lib/personal-message-manager.test.js b/app/scripts/lib/personal-message-manager.test.js index 4fc7a6283..b89db81d0 100644 --- a/app/scripts/lib/personal-message-manager.test.js +++ b/app/scripts/lib/personal-message-manager.test.js @@ -1,4 +1,4 @@ -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import PersonalMessageManager from './personal-message-manager'; describe('Personal Message Manager', () => { @@ -22,7 +22,7 @@ describe('Personal Message Manager', () => { it('adds a Msg returned in getMsgList', () => { const Msg = { id: 1, - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: 'unit test', }; messageManager.addMsg(Msg); @@ -37,7 +37,7 @@ describe('Personal Message Manager', () => { it('sets the Msg status to approved', () => { const Msg = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: 'unit test', }; messageManager.addMsg(Msg); @@ -45,7 +45,7 @@ describe('Personal Message Manager', () => { const result = messageManager.messages; expect(Array.isArray(result)).toStrictEqual(true); expect(result).toHaveLength(1); - expect(result[0].status).toStrictEqual(TRANSACTION_STATUSES.APPROVED); + expect(result[0].status).toStrictEqual(TransactionStatus.approved); }); }); @@ -53,7 +53,7 @@ describe('Personal Message Manager', () => { it('sets the Msg status to rejected', () => { const Msg = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: 'unit test', }; messageManager.addMsg(Msg); @@ -61,7 +61,7 @@ describe('Personal Message Manager', () => { const result = messageManager.messages; expect(Array.isArray(result)).toStrictEqual(true); expect(result).toHaveLength(1); - expect(result[0].status).toStrictEqual(TRANSACTION_STATUSES.REJECTED); + expect(result[0].status).toStrictEqual(TransactionStatus.rejected); }); }); @@ -69,12 +69,12 @@ describe('Personal Message Manager', () => { it('replaces the Msg with the same id', () => { messageManager.addMsg({ id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: 'unit test', }); messageManager.addMsg({ id: '2', - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: 'unit test', }); messageManager._updateMsg({ @@ -92,17 +92,17 @@ describe('Personal Message Manager', () => { it('returns unapproved Msgs in a hash', () => { messageManager.addMsg({ id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: 'unit test', }); messageManager.addMsg({ id: '2', - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: 'unit test', }); const result = messageManager.getUnapprovedMsgs(); expect(typeof result).toStrictEqual('object'); - expect(result['1'].status).toStrictEqual(TRANSACTION_STATUSES.UNAPPROVED); + expect(result['1'].status).toStrictEqual(TransactionStatus.unapproved); expect(result['2']).toBeUndefined(); }); }); @@ -111,19 +111,19 @@ describe('Personal Message Manager', () => { it('returns a Msg with the requested id', () => { messageManager.addMsg({ id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: 'unit test', }); messageManager.addMsg({ id: '2', - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, metamaskNetworkId: 'unit test', }); expect(messageManager.getMsg('1').status).toStrictEqual( - TRANSACTION_STATUSES.UNAPPROVED, + TransactionStatus.unapproved, ); expect(messageManager.getMsg('2').status).toStrictEqual( - TRANSACTION_STATUSES.APPROVED, + TransactionStatus.approved, ); }); }); diff --git a/app/scripts/lib/typed-message-manager.test.js b/app/scripts/lib/typed-message-manager.test.js index 1098f7f79..a9f2d5465 100644 --- a/app/scripts/lib/typed-message-manager.test.js +++ b/app/scripts/lib/typed-message-manager.test.js @@ -1,5 +1,5 @@ import sinon from 'sinon'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import TypedMessageManager from './typed-message-manager'; describe('Typed Message Manager', () => { @@ -92,9 +92,7 @@ describe('Typed Message Manager', () => { }); it('adds to unapproved messages and sets status to unapproved', () => { - expect(typedMsgs[msgId].status).toStrictEqual( - TRANSACTION_STATUSES.UNAPPROVED, - ); + expect(typedMsgs[msgId].status).toStrictEqual(TransactionStatus.unapproved); }); it('validates params', async () => { @@ -111,17 +109,17 @@ describe('Typed Message Manager', () => { it('approves messages', async () => { const messageMetaMaskId = messages[0].msgParams; typedMessageManager.approveMessage(messageMetaMaskId); - expect(messages[0].status).toStrictEqual(TRANSACTION_STATUSES.APPROVED); + expect(messages[0].status).toStrictEqual(TransactionStatus.approved); }); it('sets msg status to signed and adds a raw sig to message details', () => { typedMessageManager.setMsgStatusSigned(numberMsgId, 'raw sig'); - expect(messages[0].status).toStrictEqual(TRANSACTION_STATUSES.SIGNED); + expect(messages[0].status).toStrictEqual(TransactionStatus.signed); expect(messages[0].rawSig).toStrictEqual('raw sig'); }); it('rejects message', () => { typedMessageManager.rejectMsg(numberMsgId); - expect(messages[0].status).toStrictEqual(TRANSACTION_STATUSES.REJECTED); + expect(messages[0].status).toStrictEqual(TransactionStatus.rejected); }); }); diff --git a/app/scripts/lib/util.js b/app/scripts/lib/util.js index f225ddad7..b482be97f 100644 --- a/app/scripts/lib/util.js +++ b/app/scripts/lib/util.js @@ -15,7 +15,7 @@ import { PLATFORM_BRAVE, } from '../../../shared/constants/app'; import { stripHexPrefix } from '../../../shared/modules/hexstring-utils'; -import { TRANSACTION_ENVELOPE_TYPES } from '../../../shared/constants/transaction'; +import { TransactionEnvelopeType } from '../../../shared/constants/transaction'; /** * @see {@link getEnvironmentType} @@ -291,10 +291,10 @@ export function formatTxMetaForRpcResult(txMeta) { formattedTxMeta.gasPrice = maxFeePerGas; formattedTxMeta.maxFeePerGas = maxFeePerGas; formattedTxMeta.maxPriorityFeePerGas = maxPriorityFeePerGas; - formattedTxMeta.type = TRANSACTION_ENVELOPE_TYPES.FEE_MARKET; + formattedTxMeta.type = TransactionEnvelopeType.feeMarket; } else { formattedTxMeta.gasPrice = gasPrice; - formattedTxMeta.type = TRANSACTION_ENVELOPE_TYPES.LEGACY; + formattedTxMeta.type = TransactionEnvelopeType.legacy; } return formattedTxMeta; diff --git a/app/scripts/lib/util.test.js b/app/scripts/lib/util.test.js index 7faf3ac4d..c93e9f8e0 100644 --- a/app/scripts/lib/util.test.js +++ b/app/scripts/lib/util.test.js @@ -10,9 +10,9 @@ import { PLATFORM_EDGE, } from '../../../shared/constants/app'; import { - TRANSACTION_STATUSES, - TRANSACTION_TYPES, - TRANSACTION_ENVELOPE_TYPES, + TransactionStatus, + TransactionType, + TransactionEnvelopeType, } from '../../../shared/constants/transaction'; import { deferredPromise, @@ -223,7 +223,7 @@ describe('app utils', () => { it('should correctly format the tx meta object (EIP-1559)', () => { const txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: '0xc684832530fcbddae4b4230a47e991ddcec2831d', to: '0x1678a085c290ebd122dc42cba69373b5953b831d', @@ -232,7 +232,7 @@ describe('app utils', () => { gas: '0x7b0d', nonce: '0x4b', }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, origin: 'other', chainId: '0x5', time: 1624408066355, @@ -269,7 +269,7 @@ describe('app utils', () => { it('should correctly format the tx meta object (non EIP-1559)', () => { const txMeta = { id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: { from: '0xc684832530fcbddae4b4230a47e991ddcec2831d', to: '0x1678a085c290ebd122dc42cba69373b5953b831d', @@ -277,7 +277,7 @@ describe('app utils', () => { gas: '0x7b0d', nonce: '0x4b', }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, origin: 'other', chainId: '0x5', time: 1624408066355, @@ -301,7 +301,7 @@ describe('app utils', () => { s: '0x18bfc4eeb7ebcfacc3bd59ea100a6834ea3265e65945dbec69aa2a06564fafff', to: '0x1678a085c290ebd122dc42cba69373b5953b831d', transactionIndex: null, - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, v: '0x29', value: '0x0', }; diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 5ec5acafc..dcb3ad52d 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -59,9 +59,9 @@ import { import browser from 'webextension-polyfill'; import { - ASSET_TYPES, - TRANSACTION_STATUSES, - TRANSACTION_TYPES, + AssetType, + TransactionStatus, + TransactionType, } from '../../shared/constants/transaction'; import { PHISHING_NEW_ISSUE_URLS } from '../../shared/constants/phishing'; import { @@ -373,7 +373,7 @@ export default class MetamaskController extends EventEmitter { properties: { token_contract_address: address, token_symbol: symbol, - asset_type: ASSET_TYPES.NFT, + asset_type: AssetType.NFT, token_standard: standard, source, }, @@ -910,8 +910,8 @@ export default class MetamaskController extends EventEmitter { this.txController.on(`tx:status-update`, async (txId, status) => { if ( - status === TRANSACTION_STATUSES.CONFIRMED || - status === TRANSACTION_STATUSES.FAILED + status === TransactionStatus.confirmed || + status === TransactionStatus.failed ) { const txMeta = this.txController.txStateManager.getTransaction(txId); const frequentRpcListDetail = @@ -930,7 +930,7 @@ export default class MetamaskController extends EventEmitter { // if this is a transferFrom method generated from within the app it may be a collectible transfer transaction // in which case we will want to check and update ownership status of the transferred collectible. if ( - txMeta.type === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM && + txMeta.type === TransactionType.tokenMethodTransferFrom && txMeta.txParams !== undefined ) { const { @@ -1127,7 +1127,7 @@ export default class MetamaskController extends EventEmitter { this.txController.getTransactions({ searchCriteria: { hash, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, }, })[0], }); diff --git a/app/scripts/metamask-controller.test.js b/app/scripts/metamask-controller.test.js index bfdd69c6b..7e6b02fd1 100644 --- a/app/scripts/metamask-controller.test.js +++ b/app/scripts/metamask-controller.test.js @@ -7,7 +7,7 @@ import { obj as createThoughStream } from 'through2'; import EthQuery from 'eth-query'; import proxyquire from 'proxyquire'; import browser from 'webextension-polyfill'; -import { TRANSACTION_STATUSES } from '../../shared/constants/transaction'; +import { TransactionStatus } from '../../shared/constants/transaction'; import createTxMeta from '../../test/lib/createTxMeta'; import { NETWORK_TYPES } from '../../shared/constants/network'; import { KEYRING_TYPES } from '../../shared/constants/keyrings'; @@ -718,24 +718,24 @@ describe('MetaMaskController', function () { metamaskController.txController.txStateManager._addTransactionsToState([ createTxMeta({ id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { from: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc' }, }), createTxMeta({ id: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams: { from: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc' }, }), createTxMeta({ id: 2, - status: TRANSACTION_STATUSES.REJECTED, + status: TransactionStatus.rejected, metamaskNetworkId: '32', }), createTxMeta({ id: 3, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, metamaskNetworkId: currentNetworkId, txParams: { from: '0xB09d8505E1F4EF1CeA089D47094f5DD3464083d4' }, }), @@ -865,7 +865,7 @@ describe('MetaMaskController', function () { }); it('sets the status to unapproved', function () { - assert.equal(metamaskMsgs[msgId].status, TRANSACTION_STATUSES.UNAPPROVED); + assert.equal(metamaskMsgs[msgId].status, TransactionStatus.unapproved); }); it('sets the type to eth_sign', function () { @@ -875,7 +875,7 @@ describe('MetaMaskController', function () { it('rejects the message', function () { const msgIdInt = parseInt(msgId, 10); metamaskController.cancelMessage(msgIdInt, noop); - assert.equal(messages[0].status, TRANSACTION_STATUSES.REJECTED); + assert.equal(messages[0].status, TransactionStatus.rejected); }); it('checks message length', async function () { @@ -961,7 +961,7 @@ describe('MetaMaskController', function () { it('sets the status to unapproved', function () { assert.equal( metamaskPersonalMsgs[msgId].status, - TRANSACTION_STATUSES.UNAPPROVED, + TransactionStatus.unapproved, ); }); @@ -972,7 +972,7 @@ describe('MetaMaskController', function () { it('rejects the message', function () { const msgIdInt = parseInt(msgId, 10); metamaskController.cancelPersonalMessage(msgIdInt, noop); - assert.equal(personalMessages[0].status, TRANSACTION_STATUSES.REJECTED); + assert.equal(personalMessages[0].status, TransactionStatus.rejected); }); it('errors when signing a message', async function () { @@ -981,7 +981,7 @@ describe('MetaMaskController', function () { ); assert.equal( metamaskPersonalMsgs[msgId].status, - TRANSACTION_STATUSES.SIGNED, + TransactionStatus.signed, ); assert.equal( metamaskPersonalMsgs[msgId].rawSig, diff --git a/app/scripts/migrations/015.js b/app/scripts/migrations/015.js index f2783cebb..85ef2907a 100644 --- a/app/scripts/migrations/015.js +++ b/app/scripts/migrations/015.js @@ -6,7 +6,7 @@ to a 'failed' stated */ import { cloneDeep } from 'lodash'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; const version = 15; @@ -36,7 +36,7 @@ function transformState(state) { if (!txMeta.err) { return txMeta; } else if (txMeta.err.message === 'Gave up submitting tx.') { - txMeta.status = TRANSACTION_STATUSES.FAILED; + txMeta.status = TransactionStatus.failed; } return txMeta; }); diff --git a/app/scripts/migrations/016.js b/app/scripts/migrations/016.js index 542ebe81a..2767afafd 100644 --- a/app/scripts/migrations/016.js +++ b/app/scripts/migrations/016.js @@ -6,7 +6,7 @@ to a 'failed' stated */ import { cloneDeep } from 'lodash'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; const version = 16; @@ -40,7 +40,7 @@ function transformState(state) { if ( txMeta.err === 'transaction with the same hash was already imported.' ) { - txMeta.status = TRANSACTION_STATUSES.SUBMITTED; + txMeta.status = TransactionStatus.submitted; delete txMeta.err; } return txMeta; diff --git a/app/scripts/migrations/017.js b/app/scripts/migrations/017.js index 8d510b857..fcc6d60d7 100644 --- a/app/scripts/migrations/017.js +++ b/app/scripts/migrations/017.js @@ -5,7 +5,7 @@ This migration sets transactions who were retried and marked as failed to submit */ import { cloneDeep } from 'lodash'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; const version = 17; @@ -32,11 +32,11 @@ function transformState(state) { if (TransactionController && TransactionController.transactions) { const { transactions } = newState.TransactionController; newState.TransactionController.transactions = transactions.map((txMeta) => { - if (!txMeta.status === TRANSACTION_STATUSES.FAILED) { + if (!txMeta.status === TransactionStatus.failed) { return txMeta; } if (txMeta.retryCount > 0 && txMeta.retryCount < 2) { - txMeta.status = TRANSACTION_STATUSES.SUBMITTED; + txMeta.status = TransactionStatus.submitted; delete txMeta.err; } return txMeta; diff --git a/app/scripts/migrations/019.js b/app/scripts/migrations/019.js index 828795e6f..3b3fdb0f4 100644 --- a/app/scripts/migrations/019.js +++ b/app/scripts/migrations/019.js @@ -6,7 +6,7 @@ whos nonce is too high */ import { cloneDeep } from 'lodash'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; const version = 19; @@ -35,12 +35,12 @@ function transformState(state) { newState.TransactionController.transactions = transactions.map( (txMeta, _, txList) => { - if (txMeta.status !== TRANSACTION_STATUSES.SUBMITTED) { + if (txMeta.status !== TransactionStatus.submitted) { return txMeta; } const confirmedTxs = txList - .filter((tx) => tx.status === TRANSACTION_STATUSES.CONFIRMED) + .filter((tx) => tx.status === TransactionStatus.confirmed) .filter((tx) => tx.txParams.from === txMeta.txParams.from) .filter( (tx) => tx.metamaskNetworkId.from === txMeta.metamaskNetworkId.from, @@ -48,7 +48,7 @@ function transformState(state) { const highestConfirmedNonce = getHighestNonce(confirmedTxs); const pendingTxs = txList - .filter((tx) => tx.status === TRANSACTION_STATUSES.SUBMITTED) + .filter((tx) => tx.status === TransactionStatus.submitted) .filter((tx) => tx.txParams.from === txMeta.txParams.from) .filter( (tx) => tx.metamaskNetworkId.from === txMeta.metamaskNetworkId.from, @@ -64,7 +64,7 @@ function transformState(state) { ); if (parseInt(txMeta.txParams.nonce, 16) > maxNonce + 1) { - txMeta.status = TRANSACTION_STATUSES.FAILED; + txMeta.status = TransactionStatus.failed; txMeta.err = { message: 'nonce too high', note: 'migration 019 custom error', diff --git a/app/scripts/migrations/022.js b/app/scripts/migrations/022.js index d0477b0d1..f9afc6147 100644 --- a/app/scripts/migrations/022.js +++ b/app/scripts/migrations/022.js @@ -5,7 +5,7 @@ This migration adds submittedTime to the txMeta if it is not their */ import { cloneDeep } from 'lodash'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; const version = 22; @@ -34,7 +34,7 @@ function transformState(state) { newState.TransactionController.transactions = transactions.map((txMeta) => { if ( - txMeta.status !== TRANSACTION_STATUSES.SUBMITTED || + txMeta.status !== TransactionStatus.submitted || txMeta.submittedTime ) { return txMeta; diff --git a/app/scripts/migrations/022.test.js b/app/scripts/migrations/022.test.js index c2950b0ac..8d01ec416 100644 --- a/app/scripts/migrations/022.test.js +++ b/app/scripts/migrations/022.test.js @@ -1,4 +1,4 @@ -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import migration22 from './022'; const properTime = new Date().getTime(); @@ -7,9 +7,9 @@ const storage = { data: { TransactionController: { transactions: [ - { status: TRANSACTION_STATUSES.SUBMITTED }, - { status: TRANSACTION_STATUSES.SUBMITTED, submittedTime: properTime }, - { status: TRANSACTION_STATUSES.CONFIRMED }, + { status: TransactionStatus.submitted }, + { status: TransactionStatus.submitted, submittedTime: properTime }, + { status: TransactionStatus.confirmed }, ], }, }, diff --git a/app/scripts/migrations/023.js b/app/scripts/migrations/023.js index 4ec54b138..5fc1409ff 100644 --- a/app/scripts/migrations/023.js +++ b/app/scripts/migrations/023.js @@ -5,7 +5,7 @@ This migration removes transactions that are no longer usefull down to 40 total */ import { cloneDeep } from 'lodash'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; const version = 23; @@ -42,10 +42,10 @@ function transformState(state) { while (reverseTxList.length > 40 && stripping) { const txIndex = reverseTxList.findIndex((txMeta) => { return ( - txMeta.status === TRANSACTION_STATUSES.FAILED || - txMeta.status === TRANSACTION_STATUSES.REJECTED || - txMeta.status === TRANSACTION_STATUSES.CONFIRMED || - txMeta.status === TRANSACTION_STATUSES.DROPPED + txMeta.status === TransactionStatus.failed || + txMeta.status === TransactionStatus.rejected || + txMeta.status === TransactionStatus.confirmed || + txMeta.status === TransactionStatus.dropped ); }); if (txIndex < 0) { diff --git a/app/scripts/migrations/023.test.js b/app/scripts/migrations/023.test.js index 8fe2e5ff8..9bf23eeff 100644 --- a/app/scripts/migrations/023.test.js +++ b/app/scripts/migrations/023.test.js @@ -1,4 +1,4 @@ -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import migration23 from './023'; const storage = { @@ -14,13 +14,13 @@ const transactions = []; const transactions40 = []; const transactions20 = []; -const txStates = Object.values(TRANSACTION_STATUSES); +const txStates = Object.values(TransactionStatus); const deletableTxStates = [ - TRANSACTION_STATUSES.CONFIRMED, - TRANSACTION_STATUSES.REJECTED, - TRANSACTION_STATUSES.FAILED, - TRANSACTION_STATUSES.DROPPED, + TransactionStatus.confirmed, + TransactionStatus.rejected, + TransactionStatus.failed, + TransactionStatus.dropped, ]; let nonDeletableCount = 0; diff --git a/app/scripts/migrations/024.js b/app/scripts/migrations/024.js index 1eb210029..d4142383c 100644 --- a/app/scripts/migrations/024.js +++ b/app/scripts/migrations/024.js @@ -6,7 +6,7 @@ all unapproved transactions */ import { cloneDeep } from 'lodash'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; const version = 24; @@ -32,7 +32,7 @@ function transformState(state) { newState.TransactionController.transactions = transactions.map( (txMeta, _) => { if ( - txMeta.status === TRANSACTION_STATUSES.UNAPPROVED && + txMeta.status === TransactionStatus.unapproved && txMeta.txParams && txMeta.txParams.from ) { diff --git a/app/scripts/migrations/024.test.js b/app/scripts/migrations/024.test.js index c1bc709fb..06237e9e2 100644 --- a/app/scripts/migrations/024.test.js +++ b/app/scripts/migrations/024.test.js @@ -1,6 +1,6 @@ /* eslint-disable jest/no-conditional-expect */ import data from '../first-time-state'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import migration24 from './024'; const firstTimeState = { @@ -21,11 +21,11 @@ const transactions = []; while (transactions.length <= 10) { transactions.push({ txParams: { from: '0x8aCce2391c0d510a6c5E5d8f819a678f79b7e675' }, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, }); transactions.push({ txParams: { from: '0x8aCce2391c0d510a6c5E5d8f819a678f79b7e675' }, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, }); } @@ -38,7 +38,7 @@ describe('storage is migrated successfully and the txParams.from are lowercase', migratedData.data.TransactionController.transactions; migratedTransactions.forEach((tx) => { - if (tx.status === TRANSACTION_STATUSES.UNAPPROVED) { + if (tx.status === TransactionStatus.unapproved) { expect(tx.txParams.from).toStrictEqual( '0x8acce2391c0d510a6c5e5d8f819a678f79b7e675', ); diff --git a/app/scripts/migrations/025.js b/app/scripts/migrations/025.js index 7ea7a00cb..6be1740a4 100644 --- a/app/scripts/migrations/025.js +++ b/app/scripts/migrations/025.js @@ -6,7 +6,7 @@ normalizes txParams on unconfirmed txs */ import { cloneDeep } from 'lodash'; import { addHexPrefix } from '../lib/util'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; const version = 25; @@ -31,7 +31,7 @@ function transformState(state) { const { transactions } = newState.TransactionController; newState.TransactionController.transactions = transactions.map( (txMeta) => { - if (txMeta.status !== TRANSACTION_STATUSES.UNAPPROVED) { + if (txMeta.status !== TransactionStatus.unapproved) { return txMeta; } txMeta.txParams = normalizeTxParams(txMeta.txParams); diff --git a/app/scripts/migrations/025.test.js b/app/scripts/migrations/025.test.js index 81e000d68..229245b87 100644 --- a/app/scripts/migrations/025.test.js +++ b/app/scripts/migrations/025.test.js @@ -1,6 +1,6 @@ /* eslint-disable jest/no-conditional-expect */ import data from '../first-time-state'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import migration25 from './025'; const firstTimeState = { @@ -26,11 +26,11 @@ while (transactions.length <= 10) { random: 'stuff', chainId: 2, }, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, }); transactions.push({ txParams: { from: '0x8aCce2391c0d510a6c5E5d8f819a678f79b7e675' }, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, }); } @@ -43,10 +43,10 @@ describe('storage is migrated successfully and the txParams.from are lowercase', const migratedTransactions = migratedData.data.TransactionController.transactions; migratedTransactions.forEach((tx) => { - if (tx.status === TRANSACTION_STATUSES.UNAPPROVED) { + if (tx.status === TransactionStatus.unapproved) { expect(!tx.txParams.random).toStrictEqual(true); } - if (tx.status === TRANSACTION_STATUSES.UNAPPROVED) { + if (tx.status === TransactionStatus.unapproved) { expect(!tx.txParams.chainId).toStrictEqual(true); } }); diff --git a/app/scripts/migrations/027.js b/app/scripts/migrations/027.js index a067e0084..e7986584a 100644 --- a/app/scripts/migrations/027.js +++ b/app/scripts/migrations/027.js @@ -5,7 +5,7 @@ normalizes txParams on unconfirmed txs */ import { cloneDeep } from 'lodash'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; const version = 27; @@ -29,7 +29,7 @@ function transformState(state) { if (newState.TransactionController.transactions) { const { transactions } = newState.TransactionController; newState.TransactionController.transactions = transactions.filter( - (txMeta) => txMeta.status !== TRANSACTION_STATUSES.REJECTED, + (txMeta) => txMeta.status !== TransactionStatus.rejected, ); } } diff --git a/app/scripts/migrations/027.test.js b/app/scripts/migrations/027.test.js index 006bec019..add9b5c94 100644 --- a/app/scripts/migrations/027.test.js +++ b/app/scripts/migrations/027.test.js @@ -1,5 +1,5 @@ import firstTimeState from '../first-time-state'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import migration27 from './027'; const oldStorage = { @@ -14,9 +14,9 @@ const oldStorage = { const transactions = []; while (transactions.length < 9) { - transactions.push({ status: TRANSACTION_STATUSES.REJECTED }); - transactions.push({ status: TRANSACTION_STATUSES.UNAPPROVED }); - transactions.push({ status: TRANSACTION_STATUSES.APPROVED }); + transactions.push({ status: TransactionStatus.rejected }); + transactions.push({ status: TransactionStatus.unapproved }); + transactions.push({ status: TransactionStatus.approved }); } oldStorage.data.TransactionController.transactions = transactions; @@ -30,7 +30,7 @@ describe('migration #27', () => { expect(newTransactions).toHaveLength(6); newTransactions.forEach((txMeta) => { - if (txMeta.status === TRANSACTION_STATUSES.REJECTED) { + if (txMeta.status === TransactionStatus.rejected) { throw new Error('transaction was found with a status of rejected'); } }); diff --git a/app/scripts/migrations/029.js b/app/scripts/migrations/029.js index af70ee899..7d088bb29 100644 --- a/app/scripts/migrations/029.js +++ b/app/scripts/migrations/029.js @@ -1,5 +1,5 @@ // next version number -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import failTxsThat from './fail-tx'; const version = 29; @@ -23,7 +23,7 @@ export default { version, 'Stuck in approved state for too long.', (txMeta) => { - const isApproved = txMeta.status === TRANSACTION_STATUSES.APPROVED; + const isApproved = txMeta.status === TransactionStatus.approved; const createdTime = txMeta.submittedTime; const now = Date.now(); return isApproved && now - createdTime > unacceptableDelay; diff --git a/app/scripts/migrations/029.test.js b/app/scripts/migrations/029.test.js index e5ba056b8..95b3d8415 100644 --- a/app/scripts/migrations/029.test.js +++ b/app/scripts/migrations/029.test.js @@ -1,4 +1,4 @@ -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import migration29 from './029'; const properTime = new Date().getTime(); @@ -7,23 +7,23 @@ const storage = { data: { TransactionController: { transactions: [ - { status: TRANSACTION_STATUSES.APPROVED, id: 1, submittedTime: 0 }, + { status: TransactionStatus.approved, id: 1, submittedTime: 0 }, { - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, id: 2, submittedTime: properTime, }, { - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, id: 3, submittedTime: properTime, }, { - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, id: 4, submittedTime: properTime, }, - { status: TRANSACTION_STATUSES.SUBMITTED, id: 5, submittedTime: 0 }, + { status: TransactionStatus.submitted, id: 5, submittedTime: 0 }, ], }, }, @@ -36,13 +36,13 @@ describe('storage is migrated successfully where transactions that are submitted const [txMeta1] = txs; expect(migratedData.meta.version).toStrictEqual(29); - expect(txMeta1.status).toStrictEqual(TRANSACTION_STATUSES.FAILED); + expect(txMeta1.status).toStrictEqual(TransactionStatus.failed); txs.forEach((tx) => { if (tx.id === 1) { return; } - expect(tx.status).not.toStrictEqual(TRANSACTION_STATUSES.FAILED); + expect(tx.status).not.toStrictEqual(TransactionStatus.failed); }); }); }); diff --git a/app/scripts/migrations/053.js b/app/scripts/migrations/053.js index 318ce1614..472b36e66 100644 --- a/app/scripts/migrations/053.js +++ b/app/scripts/migrations/053.js @@ -1,5 +1,5 @@ import { cloneDeep } from 'lodash'; -import { TRANSACTION_TYPES } from '../../../shared/constants/transaction'; +import { TransactionType } from '../../../shared/constants/transaction'; const version = 53; @@ -25,8 +25,8 @@ function transformState(state) { transactions.forEach((transaction) => { if (transaction) { if ( - transaction.type !== TRANSACTION_TYPES.RETRY && - transaction.type !== TRANSACTION_TYPES.CANCEL + transaction.type !== TransactionType.retry && + transaction.type !== TransactionType.cancel ) { transaction.type = transaction.transactionCategory; } @@ -41,7 +41,7 @@ function transformState(state) { delete transaction.transactionCategory; state.IncomingTransactionsController.incomingTransactions[key] = { ...transaction, - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, }; } }); diff --git a/app/scripts/migrations/053.test.js b/app/scripts/migrations/053.test.js index e8f4651a9..640339fb7 100644 --- a/app/scripts/migrations/053.test.js +++ b/app/scripts/migrations/053.test.js @@ -1,7 +1,7 @@ -import { TRANSACTION_TYPES } from '../../../shared/constants/transaction'; +import { TransactionType } from '../../../shared/constants/transaction'; import migration53 from './053'; -const SENT_ETHER = 'sentEther'; // a legacy transaction type replaced now by TRANSACTION_TYPES.SIMPLE_SEND +const SENT_ETHER = 'sentEther'; // a legacy transaction type replaced now by TransactionType.simpleSend describe('migration #53', () => { it('should update the version metadata', async () => { @@ -25,7 +25,7 @@ describe('migration #53', () => { TransactionController: { transactions: [ { - type: TRANSACTION_TYPES.CANCEL, + type: TransactionType.cancel, transactionCategory: SENT_ETHER, txParams: { foo: 'bar' }, }, @@ -36,11 +36,11 @@ describe('migration #53', () => { }, { type: 'standard', - transactionCategory: TRANSACTION_TYPES.CONTRACT_INTERACTION, + transactionCategory: TransactionType.contractInteraction, txParams: { foo: 'bar' }, }, { - type: TRANSACTION_TYPES.RETRY, + type: TransactionType.retry, transactionCategory: SENT_ETHER, txParams: { foo: 'bar' }, }, @@ -64,16 +64,16 @@ describe('migration #53', () => { expect(newStorage.data).toStrictEqual({ TransactionController: { transactions: [ - { type: TRANSACTION_TYPES.CANCEL, txParams: { foo: 'bar' } }, + { type: TransactionType.cancel, txParams: { foo: 'bar' } }, { type: SENT_ETHER, txParams: { foo: 'bar' }, }, { - type: TRANSACTION_TYPES.CONTRACT_INTERACTION, + type: TransactionType.contractInteraction, txParams: { foo: 'bar' }, }, - { type: TRANSACTION_TYPES.RETRY, txParams: { foo: 'bar' } }, + { type: TransactionType.retry, txParams: { foo: 'bar' } }, ], }, IncomingTransactionsController: { diff --git a/app/scripts/migrations/059.js b/app/scripts/migrations/059.js index bbec1b9b8..ac02b6714 100644 --- a/app/scripts/migrations/059.js +++ b/app/scripts/migrations/059.js @@ -6,7 +6,7 @@ import { pickBy, isPlainObject, } from 'lodash'; -import { TRANSACTION_TYPES } from '../../../shared/constants/transaction'; +import { TransactionType } from '../../../shared/constants/transaction'; const version = 59; @@ -38,8 +38,8 @@ function transformState(state) { const withoutOrphans = pickBy(nonceNetworkGroupedObject, (group) => { return group.some( (tx) => - tx.type !== TRANSACTION_TYPES.CANCEL && - tx.type !== TRANSACTION_TYPES.RETRY, + tx.type !== TransactionType.cancel && + tx.type !== TransactionType.retry, ); }); state.TransactionController.transactions = keyBy( diff --git a/app/scripts/migrations/059.test.js b/app/scripts/migrations/059.test.js index 34065213c..f440f970b 100644 --- a/app/scripts/migrations/059.test.js +++ b/app/scripts/migrations/059.test.js @@ -1,16 +1,16 @@ import { cloneDeep } from 'lodash'; import { CHAIN_IDS } from '../../../shared/constants/network'; import { - TRANSACTION_TYPES, - TRANSACTION_STATUSES, + TransactionType, + TransactionStatus, } from '../../../shared/constants/transaction'; import migration59 from './059'; -const SENT_ETHER = 'sentEther'; // a legacy transaction type replaced now by TRANSACTION_TYPES.SIMPLE_SEND +const SENT_ETHER = 'sentEther'; // a legacy transaction type replaced now by TransactionType.simpleSend const ERRONEOUS_TRANSACTION_STATE = { 0: { - type: TRANSACTION_TYPES.CANCEL, + type: TransactionType.cancel, id: 0, chainId: CHAIN_IDS.MAINNET, txParams: { @@ -85,7 +85,7 @@ const ERRONEOUS_TRANSACTION_STATE = { type: SENT_ETHER, id: 9, chainId: '0x4', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, }, }; @@ -93,14 +93,14 @@ const ERRONEOUS_TRANSACTION_STATE_RETRY = { ...ERRONEOUS_TRANSACTION_STATE, 0: { ...ERRONEOUS_TRANSACTION_STATE[0], - type: TRANSACTION_TYPES.RETRY, + type: TransactionType.retry, }, }; const ERRONEOUS_TRANSACTION_STATE_MIXED = { ...ERRONEOUS_TRANSACTION_STATE, 10: { - type: TRANSACTION_TYPES.RETRY, + type: TransactionType.retry, id: 10, chainId: CHAIN_IDS.MAINNET, txParams: { @@ -108,7 +108,7 @@ const ERRONEOUS_TRANSACTION_STATE_MIXED = { }, }, 11: { - type: TRANSACTION_TYPES.RETRY, + type: TransactionType.retry, id: 11, chainId: CHAIN_IDS.MAINNET, txParams: { diff --git a/app/scripts/migrations/064.js b/app/scripts/migrations/064.js index 01c384234..a31833908 100644 --- a/app/scripts/migrations/064.js +++ b/app/scripts/migrations/064.js @@ -1,9 +1,9 @@ import { cloneDeep, isPlainObject } from 'lodash'; -import { TRANSACTION_TYPES } from '../../../shared/constants/transaction'; +import { TransactionType } from '../../../shared/constants/transaction'; const version = 64; -const SENT_ETHER = 'sentEther'; // the legacy transaction type being replaced in this migration with TRANSACTION_TYPES.SIMPLE_SEND +const SENT_ETHER = 'sentEther'; // the legacy transaction type being replaced in this migration with TransactionType.simpleSend /** * Removes metaMetricsSendCount from MetaMetrics controller @@ -25,12 +25,12 @@ function transformState(state) { if (isPlainObject(transactions)) { for (const tx of Object.values(transactions)) { if (tx.type === SENT_ETHER) { - tx.type = TRANSACTION_TYPES.SIMPLE_SEND; + tx.type = TransactionType.simpleSend; } if (tx.history) { tx.history.map((txEvent) => { if (txEvent.type && txEvent.type === SENT_ETHER) { - txEvent.type = TRANSACTION_TYPES.SIMPLE_SEND; + txEvent.type = TransactionType.simpleSend; } return txEvent; }); diff --git a/app/scripts/migrations/064.test.js b/app/scripts/migrations/064.test.js index ec8360695..b2dd676bd 100644 --- a/app/scripts/migrations/064.test.js +++ b/app/scripts/migrations/064.test.js @@ -1,8 +1,8 @@ import { CHAIN_IDS } from '../../../shared/constants/network'; -import { TRANSACTION_TYPES } from '../../../shared/constants/transaction'; +import { TransactionType } from '../../../shared/constants/transaction'; import migration64 from './064'; -const SENT_ETHER = 'sentEther'; // the legacy transaction type being replaced in this migration with TRANSACTION_TYPES.SIMPLE_SEND +const SENT_ETHER = 'sentEther'; // the legacy transaction type being replaced in this migration with TransactionType.simpleSend describe('migration #64', () => { it('should update the version metadata', async () => { @@ -82,7 +82,7 @@ describe('migration #64', () => { it('should change action type of "sentEther" to "simpleSend" for any transactions and transaction history events in transactionsController.transactions', async () => { const OLD_TRANSACTION_STATE = { 1462177651588364: { - type: TRANSACTION_TYPES.CANCEL, + type: TransactionType.cancel, id: 0, chainId: CHAIN_IDS.MAINNET, txParams: { @@ -261,7 +261,7 @@ describe('migration #64', () => { const EXPECTED_TRANSACTION_STATE = { 1462177651588364: { - type: TRANSACTION_TYPES.CANCEL, + type: TransactionType.cancel, id: 0, chainId: CHAIN_IDS.MAINNET, txParams: { @@ -277,7 +277,7 @@ describe('migration #64', () => { hash: '0x4d8543f12afd3795b94d723dcd0e20bfc3740e1af668e5e90a0c5ec49f36ba12', }, 1: { - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, id: 1, chainId: CHAIN_IDS.MAINNET, txParams: { @@ -301,7 +301,7 @@ describe('migration #64', () => { gas: '0x31413', value: '0x0', }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, }, [ { @@ -389,7 +389,7 @@ describe('migration #64', () => { }, type: '0x2', }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, history: [ { chainId: '0x4', diff --git a/app/scripts/migrations/fail-tx.js b/app/scripts/migrations/fail-tx.js index 0fedb6052..b89ad8b58 100644 --- a/app/scripts/migrations/fail-tx.js +++ b/app/scripts/migrations/fail-tx.js @@ -1,5 +1,5 @@ import { cloneDeep } from 'lodash'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; export default function failTxsThat(version, reason, condition) { return function (originalVersionedData) { @@ -27,7 +27,7 @@ function transformState(state, condition, reason) { return txMeta; } - txMeta.status = TRANSACTION_STATUSES.FAILED; + txMeta.status = TransactionStatus.failed; txMeta.err = { message: reason, note: `Tx automatically failed by migration because ${reason}`, diff --git a/app/scripts/platforms/extension.js b/app/scripts/platforms/extension.js index 327262a56..a3f7d1b91 100644 --- a/app/scripts/platforms/extension.js +++ b/app/scripts/platforms/extension.js @@ -4,7 +4,7 @@ import { getBlockExplorerLink } from '@metamask/etherscan-link'; import { startCase, toLower } from 'lodash'; import { getEnvironmentType } from '../lib/util'; import { ENVIRONMENT_TYPE_BACKGROUND } from '../../../shared/constants/app'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import { getURLHostName } from '../../../ui/helpers/utils/util'; export default class ExtensionPlatform { @@ -116,7 +116,7 @@ export default class ExtensionPlatform { showTransactionNotification(txMeta, rpcPrefs) { const { status, txReceipt: { status: receiptStatus } = {} } = txMeta; - if (status === TRANSACTION_STATUSES.CONFIRMED) { + if (status === TransactionStatus.confirmed) { // There was an on-chain failure receiptStatus === '0x0' ? this._showFailedTransaction( @@ -124,7 +124,7 @@ export default class ExtensionPlatform { 'Transaction encountered an error.', ) : this._showConfirmedTransaction(txMeta, rpcPrefs); - } else if (status === TRANSACTION_STATUSES.FAILED) { + } else if (status === TransactionStatus.failed) { this._showFailedTransaction(txMeta); } } diff --git a/development/ts-migration-dashboard/files-to-convert.json b/development/ts-migration-dashboard/files-to-convert.json index b479cd2d3..d6e65d860 100644 --- a/development/ts-migration-dashboard/files-to-convert.json +++ b/development/ts-migration-dashboard/files-to-convert.json @@ -766,8 +766,8 @@ "ui/components/app/transaction-list/index.js", "ui/components/app/transaction-list/transaction-list.component.js", "ui/components/app/transaction-list/transaction-list.stories.js", - "ui/components/app/transaction-status/transaction-status.component.js", - "ui/components/app/transaction-status/transaction-status.component.test.js", + "ui/components/app/transaction-status-label/transaction-status-label.js", + "ui/components/app/transaction-status-label/transaction-status-label.test.js", "ui/components/app/transaction-total-banner/index.js", "ui/components/app/transaction-total-banner/transaction-total-banner.component.js", "ui/components/app/transaction-total-banner/transaction-total-banner.stories.js", diff --git a/development/verify-locale-strings.js b/development/verify-locale-strings.js index d9f27810a..009e513e6 100755 --- a/development/verify-locale-strings.js +++ b/development/verify-locale-strings.js @@ -178,7 +178,12 @@ async function verifyEnglishLocale() { ]; const testGlob = '**/*.test.js'; const javascriptFiles = await glob( - ['ui/**/*.js', 'shared/**/*.js', 'app/scripts/constants/**/*.js'], + [ + 'ui/**/*.js', + 'shared/**/*.js', + 'shared/**/*.ts', + 'app/scripts/constants/**/*.js', + ], { ignore: [...globsToStrictSearch, testGlob], }, diff --git a/package.json b/package.json index ea88b8716..b3ba01863 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "forwarder": "node ./development/static-server.js ./node_modules/@metamask/forwarder/dist/ --port 9010", "dapp-forwarder": "concurrently -k -n forwarder,dapp -p '[{time}][{name}]' 'yarn forwarder' 'yarn dapp'", "test:unit": "node ./test/run-unit-tests.js --mocha --jestGlobal --jestDev", - "test:unit:jest": "./test/test-unit-jest.sh", + "test:unit:jest": "node ./test/run-unit-tests.js --jestGlobal --jestDev", "test:unit:global": "mocha test/unit-global/*.test.js", "test:unit:mocha": "node ./test/run-unit-tests.js --mocha", "test:e2e:chrome": "SELENIUM_BROWSER=chrome node test/e2e/run-all.js", diff --git a/shared/constants/transaction.js b/shared/constants/transaction.js deleted file mode 100644 index 37c2e45e3..000000000 --- a/shared/constants/transaction.js +++ /dev/null @@ -1,423 +0,0 @@ -import { MESSAGE_TYPE } from './app'; - -/** - * Transaction Type is a MetaMask construct used internally - * - * @typedef {object} TransactionTypes - * @property {'transfer'} TOKEN_METHOD_TRANSFER - A token transaction where the user - * is sending tokens that they own to another address - * @property {'transferfrom'} TOKEN_METHOD_TRANSFER_FROM - A token transaction - * transferring tokens from an account that the sender has an allowance of. - * For more information on allowances, see the approve type. - * @property {'safetransferfrom'} TOKEN_METHOD_SAFE_TRANSFER_FROM - A token transaction - * transferring tokens from an account that the sender has an allowance of. - * The method is prefixed with safe because when calling this method the contract checks - * to ensure that the receiver is an address capable of handling with the token being sent. - * @property {'approve'} TOKEN_METHOD_APPROVE - A token transaction requesting an - * allowance of the token to spend on behalf of the user - * @property {'setapprovalforall'} TOKEN_METHOD_SET_APPROVAL_FOR_ALL - A token transaction requesting an - * allowance of all of a user's token to spend on behalf of the user - * @property {'incoming'} INCOMING - An incoming (deposit) transaction - * @property {'simpleSend'} SIMPLE_SEND - A transaction sending a network's native asset to a recipient - * @property {'contractInteraction'} CONTRACT_INTERACTION - A transaction that is - * interacting with a smart contract's methods that we have not treated as a special - * case, such as approve, transfer, and transferfrom - * @property {'contractDeployment'} DEPLOY_CONTRACT - A transaction that deployed - * a smart contract - * @property {'swap'} SWAP - A transaction swapping one token for another through - * MetaMask Swaps - * @property {'swapApproval'} SWAP_APPROVAL - Similar to the approve type, a swap - * approval is a special case of ERC20 approve method that requests an allowance of - * the token to spend on behalf of the user for the MetaMask Swaps contract. The first - * swap for any token will have an accompanying swapApproval transaction. - * @property {'cancel'} CANCEL - A transaction submitted with the same nonce as a - * previous transaction, a higher gas price and a zeroed out send amount. Useful - * for users who accidentally send to erroneous addresses or if they send too much. - * @property {'retry'} RETRY - When a transaction is failed it can be retried by - * resubmitting the same transaction with a higher gas fee. This type is also used - * to speed up pending transactions. This is accomplished by creating a new tx with - * the same nonce and higher gas fees. - */ - -/** - * This type will work anywhere you expect a string that can be one of the - * above transaction types. - * - * @typedef {TransactionTypes[keyof TransactionTypes]} TransactionTypeString - */ - -/** - * @type {TransactionTypes} - */ -export const TRANSACTION_TYPES = { - CANCEL: 'cancel', - CONTRACT_INTERACTION: 'contractInteraction', - DEPLOY_CONTRACT: 'contractDeployment', - ETH_DECRYPT: MESSAGE_TYPE.ETH_DECRYPT, - ETH_GET_ENCRYPTION_PUBLIC_KEY: MESSAGE_TYPE.ETH_GET_ENCRYPTION_PUBLIC_KEY, - INCOMING: 'incoming', - PERSONAL_SIGN: MESSAGE_TYPE.PERSONAL_SIGN, - RETRY: 'retry', - SIGN: MESSAGE_TYPE.ETH_SIGN, - SIGN_TYPED_DATA: MESSAGE_TYPE.ETH_SIGN_TYPED_DATA, - SIMPLE_SEND: 'simpleSend', - SMART: 'smart', - SWAP: 'swap', - SWAP_APPROVAL: 'swapApproval', - TOKEN_METHOD_APPROVE: 'approve', - TOKEN_METHOD_SAFE_TRANSFER_FROM: 'safetransferfrom', - TOKEN_METHOD_TRANSFER: 'transfer', - TOKEN_METHOD_TRANSFER_FROM: 'transferfrom', - TOKEN_METHOD_SET_APPROVAL_FOR_ALL: 'setapprovalforall', -}; - -/** - * In EIP-2718 typed transaction envelopes were specified, with the very first - * typed envelope being 'legacy' and describing the shape of the base - * transaction params that were hitherto the only transaction type sent on - * Ethereum. - * - * @typedef {object} TransactionEnvelopeTypes - * @property {'0x0'} LEGACY - A legacy transaction, the very first type. - * @property {'0x1'} ACCESS_LIST - EIP-2930 defined the access list transaction - * type that allowed for specifying the state that a transaction would act - * upon in advance and theoretically save on gas fees. - * @property {'0x2'} FEE_MARKET - The type introduced comes from EIP-1559, - * Fee Market describes the addition of a baseFee to blocks that will be - * burned instead of distributed to miners. Transactions of this type have - * both a maxFeePerGas (maximum total amount in gwei per gas to spend on the - * transaction) which is inclusive of the maxPriorityFeePerGas (maximum amount - * of gwei per gas from the transaction fee to distribute to miner). - */ - -/** - * @type {TransactionEnvelopeTypes} - */ -export const TRANSACTION_ENVELOPE_TYPES = { - LEGACY: '0x0', - ACCESS_LIST: '0x1', - FEE_MARKET: '0x2', -}; - -/** - * Transaction Status is a mix of Ethereum and MetaMask terminology, used internally - * for transaction processing. - * - * @typedef {object} TransactionStatuses - * @property {'unapproved'} UNAPPROVED - A new transaction that the user has not - * approved or rejected - * @property {'approved'} APPROVED - The user has approved the transaction in the - * MetaMask UI - * @property {'rejected'} REJECTED - The user has rejected the transaction in the - * MetaMask UI - * @property {'signed'} SIGNED - The transaction has been signed - * @property {'submitted'} SUBMITTED - The transaction has been submitted to network - * @property {'failed'} FAILED - The transaction has failed for some reason - * @property {'dropped'} DROPPED - The transaction was dropped due to a tx with same - * nonce being accepted - * @property {'confirmed'} CONFIRMED - The transaction was confirmed by the network - */ - -/** - * This type will work anywhere you expect a string that can be one of the - * above transaction statuses. - * - * @typedef {TransactionStatuses[keyof TransactionStatuses]} TransactionStatusString - */ - -/** - * @type {TransactionStatuses} - */ -export const TRANSACTION_STATUSES = { - UNAPPROVED: 'unapproved', - APPROVED: 'approved', - REJECTED: 'rejected', - SIGNED: 'signed', - SUBMITTED: 'submitted', - FAILED: 'failed', - DROPPED: 'dropped', - CONFIRMED: 'confirmed', - PENDING: 'pending', -}; - -/** - * With this list we can detect if a transaction is still in progress. - */ -export const IN_PROGRESS_TRANSACTION_STATUSES = [ - TRANSACTION_STATUSES.UNAPPROVED, - TRANSACTION_STATUSES.APPROVED, - TRANSACTION_STATUSES.SIGNED, - TRANSACTION_STATUSES.SUBMITTED, - TRANSACTION_STATUSES.PENDING, -]; - -/** - * Transaction Group Status is a MetaMask construct to track the status of groups - * of transactions. - * - * @typedef {object} TransactionGroupStatuses - * @property {'cancelled'} CANCELLED - A cancel type transaction in the group was - * confirmed - * @property {'pending'} PENDING - The primaryTransaction of the group has a status - * that is one of TRANSACTION_STATUSES.APPROVED, TRANSACTION_STATUSES.UNAPPROVED - * or TRANSACTION_STATUSES.SUBMITTED - */ - -/** - * @type {TransactionGroupStatuses} - */ -export const TRANSACTION_GROUP_STATUSES = { - CANCELLED: 'cancelled', - PENDING: 'pending', -}; - -/** - * Statuses that are specific to Smart Transactions. - * - * @typedef {object} SmartTransactionStatuses - * @property {'cancelled'} CANCELLED - It can be cancelled for various reasons. - * @property {'pending'} PENDING - Smart transaction is being processed. - * @property {'success'} SUCCESS - Smart transaction was successfully mined. - */ - -/** - * @type {SmartTransactionStatuses} - */ -export const SMART_TRANSACTION_STATUSES = { - CANCELLED: 'cancelled', - PENDING: 'pending', - SUCCESS: 'success', -}; - -/** - * Types that are specific to the transaction approval amount. - * - * @typedef {object} TransactionApprovalAmountType - * @property {'custom'} CUSTOM - The user has edited the token amount. - * @property {'revoke'} REVOKE - The selected amount (either CUSTOM or DAPP_PROPOSED) is 0. - * @property {'dapp_proposed'} DAPP_PROPOSED - The dapp proposed token amount. - */ - -/** - * @type {TransactionApprovalAmountType} - */ -export const TRANSACTION_APPROVAL_AMOUNT_TYPE = { - CUSTOM: 'custom', - REVOKE: 'revoke', - DAPP_PROPOSED: 'dapp_proposed', -}; - -/** - * Transaction Group Category is a MetaMask construct to categorize the intent - * of a group of transactions for purposes of displaying in the UI - * - * @typedef {object} TransactionGroupCategories - * @property {'send'} SEND - Transaction group representing ether being sent from - * the user. - * @property {'receive'} RECEIVE - Transaction group representing a deposit/incoming - * transaction. This category maps 1:1 with TRANSACTION_CATEGORIES.INCOMING. - * @property {'interaction'} INTERACTION - Transaction group representing - * an interaction with a smart contract's methods. - * @property {'approval'} APPROVAL - Transaction group representing a request for an - * allowance of a token to spend on the user's behalf. - * @property {'signature-request'} SIGNATURE_REQUEST - Transaction group representing - * a signature request This currently only shows up in the UI when its pending user - * approval in the UI. Once the user approves or rejects it will no longer show in - * activity. - * @property {'swap'} SWAP - Transaction group representing a token swap through - * MetaMask Swaps. This transaction group's primary currency changes depending - * on context. If the user is viewing an asset page for a token received from a swap, - * the primary currency will be the received token. Otherwise the token exchanged - * will be shown. - */ - -/** - * @type {TransactionGroupCategories} - */ -export const TRANSACTION_GROUP_CATEGORIES = { - APPROVAL: 'approval', - INTERACTION: 'interaction', - RECEIVE: 'receive', - SEND: 'send', - SIGNATURE_REQUEST: 'signature-request', - SWAP: 'swap', -}; - -/** - * @typedef {object} TxParams - * @property {string} from - The address the transaction is sent from - * @property {string} to - The address the transaction is sent to - * @property {string} value - The amount of wei, in hexadecimal, to send - * @property {number} nonce - The transaction count for the current account/network - * @property {string} gasPrice - The amount of gwei, in hexadecimal, per unit of gas - * @property {string} gas - The max amount of gwei, in hexadecimal, the user is willing to pay - * @property {string} [data] - Hexadecimal encoded string representing calls to the EVM's ABI - */ - -/** - * @typedef {object} TxError - * @property {string} message - The message from the encountered error. - * @property {any} rpc - The "value" of the error. - * @property {string} [stack] - the stack trace from the error, if available. - */ - -/** - * An object representing a transaction, in whatever state it is in. - * - * @typedef {object} TransactionMeta - * @property {string} [blockNumber] - The block number this transaction was - * included in. Currently only present on incoming transactions! - * @property {number} id - An internally unique tx identifier. - * @property {number} time - Time the transaction was first suggested, in unix - * epoch time (ms). - * @property {string} contractMethodName - A string representing a name of - * transaction contract method. - * @property {string} customTokenAmount - The custom token amount is the amount - * set by the user - * @property {string} dappProposedTokenAmount - The dapp proposed token amount - * @property {string} currentTokenBalance - The balance of the token that is - * being send - * @property {string} originalApprovalAmount - The original approval amount - * is the originally dapp proposed token amount - * @property {string} finalApprovalAmount - The chosen amount which will be the - * same as the originally proposed token amount if the user does not edit the - * amount or will be a custom token amount set by the user - * @property {TransactionTypeString} type - The type of transaction this txMeta - * represents. - * @property {string} originalType - When we speed up a transaction, - * we set the type as Retry and we lose information about type of transaction - * that is being set up, so we use original type to track that information. - * @property {TransactionStatusString} status - The current status of the - * transaction. - * @property {string} metamaskNetworkId - The transaction's network ID, used - * for EIP-155 compliance. - * @property {boolean} loadingDefaults - TODO: Document - * @property {TxParams} txParams - The transaction params as passed to the - * network provider. - * @property {object[]} history - A history of mutations to this - * TransactionMeta object. - * @property {string} origin - A string representing the interface that - * suggested the transaction. - * @property {string} originalGasEstimate - A string representing the original - * gas estimation on the transaction metadata. - * @property {boolean} userEditedGasLimit - A boolean representing when the - * user manually edited the gas limit. - * @property {object} nonceDetails - A metadata object containing information - * used to derive the suggested nonce, useful for debugging nonce issues. - * @property {string} rawTx - A hex string of the final signed transaction, - * ready to submit to the network. - * @property {string} hash - A hex string of the transaction hash, used to - * identify the transaction on the network. - * @property {number} [submittedTime] - The time the transaction was submitted to - * the network, in Unix epoch time (ms). - * @property {TxError} [err] - The error encountered during the transaction - */ - -/** - * Defines the possible types - * - * @typedef {object} TransactionMetaMetricsEvents - * @property {'Transaction Added'} ADDED - All transactions, except incoming - * ones, are added to the controller state in an unapproved status. When this - * happens we fire the Transaction Added event to show that the transaction - * has been added to the user's MetaMask. - * @property {'Transaction Approved'} APPROVED - When an unapproved transaction - * is in the controller state, MetaMask will render a confirmation screen for - * that transaction. If the user approves the transaction we fire this event - * to indicate that the user has approved the transaction for submission to - * the network. - * @property {'Transaction Rejected'} REJECTED - When an unapproved transaction - * is in the controller state, MetaMask will render a confirmation screen for - * that transaction. If the user rejects the transaction we fire this event - * to indicate that the user has rejected the transaction. It will be removed - * from state as a result. - * @property {'Transaction Submitted'} SUBMITTED - After a transaction is - * approved by the user, it is then submitted to the network for inclusion in - * a block. When this happens we fire the Transaction Submitted event to - * indicate that MetaMask is submitting a transaction at the user's request. - * @property {'Transaction Finalized'} FINALIZED - All transactions that are - * submitted will finalized (eventually) by either being dropped, failing - * or being confirmed. When this happens we track this event, along with the - * status. - */ - -/** - * This type will work anywhere you expect a string that can be one of the - * above transaction event types. - * - * @typedef {TransactionMetaMetricsEvents[keyof TransactionMetaMetricsEvents]} TransactionMetaMetricsEventString - */ - -/** - * @type {TransactionMetaMetricsEvents} - */ -export const TRANSACTION_EVENTS = { - ADDED: 'Transaction Added', - APPROVED: 'Transaction Approved', - FINALIZED: 'Transaction Finalized', - REJECTED: 'Transaction Rejected', - SUBMITTED: 'Transaction Submitted', -}; - -/** - * @typedef {object} AssetTypes - * @property {'NATIVE'} NATIVE - The native asset for the current network, such - * as ETH - * @property {'TOKEN'} TOKEN - An ERC20 token. - * @property {'NFT'} NFT - An ERC721 or ERC1155 token. - * @property {'UNKNOWN'} UNKNOWN - A transaction interacting with a contract - * that isn't a token method interaction will be marked as dealing with an - * unknown asset type. - */ - -/** - * This type will work anywhere you expect a string that can be one of the - * above asset types - * - * @typedef {AssetTypes[keyof AssetTypes]} AssetTypesString - */ - -/** - * The types of assets that a user can send - * - * @type {AssetTypes} - */ -export const ASSET_TYPES = { - NATIVE: 'NATIVE', - TOKEN: 'TOKEN', - NFT: 'NFT', - UNKNOWN: 'UNKNOWN', -}; - -export const ERC20 = 'ERC20'; -export const ERC721 = 'ERC721'; -export const ERC1155 = 'ERC1155'; - -/** - * @typedef {object} TokenStandards - * @property {'ERC20'} ERC20 - A token that conforms to the ERC20 standard. - * @property {'ERC721'} ERC721 - A token that conforms to the ERC721 standard. - * @property {'ERC1155'} ERC1155 - A token that conforms to the ERC1155 - * standard. - * @property {'NONE'} NONE - Not a token, but rather the base asset of the - * selected chain. - */ - -/** - * This type will work anywhere you expect a string that can be one of the - * above statuses - * - * @typedef {TokenStandards[keyof TokenStandards]} TokenStandardStrings - */ - -/** - * Describes the standard which a token conforms to. - * - * @type {TokenStandards} - */ -export const TOKEN_STANDARDS = { - ERC20, - ERC721, - ERC1155, - NONE: 'NONE', -}; diff --git a/shared/constants/transaction.ts b/shared/constants/transaction.ts new file mode 100644 index 000000000..e766aba5e --- /dev/null +++ b/shared/constants/transaction.ts @@ -0,0 +1,426 @@ +export enum TransactionType { + /** + * A transaction submitted with the same nonce as a previous transaction, a + * higher gas price and a zeroed out send amount. Useful for users who + * accidentally send to erroneous addresses or if they send too much. + */ + cancel = 'cancel', + /** + * A transaction that is interacting with a smart contract's methods that we + * have not treated as a special case, such as approve, transfer, and + * transferfrom + */ + contractInteraction = 'contractInteraction', + /** + * A transaction that deployed a smart contract + */ + deployContract = 'contractDeployment', + ethDecrypt = 'eth_decrypt', + ethGetEncryptionPublicKey = 'eth_getEncryptionPublicKey', + /** + * An incoming (deposit) transaction + */ + incoming = 'incoming', + personalSign = 'personal_sign', + /** + * When a transaction is failed it can be retried by + * resubmitting the same transaction with a higher gas fee. This type is also used + * to speed up pending transactions. This is accomplished by creating a new tx with + * the same nonce and higher gas fees. + */ + retry = 'retry', + sign = 'eth_sign', + signTypedData = 'eth_signTypedData', + /** A transaction sending a network's native asset to a recipient */ + simpleSend = 'simpleSend', + smart = 'smart', + /** + * A transaction swapping one token for another through MetaMask Swaps + */ + swap = 'swap', + /** + * Similar to the approve type, a swap approval is a special case of ERC20 + * approve method that requests an allowance of the token to spend on behalf + * of the user for the MetaMask Swaps contract. The first swap for any token + * will have an accompanying swapApproval transaction. + */ + swapApproval = 'swapApproval', + /** + * A token transaction requesting an allowance of the token to spend on + * behalf of the user + */ + tokenMethodApprove = 'approve', + /** + * A token transaction transferring tokens from an account that the sender + * has an allowance of. The method is prefixed with safe because when calling + * this method the contract checks to ensure that the receiver is an address + * capable of handling with the token being sent. + */ + tokenMethodSafeTransferFrom = 'safetransferfrom', + /** + * A token transaction where the user is sending tokens that they own to + * another address + */ + tokenMethodTransfer = 'transfer', + /** + * A token transaction transferring tokens from an account that the sender + * has an allowance of. For more information on allowances, see the approve + * type. + */ + tokenMethodTransferFrom = 'transferfrom', + /** + * A token transaction requesting an allowance of all of a user's token to + * spend on behalf of the user + */ + tokenMethodSetApprovalForAll = 'setapprovalforall', +} + +/** + * In EIP-2718 typed transaction envelopes were specified, with the very first + * typed envelope being 'legacy' and describing the shape of the base + * transaction params that were hitherto the only transaction type sent on + * Ethereum. + */ +export enum TransactionEnvelopeType { + /** + * A legacy transaction, the very first type. + */ + legacy = '0x0', + /** + * EIP-2930 defined the access list transaction type that allowed for + * specifying the state that a transaction would act upon in advance and + * theoretically save on gas fees. + */ + accessList = '0x1', + /** + * The type introduced comes from EIP-1559, Fee Market describes the addition + * of a baseFee to blocks that will be burned instead of distributed to + * miners. Transactions of this type have both a maxFeePerGas (maximum total + * amount in gwei per gas to spend on the transaction) which is inclusive of + * the maxPriorityFeePerGas (maximum amount of gwei per gas from the + * transaction fee to distribute to miner). + */ + feeMarket = '0x2', +} + +/** + * Transaction Status is a mix of Ethereum and MetaMask terminology, used internally + * for transaction processing. + */ +export enum TransactionStatus { + /** + * A new transaction that the user has not approved or rejected + */ + unapproved = 'unapproved', + /** + * The user has approved the transaction in the MetaMask UI + */ + approved = 'approved', + /** + * The user has rejected the transaction in the MetaMask UI + */ + rejected = 'rejected', + /** + * The transaction has been signed + */ + signed = 'signed', + /** + * The transaction has been submitted to network + */ + submitted = 'submitted', + /** + * The transaction has failed for some reason + */ + failed = 'failed', + /** + * The transaction was dropped due to a tx with same nonce being accepted + */ + dropped = 'dropped', + /** + * The transaction was confirmed by the network + */ + confirmed = 'confirmed', + /** + * The transaction has been signed and is waiting to either be confirmed, + * dropped or failed. This is a "fake" status that we use to group statuses + * that are very similar from the user's perspective (approved, + * signed, submitted). The only notable case where approve and signed are + * different from user perspective is in hardware wallets where the + * transaction is signed on an external device. Otherwise signing happens + * transparently to users. + */ + pending = 'pending', +} + +/** + * With this list we can detect if a transaction is still in progress. + */ +export const IN_PROGRESS_TRANSACTION_STATUSES = [ + TransactionStatus.unapproved, + TransactionStatus.approved, + TransactionStatus.signed, + TransactionStatus.submitted, + TransactionStatus.pending, +]; + +/** + * Transaction Group Status is a MetaMask construct to track the status of groups + * of transactions. + */ +export enum TransactionGroupStatus { + /** + * A cancel type transaction in the group was confirmed + */ + cancelled = 'cancelled', + /** + * The primaryTransaction of the group has a status that is one of + * TransactionStatus.approved, TransactionStatus.unapproved or + * TransactionStatus.submitted + */ + pending = 'pending', +} + +/** + * Statuses that are specific to Smart Transactions. + */ +export enum SmartTransactionStatus { + /** It can be cancelled for various reasons. */ + cancelled = 'cancelled', + /** Smart transaction is being processed. */ + pending = 'pending', + /** Smart transaction was successfully mined. */ + success = 'success', +} + +/** + * Types that are specific to the transaction approval amount. + */ +export enum TransactionApprovalAmountType { + /** The user has edited the token amount. */ + custom = 'custom', + /** The selected amount (either custom or dappProposed) is 0. */ + revoke = 'revoke', + /** The dapp proposed token amount. */ + dappProposed = 'dapp_proposed', +} + +/** + * Transaction Group Category is a MetaMask construct to categorize the intent + * of a group of transactions for purposes of displaying in the UI + */ +export enum TransactionGroupCategory { + /** + * Transaction group representing a request for an allowance of a token to + * spend on the user's behalf. + */ + approval = 'approval', + /** + * Transaction group representing an interaction with a smart contract's methods. + */ + interaction = 'interaction', + /** + * Transaction group representing a deposit/incoming transaction. This + * category maps 1:1 with TransactionType.incoming. + */ + receive = 'receive', + /** + * Transaction group representing the network native currency being sent from + * the user. + */ + send = 'send', + /** + * Transaction group representing a signature request This currently only + * shows up in the UI when its pending user approval in the UI. Once the user + * approves or rejects it will no longer show in activity. + */ + signatureRequest = 'signature-request', + /** + * Transaction group representing a token swap through MetaMask Swaps. This + * transaction group's primary currency changes depending on context. If the + * user is viewing an asset page for a token received from a swap, the + * primary currency will be the received token. Otherwise the token exchanged + * will be shown. + */ + swap = 'swap', +} + +/** + * An object representing parameters of a transaction to submit to the network + */ +export interface TxParams { + /** The address the transaction is sent from */ + from: string; + /** The address the transaction is sent to */ + to: string; + /** The amount of wei, in hexadecimal, to send */ + value: string; + /** The transaction count for the current account/network */ + nonce: number; + /** The amount of gwei, in hexadecimal, per unit of gas */ + gasPrice: string; + /** The max amount of gwei, in hexadecimal, the user is willing to pay */ + gas: string; + /** Hexadecimal encoded string representing calls to the EVM's ABI */ + data?: string; +} + +export interface TxError { + /** The message from the encountered error. */ + message: string; + /** The "value" of the error. */ + rpc: any; + /** the stack trace from the error, if available. */ + stack?: string; +} + +/** + * An object representing a transaction, in whatever state it is in. + */ +export interface TransactionMeta { + /** + * The block number this transaction was included in. Currently only present + * on incoming transactions! + */ + blockNumber?: string; + /** An internally unique tx identifier. */ + id: number; + /** Time the transaction was first suggested, in unix epoch time (ms). */ + time: number; + /** A string representing a name of transaction contract method. */ + contractMethodName: string; + /** The custom token amount is the amount set by the user */ + customTokenAmount: string; + /** The dapp proposed token amount */ + dappProposedTokenAmount: string; + /** The balance of the token that is being sent */ + currentTokenBalance: string; + /** The original dapp proposed token approval amount before edit by user */ + originalApprovalAmount: string; + /** + * The chosen amount which will be the same as the originally proposed token + * amount if the user does not edit the amount or will be a custom token + * amount set by the user + */ + finalApprovalAmount: string; + /** The type of transaction this txMeta represents. */ + type: TransactionType; + /** + * When we speed up a transaction, we set the type as Retry and we lose + * information about type of transaction that is being set up, so we use + * original type to track that information. + */ + originalType: TransactionType; + /** The current status of the transaction. */ + status: TransactionStatus; + /** The transaction's network ID, used for EIP-155 compliance. */ + metamaskNetworkId: string; + /** TODO: Find out what this is and document it */ + loadingDefaults: boolean; + /** The transaction params as passed to the network provider. */ + txParams: TxParams; + /** A history of mutations to this TransactionMeta object. */ + history: Record[]; + /** A string representing the interface that suggested the transaction. */ + origin: string; + /** + * A string representing the original gas estimation on the transaction + * metadata. + */ + originalGasEstimate: string; + /** A boolean representing when the user manually edited the gas limit. */ + userEditedGasLimit: boolean; + /** + * A metadata object containing information used to derive the suggested + * nonce, useful for debugging nonce issues. + */ + nonceDetails: Record; + /** + * A hex string of the final signed transaction, ready to submit to the + * network. + */ + rawTx: string; + /** + * A hex string of the transaction hash, used to identify the transaction + * on the network. + */ + hash: string; + /** + * The time the transaction was submitted to the network, in Unix epoch time + * (ms). + */ + submittedTime?: number; + /** The error encountered during the transaction */ + txErr?: TxError; +} + +/** + * Defines the possible types + */ +export enum TransactionMetaMetricsEvent { + /** + * All transactions, except incoming ones, are added to the controller state + * in an unapproved status. When this happens we fire the Transaction Added + * event to show that the transaction has been added to the user's MetaMask. + */ + added = 'Transaction Added', + /** + * When an unapproved transaction is in the controller state, MetaMask will + * render a confirmation screen for that transaction. If the user approves + * the transaction we fire this event to indicate that the user has approved + * the transaction for submission to the network. + */ + approved = 'Transaction Approved', + /** + * All transactions that are submitted will finalized (eventually) by either + * being dropped, failing or being confirmed. When this happens we track this + * event, along with the status. + */ + finalized = 'Transaction Finalized', + /** + * When an unapproved transaction is in the controller state, MetaMask will + * render a confirmation screen for that transaction. If the user rejects the + * transaction we fire this event to indicate that the user has rejected the + * transaction. It will be removed from state as a result. + */ + rejected = 'Transaction Rejected', + /** + * After a transaction is approved by the user, it is then submitted to the + * network for inclusion in a block. When this happens we fire the + * Transaction Submitted event to indicate that MetaMask is submitting a + * transaction at the user's request. + */ + submitted = 'Transaction Submitted', +} + +/** + * The types of assets that a user can send + * + * @type {AssetTypes} + */ +export enum AssetType { + /** The native asset for the current network, such as ETH */ + native = 'NATIVE', + /** An ERC20 token */ + token = 'TOKEN', + /** An ERC721 or ERC1155 token. */ + NFT = 'NFT', + /** + * A transaction interacting with a contract that isn't a token method + * interaction will be marked as dealing with an unknown asset type. + */ + unknown = 'UNKNOWN', +} + +/** + * Describes the standard which a token conforms to. + */ +export enum TokenStandard { + /** A token that conforms to the ERC20 standard. */ + ERC20 = 'ERC20', + /** A token that conforms to the ERC721 standard. */ + ERC721 = 'ERC721', + /** A token that conforms to the ERC1155 standard. */ + ERC1155 = 'ERC1155', + /** Not a token, but rather the base asset of the selected chain. */ + none = 'NONE', +} diff --git a/shared/lib/transactions-controller-utils.js b/shared/lib/transactions-controller-utils.js index bc6cec5ad..02ef738f6 100644 --- a/shared/lib/transactions-controller-utils.js +++ b/shared/lib/transactions-controller-utils.js @@ -1,5 +1,5 @@ import BigNumber from 'bignumber.js'; -import { TRANSACTION_ENVELOPE_TYPES } from '../constants/transaction'; +import { TransactionEnvelopeType } from '../constants/transaction'; import { conversionUtil, multiplyCurrencies, @@ -53,7 +53,7 @@ export function getSwapsTokensReceivedFromTxMeta( ) { const txReceipt = txMeta?.txReceipt; const networkAndAccountSupports1559 = - txMeta?.txReceipt?.type === TRANSACTION_ENVELOPE_TYPES.FEE_MARKET; + txMeta?.txReceipt?.type === TransactionEnvelopeType.feeMarket; if (isSwapsDefaultTokenSymbol(tokenSymbol, chainId)) { if ( !txReceipt || diff --git a/shared/modules/transaction.utils.js b/shared/modules/transaction.utils.js index d7fd45801..9e95fb9a0 100644 --- a/shared/modules/transaction.utils.js +++ b/shared/modules/transaction.utils.js @@ -3,9 +3,9 @@ import { ethers } from 'ethers'; import { abiERC721, abiERC20, abiERC1155 } from '@metamask/metamask-eth-abis'; import log from 'loglevel'; import { - ASSET_TYPES, - TOKEN_STANDARDS, - TRANSACTION_TYPES, + AssetType, + TokenStandard, + TransactionType, } from '../constants/transaction'; import { readAddressAsContract } from './contract-utils'; import { isEqualCaseInsensitive } from './string-utils'; @@ -168,7 +168,7 @@ export async function determineTransactionType(txParams, query) { let contractCode; if (data && !to) { - result = TRANSACTION_TYPES.DEPLOY_CONTRACT; + result = TransactionType.deployContract; } else { const { contractCode: resultCode, isContractAddress } = await readAddressAsContract(query, to); @@ -177,19 +177,19 @@ export async function determineTransactionType(txParams, query) { if (isContractAddress) { const tokenMethodName = [ - TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, - TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, - TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM, + TransactionType.tokenMethodApprove, + TransactionType.tokenMethodSetApprovalForAll, + TransactionType.tokenMethodTransfer, + TransactionType.tokenMethodTransferFrom, + TransactionType.tokenMethodSafeTransferFrom, ].find((methodName) => isEqualCaseInsensitive(methodName, name)); result = data && tokenMethodName ? tokenMethodName - : TRANSACTION_TYPES.CONTRACT_INTERACTION; + : TransactionType.contractInteraction; } else { - result = TRANSACTION_TYPES.SIMPLE_SEND; + result = TransactionType.simpleSend; } } @@ -197,12 +197,12 @@ export async function determineTransactionType(txParams, query) { } const INFERRABLE_TRANSACTION_TYPES = [ - TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, - TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, - TRANSACTION_TYPES.CONTRACT_INTERACTION, - TRANSACTION_TYPES.SIMPLE_SEND, + TransactionType.tokenMethodApprove, + TransactionType.tokenMethodSetApprovalForAll, + TransactionType.tokenMethodTransfer, + TransactionType.tokenMethodTransferFrom, + TransactionType.contractInteraction, + TransactionType.simpleSend, ]; /** @@ -237,10 +237,10 @@ export async function determineTransactionAssetType( // the token contract standards, we can use the getTokenStandardAndDetails // method to get the asset type. const isTokenMethod = [ - TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, - TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, + TransactionType.tokenMethodApprove, + TransactionType.tokenMethodSetApprovalForAll, + TransactionType.tokenMethodTransfer, + TransactionType.tokenMethodTransferFrom, ].find((methodName) => methodName === inferrableType); if ( @@ -248,7 +248,7 @@ export async function determineTransactionAssetType( // We can also check any contract interaction type to see if the to address // is a token contract. If it isn't, then the method will throw and we can // fall through to the other checks. - inferrableType === TRANSACTION_TYPES.CONTRACT_INTERACTION + inferrableType === TransactionType.contractInteraction ) { try { // We don't need a balance check, so the second parameter to @@ -257,9 +257,9 @@ export async function determineTransactionAssetType( if (details.standard) { return { assetType: - details.standard === TOKEN_STANDARDS.ERC20 - ? ASSET_TYPES.TOKEN - : ASSET_TYPES.NFT, + details.standard === TokenStandard.ERC20 + ? AssetType.token + : AssetType.NFT, tokenStandard: details.standard, }; } @@ -272,11 +272,11 @@ export async function determineTransactionAssetType( // If the transaction is interacting with a contract but isn't a token method // we use the 'UNKNOWN' value to show that it isn't a transaction sending any // particular asset. - if (inferrableType === TRANSACTION_TYPES.CONTRACT_INTERACTION) { + if (inferrableType === TransactionType.contractInteraction) { return { - assetType: ASSET_TYPES.UNKNOWN, - tokenStandard: TOKEN_STANDARDS.NONE, + assetType: AssetType.unknown, + tokenStandard: TokenStandard.none, }; } - return { assetType: ASSET_TYPES.NATIVE, tokenStandard: TOKEN_STANDARDS.NONE }; + return { assetType: AssetType.native, tokenStandard: TokenStandard.none }; } diff --git a/shared/modules/transaction.utils.test.js b/shared/modules/transaction.utils.test.js index 906cdb2bb..49248c995 100644 --- a/shared/modules/transaction.utils.test.js +++ b/shared/modules/transaction.utils.test.js @@ -1,6 +1,6 @@ import EthQuery from 'ethjs-query'; import { createTestProviderTools } from '../../test/stub/provider'; -import { TRANSACTION_TYPES } from '../constants/transaction'; +import { TransactionType } from '../constants/transaction'; import { determineTransactionType, isEIP1559Transaction, @@ -16,7 +16,7 @@ describe('Transaction.utils', function () { ); expect(tokenData).toStrictEqual(expect.anything()); const { name, args } = tokenData; - expect(name).toStrictEqual(TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER); + expect(name).toStrictEqual(TransactionType.tokenMethodTransfer); const to = args._to; const value = args._value.toString(); expect(to).toStrictEqual('0x50A9D56C2B8BA9A5c7f2C08C3d26E0499F23a706'); @@ -130,7 +130,7 @@ describe('Transaction.utils', function () { new EthQuery(_provider), ); expect(result).toMatchObject({ - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, getCodeResponse: null, }); }); @@ -154,7 +154,7 @@ describe('Transaction.utils', function () { new EthQuery(_provider), ); expect(result).toMatchObject({ - type: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + type: TransactionType.tokenMethodTransfer, getCodeResponse: '0xab', }); }); @@ -178,7 +178,7 @@ describe('Transaction.utils', function () { new EthQuery(_provider), ); expect(result).toMatchObject({ - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, getCodeResponse: '0x', }); }); @@ -202,7 +202,7 @@ describe('Transaction.utils', function () { new EthQuery(_provider), ); expect(result).toMatchObject({ - type: TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, + type: TransactionType.tokenMethodApprove, getCodeResponse: '0xab', }); }); @@ -216,7 +216,7 @@ describe('Transaction.utils', function () { query, ); expect(result).toMatchObject({ - type: TRANSACTION_TYPES.DEPLOY_CONTRACT, + type: TransactionType.deployContract, getCodeResponse: undefined, }); }); @@ -230,7 +230,7 @@ describe('Transaction.utils', function () { query, ); expect(result).toMatchObject({ - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, getCodeResponse: '0x', }); }); @@ -254,7 +254,7 @@ describe('Transaction.utils', function () { new EthQuery(_provider), ); expect(result).toMatchObject({ - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, getCodeResponse: null, }); }); @@ -278,7 +278,7 @@ describe('Transaction.utils', function () { new EthQuery(_provider), ); expect(result).toMatchObject({ - type: TRANSACTION_TYPES.CONTRACT_INTERACTION, + type: TransactionType.contractInteraction, getCodeResponse: '0x0a', }); }); @@ -302,7 +302,7 @@ describe('Transaction.utils', function () { new EthQuery(_provider), ); expect(result).toMatchObject({ - type: TRANSACTION_TYPES.CONTRACT_INTERACTION, + type: TransactionType.contractInteraction, getCodeResponse: '0x0a', }); }); diff --git a/test/e2e/tests/failing-contract.spec.js b/test/e2e/tests/failing-contract.spec.js index 6b15c6a05..babd46e72 100644 --- a/test/e2e/tests/failing-contract.spec.js +++ b/test/e2e/tests/failing-contract.spec.js @@ -78,7 +78,7 @@ describe('Failing contract interaction ', function () { // display the transaction status const transactionStatus = await driver.findElement( - '.transaction-list-item:nth-of-type(1) .transaction-status', + '.transaction-list-item:nth-of-type(1) .transaction-status-label', ); assert.equal(await transactionStatus.getText(), 'Failed'); }, diff --git a/test/e2e/user-actions-benchmark.js b/test/e2e/user-actions-benchmark.js index 821e1b92a..7b72c73f5 100644 --- a/test/e2e/user-actions-benchmark.js +++ b/test/e2e/user-actions-benchmark.js @@ -83,7 +83,7 @@ async function confirmTx() { return confirmedTxes.length === 1; }, 10000); - await driver.waitForSelector('.transaction-status--confirmed'); + await driver.waitForSelector('.transaction-status-label--confirmed'); const timestampAfterAction = new Date(); loadingTimes = timestampAfterAction - timestampBeforeAction; }, diff --git a/test/lib/createTxMeta.js b/test/lib/createTxMeta.js index 035f336a6..08477dd3a 100644 --- a/test/lib/createTxMeta.js +++ b/test/lib/createTxMeta.js @@ -1,9 +1,9 @@ import { snapshotFromTxMeta } from '../../app/scripts/controllers/transactions/lib/tx-state-history-helpers'; -import { TRANSACTION_STATUSES } from '../../shared/constants/transaction'; +import { TransactionStatus } from '../../shared/constants/transaction'; export default function createTxMeta(partialMeta) { const txMeta = { - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, txParams: {}, ...partialMeta, }; diff --git a/test/stub/tx-meta-stub.js b/test/stub/tx-meta-stub.js index 8640998f4..dd03619ce 100644 --- a/test/stub/tx-meta-stub.js +++ b/test/stub/tx-meta-stub.js @@ -1,7 +1,7 @@ import { GAS_LIMITS } from '../../shared/constants/gas'; import { - TRANSACTION_STATUSES, - TRANSACTION_TYPES, + TransactionStatus, + TransactionType, } from '../../shared/constants/transaction'; export const txMetaStub = { @@ -12,9 +12,9 @@ export const txMetaStub = { id: 405984854664302, loadingDefaults: true, metamaskNetworkId: '5', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, time: 1572395156620, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, txParams: { from: '0xf231d46dd78806e1dd93442cf33c7671f8538748', gas: GAS_LIMITS.SIMPLE, @@ -47,7 +47,7 @@ export const txMetaStub = { op: 'replace', path: '/status', timestamp: 1572395158240, - value: TRANSACTION_STATUSES.APPROVED, + value: TransactionStatus.approved, }, ], [ @@ -113,7 +113,7 @@ export const txMetaStub = { op: 'replace', path: '/status', timestamp: 1572395158281, - value: TRANSACTION_STATUSES.SIGNED, + value: TransactionStatus.signed, }, { op: 'add', @@ -148,7 +148,7 @@ export const txMetaStub = { op: 'replace', path: '/status', timestamp: 1572395158576, - value: TRANSACTION_STATUSES.SUBMITTED, + value: TransactionStatus.submitted, }, ], [ @@ -192,10 +192,10 @@ export const txMetaStub = { rawTx: '0xf86204831e848082520894f231d46dd78806e1dd93442cf33c7671f853874880802ca05f973e540f2d3c2f06d3725a626b75247593cb36477187ae07ecfe0a4db3cf57a00259b52ee8c58baaa385fb05c3f96116e58de89bcc165cb3bfdfc708672fed8a', s: '0x0259b52ee8c58baaa385fb05c3f96116e58de89bcc165cb3bfdfc708672fed8a', - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, submittedTime: 1572395158570, time: 1572395156620, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, txParams: { from: '0xf231d46dd78806e1dd93442cf33c7671f8538748', gas: GAS_LIMITS.SIMPLE, diff --git a/ui/components/app/app-components.scss b/ui/components/app/app-components.scss index 7ab1d92de..b59623b29 100644 --- a/ui/components/app/app-components.scss +++ b/ui/components/app/app-components.scss @@ -81,7 +81,7 @@ @import 'transaction-list-item-details/index'; @import 'transaction-list-item/index'; @import 'transaction-list/index'; -@import 'transaction-status/index'; +@import 'transaction-status-label/index'; @import 'wallet-overview/index'; @import 'whats-new-popup/index'; @import 'loading-network-screen/index'; diff --git a/ui/components/app/asset-list-item/asset-list-item.js b/ui/components/app/asset-list-item/asset-list-item.js index f05992bb4..deef3bfe5 100644 --- a/ui/components/app/asset-list-item/asset-list-item.js +++ b/ui/components/app/asset-list-item/asset-list-item.js @@ -14,7 +14,7 @@ import { SEND_ROUTE } from '../../../helpers/constants/routes'; import { SEVERITIES } from '../../../helpers/constants/design-system'; import { INVALID_ASSET_TYPE } from '../../../helpers/constants/error-keys'; import { EVENT } from '../../../../shared/constants/metametrics'; -import { ASSET_TYPES } from '../../../../shared/constants/transaction'; +import { AssetType } from '../../../../shared/constants/transaction'; import { MetaMetricsContext } from '../../../contexts/metametrics'; const AssetListItem = ({ @@ -75,7 +75,7 @@ const AssetListItem = ({ try { await dispatch( startNewDraftTransaction({ - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: { address: tokenAddress, decimals: tokenDecimals, diff --git a/ui/components/app/collectible-details/collectible-details.js b/ui/components/app/collectible-details/collectible-details.js index efb5e1824..546986da7 100644 --- a/ui/components/app/collectible-details/collectible-details.js +++ b/ui/components/app/collectible-details/collectible-details.js @@ -43,7 +43,10 @@ import InfoTooltip from '../../ui/info-tooltip'; import { usePrevious } from '../../../hooks/usePrevious'; import { useCopyToClipboard } from '../../../hooks/useCopyToClipboard'; import { isEqualCaseInsensitive } from '../../../../shared/modules/string-utils'; -import { ASSET_TYPES, ERC721 } from '../../../../shared/constants/transaction'; +import { + AssetType, + TokenStandard, +} from '../../../../shared/constants/transaction'; import CollectibleDefaultImage from '../collectible-default-image'; export default function CollectibleDetails({ collectible }) { @@ -105,13 +108,13 @@ export default function CollectibleDetails({ collectible }) { }; const openSeaLink = getOpenSeaLink(); - const sendDisabled = standard !== ERC721; + const sendDisabled = standard !== TokenStandard.ERC721; const inPopUp = getEnvironmentType() === ENVIRONMENT_TYPE_POPUP; const onSend = async () => { await dispatch( startNewDraftTransaction({ - type: ASSET_TYPES.NFT, + type: AssetType.NFT, details: collectible, }), ); diff --git a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.test.js b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.test.js index 37766b739..ed13a3987 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.test.js +++ b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-content.component.test.js @@ -1,7 +1,7 @@ import { fireEvent } from '@testing-library/react'; import React from 'react'; import configureMockStore from 'redux-mock-store'; -import { TRANSACTION_TYPES } from '../../../../../shared/constants/transaction'; +import { TransactionType } from '../../../../../shared/constants/transaction'; import { renderWithProvider } from '../../../../../test/lib/render-helpers'; import { TRANSACTION_ERROR_KEY } from '../../../../helpers/constants/error-keys'; import ConfirmPageContainerContent from './confirm-page-container-content.component'; @@ -106,7 +106,7 @@ describe('Confirm Page Container Content', () => { it('render contract address name from addressBook in title for contract', async () => { props.disabled = false; props.toAddress = '0x06195827297c7A80a443b6894d3BDB8824b43896'; - props.transactionType = TRANSACTION_TYPES.CONTRACT_INTERACTION; + props.transactionType = TransactionType.contractInteraction; const { queryByText } = renderWithProvider( , store, @@ -118,7 +118,7 @@ describe('Confirm Page Container Content', () => { it('render simple title without address name for simple send', async () => { props.disabled = false; props.toAddress = '0x06195827297c7A80a443b6894d3BDB8824b43896'; - props.transactionType = TRANSACTION_TYPES.SIMPLE_SEND; + props.transactionType = TransactionType.simpleSend; const { queryByText } = renderWithProvider( , store, diff --git a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js index 442329497..ace2c3ff7 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js +++ b/ui/components/app/confirm-page-container/confirm-page-container-content/confirm-page-container-summary/confirm-page-container-summary.component.js @@ -3,7 +3,7 @@ import React, { useState } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; -import { TRANSACTION_TYPES } from '../../../../../../shared/constants/transaction'; +import { TransactionType } from '../../../../../../shared/constants/transaction'; import { toChecksumHexAddress } from '../../../../../../shared/modules/hexstring-utils'; import { useI18nContext } from '../../../../../hooks/useI18nContext'; import useAddressDetails from '../../../../../hooks/useAddressDetails'; @@ -37,10 +37,10 @@ const ConfirmPageContainerSummary = (props) => { const t = useI18nContext(); const contractInitiatedTransactionType = [ - TRANSACTION_TYPES.CONTRACT_INTERACTION, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, - TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM, + TransactionType.contractInteraction, + TransactionType.tokenMethodTransfer, + TransactionType.tokenMethodTransferFrom, + TransactionType.tokenMethodSafeTransferFrom, ]; const isContractTypeTransaction = contractInitiatedTransactionType.includes(transactionType); @@ -50,10 +50,10 @@ const ConfirmPageContainerSummary = (props) => { // the contract address is passed down as tokenAddress, if it is anyother // type of contract interaction it is passed as toAddress contractAddress = - transactionType === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER || - transactionType === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM || - transactionType === TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM || - transactionType === TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL + transactionType === TransactionType.tokenMethodTransfer || + transactionType === TransactionType.tokenMethodTransferFrom || + transactionType === TransactionType.tokenMethodSafeTransferFrom || + transactionType === TransactionType.tokenMethodSetApprovalForAll ? tokenAddress : toAddress; } diff --git a/ui/components/app/confirm-page-container/confirm-page-container.component.js b/ui/components/app/confirm-page-container/confirm-page-container.component.js index 369028fa0..379518f5e 100644 --- a/ui/components/app/confirm-page-container/confirm-page-container.component.js +++ b/ui/components/app/confirm-page-container/confirm-page-container.component.js @@ -4,10 +4,8 @@ import PropTypes from 'prop-types'; import { EDIT_GAS_MODES } from '../../../../shared/constants/gas'; import { GasFeeContextProvider } from '../../../contexts/gasFee'; import { - ERC1155, - ERC20, - ERC721, - TRANSACTION_TYPES, + TokenStandard, + TransactionType, } from '../../../../shared/constants/transaction'; import { NETWORK_TO_NAME_MAP } from '../../../../shared/constants/network'; @@ -105,10 +103,9 @@ export default class ConfirmPageContainer extends Component { const { tokenAddress, fromAddress, currentTransaction, assetStandard } = this.props; const isSetApproveForAll = - currentTransaction.type === - TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL; + currentTransaction.type === TransactionType.tokenMethodSetApprovalForAll; - if (isSetApproveForAll && assetStandard === ERC721) { + if (isSetApproveForAll && assetStandard === TokenStandard.ERC721) { const tokenBalance = await fetchTokenBalance(tokenAddress, fromAddress); this.setState({ collectionBalance: tokenBalance?.balance?.words?.[0] || 0, @@ -173,16 +170,15 @@ export default class ConfirmPageContainer extends Component { contentComponent && disabled && (errorKey || errorMessage); const hideTitle = - (currentTransaction.type === TRANSACTION_TYPES.CONTRACT_INTERACTION || - currentTransaction.type === TRANSACTION_TYPES.DEPLOY_CONTRACT) && + (currentTransaction.type === TransactionType.contractInteraction || + currentTransaction.type === TransactionType.deployContract) && currentTransaction.txParams?.value === '0x0'; const networkName = NETWORK_TO_NAME_MAP[currentTransaction.chainId] || networkIdentifier; const isSetApproveForAll = - currentTransaction.type === - TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL; + currentTransaction.type === TransactionType.tokenMethodSetApprovalForAll; const { setShowDepositPopover } = this.state; @@ -192,9 +188,9 @@ export default class ConfirmPageContainer extends Component {
- {assetStandard === ERC20 || - assetStandard === ERC721 || - assetStandard === ERC1155 ? ( + {assetStandard === TokenStandard.ERC20 || + assetStandard === TokenStandard.ERC721 || + assetStandard === TokenStandard.ERC1155 ? ( { token_contract_address: importedToken.address, token_decimal_precision: importedToken.decimals, source: EVENT.SOURCE.TOKEN.DETECTED, - token_standard: TOKEN_STANDARDS.ERC20, - asset_type: ASSET_TYPES.TOKEN, + token_standard: TokenStandard.ERC20, + asset_type: AssetType.token, }, }); }); @@ -91,8 +91,8 @@ const DetectedToken = ({ setShowDetectedTokens }) => { sensitiveProperties: { tokens: tokensDetailsList, location: EVENT.LOCATION.TOKEN_DETECTION, - token_standard: TOKEN_STANDARDS.ERC20, - asset_type: ASSET_TYPES.TOKEN, + token_standard: TokenStandard.ERC20, + asset_type: AssetType.token, }, }); const deSelectedTokensAddresses = deSelectedTokens.map( diff --git a/ui/components/app/edit-gas-fee-button/edit-gas-fee-button.test.js b/ui/components/app/edit-gas-fee-button/edit-gas-fee-button.test.js index e49cc8a1b..5ee263d5e 100644 --- a/ui/components/app/edit-gas-fee-button/edit-gas-fee-button.test.js +++ b/ui/components/app/edit-gas-fee-button/edit-gas-fee-button.test.js @@ -6,7 +6,7 @@ import { GAS_ESTIMATE_TYPES, PRIORITY_LEVELS, } from '../../../../shared/constants/gas'; -import { TRANSACTION_ENVELOPE_TYPES } from '../../../../shared/constants/transaction'; +import { TransactionEnvelopeType } from '../../../../shared/constants/transaction'; import { GasFeeContextProvider } from '../../../contexts/gasFee'; import { renderWithProvider } from '../../../../test/jest'; @@ -144,7 +144,7 @@ describe('EditGasFeeButton', () => { contextProps: { transaction: { userFeeLevel: 'low', - txParams: { type: TRANSACTION_ENVELOPE_TYPES.LEGACY }, + txParams: { type: TransactionEnvelopeType.legacy }, }, }, }); diff --git a/ui/components/app/modals/cancel-transaction/cancel-transaction.component.js b/ui/components/app/modals/cancel-transaction/cancel-transaction.component.js index f98ce7c7b..13c2b943b 100644 --- a/ui/components/app/modals/cancel-transaction/cancel-transaction.component.js +++ b/ui/components/app/modals/cancel-transaction/cancel-transaction.component.js @@ -1,7 +1,7 @@ import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Modal from '../../modal'; -import { TRANSACTION_STATUSES } from '../../../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../../../shared/constants/transaction'; import CancelTransactionGasFee from './cancel-transaction-gas-fee'; export default class CancelTransaction extends PureComponent { @@ -24,7 +24,7 @@ export default class CancelTransaction extends PureComponent { componentDidUpdate() { const { transactionStatus, showTransactionConfirmedModal } = this.props; - if (transactionStatus !== TRANSACTION_STATUSES.SUBMITTED) { + if (transactionStatus !== TransactionStatus.submitted) { showTransactionConfirmedModal(); } } diff --git a/ui/components/app/modals/contract-details-modal/contract-details-modal.js b/ui/components/app/modals/contract-details-modal/contract-details-modal.js index c339f1313..a5e8720f2 100644 --- a/ui/components/app/modals/contract-details-modal/contract-details-modal.js +++ b/ui/components/app/modals/contract-details-modal/contract-details-modal.js @@ -25,7 +25,7 @@ import { import { useCopyToClipboard } from '../../../../hooks/useCopyToClipboard'; import UrlIcon from '../../../ui/url-icon/url-icon'; import { getAddressBookEntry } from '../../../../selectors'; -import { ERC1155, ERC721 } from '../../../../../shared/constants/transaction'; +import { TokenStandard } from '../../../../../shared/constants/transaction'; import NftCollectionImage from '../../../ui/nft-collection-image/nft-collection-image'; export default function ContractDetailsModal({ @@ -50,8 +50,8 @@ export default function ContractDetailsModal({ data: getAddressBookEntry(state, toAddress), })); const nft = - assetStandard === ERC721 || - assetStandard === ERC1155 || + assetStandard === TokenStandard.ERC721 || + assetStandard === TokenStandard.ERC1155 || // if we don't have an asset standard but we do have either both an assetname and a tokenID or both a tokenName and tokenId we assume its an NFT (assetName && tokenId) || (tokenName && tokenId); diff --git a/ui/components/app/transaction-activity-log/transaction-activity-log.util.js b/ui/components/app/transaction-activity-log/transaction-activity-log.util.js index f9aec2343..e722cf45a 100644 --- a/ui/components/app/transaction-activity-log/transaction-activity-log.util.js +++ b/ui/components/app/transaction-activity-log/transaction-activity-log.util.js @@ -1,4 +1,4 @@ -import { TRANSACTION_TYPES } from '../../../../shared/constants/transaction'; +import { TransactionType } from '../../../../shared/constants/transaction'; import { getHexGasTotal } from '../../../helpers/utils/confirm-tx.util'; import { sumHexes } from '../../../helpers/utils/transactions.util'; @@ -136,13 +136,13 @@ export function getActivities(transaction, isFirstTransaction = false) { // If the status is 'submitted', we need to determine whether the event is a // transaction retry or a cancellation attempt. if (value === SUBMITTED_STATUS) { - if (type === TRANSACTION_TYPES.RETRY) { + if (type === TransactionType.retry) { eventKey = TRANSACTION_RESUBMITTED_EVENT; - } else if (type === TRANSACTION_TYPES.CANCEL) { + } else if (type === TransactionType.cancel) { eventKey = TRANSACTION_CANCEL_ATTEMPTED_EVENT; } } else if (value === CONFIRMED_STATUS) { - if (type === TRANSACTION_TYPES.CANCEL) { + if (type === TransactionType.cancel) { eventKey = TRANSACTION_CANCEL_SUCCESS_EVENT; } } diff --git a/ui/components/app/transaction-activity-log/transaction-activity-log.util.test.js b/ui/components/app/transaction-activity-log/transaction-activity-log.util.test.js index f076b4038..ef12dc8d7 100644 --- a/ui/components/app/transaction-activity-log/transaction-activity-log.util.test.js +++ b/ui/components/app/transaction-activity-log/transaction-activity-log.util.test.js @@ -1,7 +1,7 @@ import { GAS_LIMITS } from '../../../../shared/constants/gas'; import { - TRANSACTION_STATUSES, - TRANSACTION_TYPES, + TransactionStatus, + TransactionType, } from '../../../../shared/constants/transaction'; import { combineTransactionHistories, @@ -22,7 +22,7 @@ describe('TransactionActivityLog utils', () => { { id: 6400627574331058, time: 1543958845581, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: '5', chainId: '0x5', loadingDefaults: true, @@ -33,13 +33,13 @@ describe('TransactionActivityLog utils', () => { gas: GAS_LIMITS.SIMPLE, gasPrice: '0x3b9aca00', }, - type: TRANSACTION_TYPES.STANDARD, + type: TransactionType.simpleSend, }, [ { op: 'replace', path: '/status', - value: TRANSACTION_STATUSES.APPROVED, + value: TransactionStatus.approved, note: 'txStateManager: setting status to approved', timestamp: 1543958847813, }, @@ -48,7 +48,7 @@ describe('TransactionActivityLog utils', () => { { op: 'replace', path: '/status', - value: TRANSACTION_STATUSES.SUBMITTED, + value: TransactionStatus.submitted, note: 'txStateManager: setting status to submitted', timestamp: 1543958848147, }, @@ -57,7 +57,7 @@ describe('TransactionActivityLog utils', () => { { op: 'replace', path: '/status', - value: TRANSACTION_STATUSES.DROPPED, + value: TransactionStatus.dropped, note: 'txStateManager: setting status to dropped', timestamp: 1543958897181, }, @@ -73,7 +73,7 @@ describe('TransactionActivityLog utils', () => { loadingDefaults: false, metamaskNetworkId: '5', chainId: '0x5', - status: TRANSACTION_STATUSES.DROPPED, + status: TransactionStatus.dropped, submittedTime: 1543958848135, time: 1543958845581, txParams: { @@ -84,7 +84,7 @@ describe('TransactionActivityLog utils', () => { to: '0xc5ae6383e126f901dcb06131d97a88745bfa88d6', value: '0x2386f26fc10000', }, - type: TRANSACTION_TYPES.STANDARD, + type: TransactionType.simpleSend, }, { hash: '0xecbe181ee67c4291d04a7cb9ffbf1d5d831e4fbaa89994fd06bab5dd4cc79b33', @@ -92,7 +92,7 @@ describe('TransactionActivityLog utils', () => { { id: 6400627574331060, time: 1543958857697, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: '5', chainId: '0x5', loadingDefaults: false, @@ -105,7 +105,7 @@ describe('TransactionActivityLog utils', () => { nonce: '0x32', }, lastGasPrice: '0x4190ab00', - type: TRANSACTION_TYPES.RETRY, + type: TransactionType.retry, }, [ { @@ -120,7 +120,7 @@ describe('TransactionActivityLog utils', () => { { op: 'replace', path: '/status', - value: TRANSACTION_STATUSES.APPROVED, + value: TransactionStatus.approved, note: 'txStateManager: setting status to approved', timestamp: 1543958859485, }, @@ -129,7 +129,7 @@ describe('TransactionActivityLog utils', () => { { op: 'replace', path: '/status', - value: TRANSACTION_STATUSES.SIGNED, + value: TransactionStatus.signed, note: 'transactions#publishTransaction', timestamp: 1543958859889, }, @@ -138,7 +138,7 @@ describe('TransactionActivityLog utils', () => { { op: 'replace', path: '/status', - value: TRANSACTION_STATUSES.SUBMITTED, + value: TransactionStatus.submitted, note: 'txStateManager: setting status to submitted', timestamp: 1543958860061, }, @@ -156,7 +156,7 @@ describe('TransactionActivityLog utils', () => { { op: 'replace', path: '/status', - value: TRANSACTION_STATUSES.CONFIRMED, + value: TransactionStatus.confirmed, timestamp: 1543958897165, }, ], @@ -166,7 +166,7 @@ describe('TransactionActivityLog utils', () => { loadingDefaults: false, metamaskNetworkId: '5', chainId: '0x5', - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, submittedTime: 1543958860054, time: 1543958857697, txParams: { @@ -180,7 +180,7 @@ describe('TransactionActivityLog utils', () => { txReceipt: { status: '0x1', }, - type: TRANSACTION_TYPES.RETRY, + type: TransactionType.retry, }, ]; @@ -232,7 +232,7 @@ describe('TransactionActivityLog utils', () => { const transaction = { history: [], id: 1, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: '0x1', gas: GAS_LIMITS.SIMPLE, @@ -254,7 +254,7 @@ describe('TransactionActivityLog utils', () => { loadingDefaults: true, metamaskNetworkId: '5', chainId: '0x5', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, time: 1535507561452, txParams: { from: '0x1', @@ -298,7 +298,7 @@ describe('TransactionActivityLog utils', () => { op: 'replace', path: '/status', timestamp: 1535507564302, - value: TRANSACTION_STATUSES.APPROVED, + value: TransactionStatus.approved, }, ], [ @@ -325,7 +325,7 @@ describe('TransactionActivityLog utils', () => { op: 'replace', path: '/status', timestamp: 1535507564518, - value: TRANSACTION_STATUSES.SIGNED, + value: TransactionStatus.signed, }, { op: 'add', @@ -360,7 +360,7 @@ describe('TransactionActivityLog utils', () => { op: 'replace', path: '/status', timestamp: 1535507564665, - value: TRANSACTION_STATUSES.SUBMITTED, + value: TransactionStatus.submitted, }, ], [ @@ -378,12 +378,12 @@ describe('TransactionActivityLog utils', () => { op: 'replace', path: '/status', timestamp: 1535507615993, - value: TRANSACTION_STATUSES.CONFIRMED, + value: TransactionStatus.confirmed, }, ], ], id: 1, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: '0x1', gas: GAS_LIMITS.SIMPLE, diff --git a/ui/components/app/transaction-detail/transaction-detail.component.test.js b/ui/components/app/transaction-detail/transaction-detail.component.test.js index 9a274e516..519dff09c 100644 --- a/ui/components/app/transaction-detail/transaction-detail.component.test.js +++ b/ui/components/app/transaction-detail/transaction-detail.component.test.js @@ -2,7 +2,7 @@ import React from 'react'; import { screen } from '@testing-library/react'; import { GAS_ESTIMATE_TYPES } from '../../../../shared/constants/gas'; -import { TRANSACTION_ENVELOPE_TYPES } from '../../../../shared/constants/transaction'; +import { TransactionEnvelopeType } from '../../../../shared/constants/transaction'; import { GasFeeContextProvider } from '../../../contexts/gasFee'; import { renderWithProvider } from '../../../../test/jest'; @@ -62,7 +62,7 @@ describe('TransactionDetail', () => { contextProps: { transaction: { userFeeLevel: 'low', - txParams: { type: TRANSACTION_ENVELOPE_TYPES.LEGACY }, + txParams: { type: TransactionEnvelopeType.legacy }, }, }, }); diff --git a/ui/components/app/transaction-icon/transaction-icon.js b/ui/components/app/transaction-icon/transaction-icon.js index e87b8520a..bb42a71b9 100644 --- a/ui/components/app/transaction-icon/transaction-icon.js +++ b/ui/components/app/transaction-icon/transaction-icon.js @@ -8,19 +8,19 @@ import Send from '../../ui/icon/send-icon.component'; import Sign from '../../ui/icon/sign-icon.component'; import Swap from '../../ui/icon/swap-icon-for-list.component'; import { - TRANSACTION_GROUP_CATEGORIES, - TRANSACTION_GROUP_STATUSES, - TRANSACTION_STATUSES, + TransactionGroupCategory, + TransactionGroupStatus, + TransactionStatus, } from '../../../../shared/constants/transaction'; import { captureSingleException } from '../../../store/actions'; const ICON_MAP = { - [TRANSACTION_GROUP_CATEGORIES.APPROVAL]: Approve, - [TRANSACTION_GROUP_CATEGORIES.INTERACTION]: Interaction, - [TRANSACTION_GROUP_CATEGORIES.RECEIVE]: Receive, - [TRANSACTION_GROUP_CATEGORIES.SEND]: Send, - [TRANSACTION_GROUP_CATEGORIES.SIGNATURE_REQUEST]: Sign, - [TRANSACTION_GROUP_CATEGORIES.SWAP]: Swap, + [TransactionGroupCategory.approval]: Approve, + [TransactionGroupCategory.interaction]: Interaction, + [TransactionGroupCategory.receive]: Receive, + [TransactionGroupCategory.send]: Send, + [TransactionGroupCategory.signatureRequest]: Sign, + [TransactionGroupCategory.swap]: Swap, }; const FAIL_COLOR = 'var(--color-error-default)'; @@ -28,14 +28,14 @@ const PENDING_COLOR = 'var(--color-icon-default)'; const OK_COLOR = 'var(--color-primary-default)'; const COLOR_MAP = { - [TRANSACTION_GROUP_STATUSES.PENDING]: PENDING_COLOR, - [TRANSACTION_GROUP_STATUSES.CANCELLED]: FAIL_COLOR, - [TRANSACTION_STATUSES.APPROVED]: PENDING_COLOR, - [TRANSACTION_STATUSES.DROPPED]: FAIL_COLOR, - [TRANSACTION_STATUSES.FAILED]: FAIL_COLOR, - [TRANSACTION_STATUSES.REJECTED]: FAIL_COLOR, - [TRANSACTION_STATUSES.SUBMITTED]: PENDING_COLOR, - [TRANSACTION_STATUSES.UNAPPROVED]: PENDING_COLOR, + [TransactionGroupStatus.pending]: PENDING_COLOR, + [TransactionGroupStatus.cancelled]: FAIL_COLOR, + [TransactionStatus.approved]: PENDING_COLOR, + [TransactionStatus.dropped]: FAIL_COLOR, + [TransactionStatus.failed]: FAIL_COLOR, + [TransactionStatus.rejected]: FAIL_COLOR, + [TransactionStatus.submitted]: PENDING_COLOR, + [TransactionStatus.unapproved]: PENDING_COLOR, }; export default function TransactionIcon({ status, category }) { @@ -58,22 +58,22 @@ export default function TransactionIcon({ status, category }) { TransactionIcon.propTypes = { status: PropTypes.oneOf([ - TRANSACTION_GROUP_STATUSES.CANCELLED, - TRANSACTION_GROUP_STATUSES.PENDING, - TRANSACTION_STATUSES.APPROVED, - TRANSACTION_STATUSES.CONFIRMED, - TRANSACTION_STATUSES.DROPPED, - TRANSACTION_STATUSES.FAILED, - TRANSACTION_STATUSES.REJECTED, - TRANSACTION_STATUSES.SUBMITTED, - TRANSACTION_STATUSES.UNAPPROVED, + TransactionGroupStatus.cancelled, + TransactionGroupStatus.pending, + TransactionStatus.approved, + TransactionStatus.confirmed, + TransactionStatus.dropped, + TransactionStatus.failed, + TransactionStatus.rejected, + TransactionStatus.submitted, + TransactionStatus.unapproved, ]).isRequired, category: PropTypes.oneOf([ - TRANSACTION_GROUP_CATEGORIES.APPROVAL, - TRANSACTION_GROUP_CATEGORIES.INTERACTION, - TRANSACTION_GROUP_CATEGORIES.RECEIVE, - TRANSACTION_GROUP_CATEGORIES.SEND, - TRANSACTION_GROUP_CATEGORIES.SIGNATURE_REQUEST, - TRANSACTION_GROUP_CATEGORIES.SWAP, + TransactionGroupCategory.approval, + TransactionGroupCategory.interaction, + TransactionGroupCategory.receive, + TransactionGroupCategory.send, + TransactionGroupCategory.signatureRequest, + TransactionGroupCategory.swap, ]).isRequired, }; diff --git a/ui/components/app/transaction-list-item-details/transaction-list-item-details.component.js b/ui/components/app/transaction-list-item-details/transaction-list-item-details.component.js index b48a50558..7e96ace0e 100644 --- a/ui/components/app/transaction-list-item-details/transaction-list-item-details.component.js +++ b/ui/components/app/transaction-list-item-details/transaction-list-item-details.component.js @@ -13,7 +13,7 @@ import CancelButton from '../cancel-button'; import Popover from '../../ui/popover'; import { SECOND } from '../../../../shared/constants/time'; import { EVENT } from '../../../../shared/constants/metametrics'; -import { TRANSACTION_TYPES } from '../../../../shared/constants/transaction'; +import { TransactionType } from '../../../../shared/constants/transaction'; import { getURLHostName } from '../../../helpers/utils/util'; import TransactionDecoding from '../transaction-decoding'; import { NETWORKS_ROUTE } from '../../../helpers/constants/routes'; @@ -274,15 +274,15 @@ export default class TransactionListItemDetails extends PureComponent { {transactionGroup.initialTransaction.type !== - TRANSACTION_TYPES.INCOMING && ( + TransactionType.incoming && ( { const transaction = { history: [], id: 1, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txParams: { from: '0x1', gas: GAS_LIMITS.SIMPLE, diff --git a/ui/components/app/transaction-list-item/index.scss b/ui/components/app/transaction-list-item/index.scss index f523714bd..1191f79c8 100644 --- a/ui/components/app/transaction-list-item/index.scss +++ b/ui/components/app/transaction-list-item/index.scss @@ -48,7 +48,7 @@ text-overflow: initial; } - .transaction-status::after { + .transaction-status-label::after { content: "·"; margin: 0 4px; } diff --git a/ui/components/app/transaction-list-item/smart-transaction-list-item.component.js b/ui/components/app/transaction-list-item/smart-transaction-list-item.component.js index 2e2f2ccb1..7c71e3a44 100644 --- a/ui/components/app/transaction-list-item/smart-transaction-list-item.component.js +++ b/ui/components/app/transaction-list-item/smart-transaction-list-item.component.js @@ -2,15 +2,15 @@ import React, { useState, useCallback } from 'react'; import PropTypes from 'prop-types'; import { useDispatch } from 'react-redux'; import ListItem from '../../ui/list-item'; -import TransactionStatus from '../transaction-status/transaction-status.component'; +import TransactionStatusLabel from '../transaction-status-label/transaction-status-label'; import TransactionIcon from '../transaction-icon'; import { useI18nContext } from '../../../hooks/useI18nContext'; import { useTransactionDisplayData } from '../../../hooks/useTransactionDisplayData'; import { formatDateWithYearContext } from '../../../helpers/utils/util'; import { - TRANSACTION_GROUP_CATEGORIES, - TRANSACTION_GROUP_STATUSES, - SMART_TRANSACTION_STATUSES, + TransactionGroupCategory, + TransactionGroupStatus, + SmartTransactionStatus, } from '../../../../shared/constants/transaction'; import CancelButton from '../cancel-button'; @@ -31,7 +31,7 @@ export default function SmartTransactionListItem({ useTransactionDisplayData(transactionGroup); const { sourceTokenSymbol, destinationTokenSymbol, time, status } = smartTransaction; - const category = TRANSACTION_GROUP_CATEGORIES.SWAP; + const category = TransactionGroupCategory.swap; const title = t('swapTokenToToken', [ sourceTokenSymbol, destinationTokenSymbol, @@ -39,10 +39,10 @@ export default function SmartTransactionListItem({ const subtitle = 'metamask'; const date = formatDateWithYearContext(time); let displayedStatusKey; - if (status === SMART_TRANSACTION_STATUSES.PENDING) { - displayedStatusKey = TRANSACTION_GROUP_STATUSES.PENDING; - } else if (status?.startsWith(SMART_TRANSACTION_STATUSES.CANCELLED)) { - displayedStatusKey = TRANSACTION_GROUP_STATUSES.CANCELLED; + if (status === SmartTransactionStatus.pending) { + displayedStatusKey = TransactionGroupStatus.pending; + } else if (status?.startsWith(SmartTransactionStatus.cancelled)) { + displayedStatusKey = TransactionGroupStatus.cancelled; } const showCancelSwapLink = smartTransaction.cancellable && !cancelSwapLinkClicked; @@ -61,7 +61,7 @@ export default function SmartTransactionListItem({ } subtitle={

- } > - {displayedStatusKey === TRANSACTION_GROUP_STATUSES.PENDING && + {displayedStatusKey === TransactionGroupStatus.pending && showCancelSwapLink && (
( - - ( - { /** * Transaction List Item Storybook Page * - * Each page displays a different Transaction Type (TRANSACTION_TYPES) - * except TRANSACTION_TYPES.CANCEL and TRANSACTION_TYPES.RETRY as these two types + * Each page displays a different Transaction Type (TransactionType) + * except TransactionType.cancel and TransactionType.retry as these two types * are never initialTransactions */ export default { @@ -47,9 +47,9 @@ export default { 'transactionGroup.hasCancelled': { control: 'boolean' }, 'transactionGroup.hasRetried': { control: 'boolean' }, 'transactionGroup.primaryTransaction.status': { - options: Object.values(TRANSACTION_STATUSES) + options: Object.values(TransactionStatus) .filter((status) => { - return status !== TRANSACTION_STATUSES.SIGNED; + return status !== TransactionStatus.signed; }) .sort(), control: { type: 'select' }, @@ -61,7 +61,7 @@ export default { isEarliestNonce: true, 'transactionGroup.hasCancelled': false, 'transactionGroup.hasRetried': false, - 'transactionGroup.primaryTransaction.status': TRANSACTION_STATUSES.PENDING, + 'transactionGroup.primaryTransaction.status': TransactionStatus.pending, 'transactionGroup.primaryTransaction.submittedTime': 19999999999999, }, }; @@ -96,115 +96,111 @@ export const TokenMethodTransferFrom = Template.bind({}); ContractInteraction.storyName = 'contractInteraction'; ContractInteraction.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.CONTRACT_INTERACTION], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.contractInteraction], }, }; DeployContract.storyName = 'contractDeployment'; DeployContract.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.DEPLOY_CONTRACT], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.deployContract], }, }; EthDecrypt.storyName = 'eth_decrypt'; EthDecrypt.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.ETH_DECRYPT], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.ethDecrypt], }, }; EthGetEncryptionPublicKey.storyName = 'eth_getEncryptionPublicKey'; EthGetEncryptionPublicKey.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[ - TRANSACTION_TYPES.ETH_GET_ENCRYPTION_PUBLIC_KEY - ], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.ethGetEncryptionPublicKey], }, }; Incoming.storyName = 'incoming'; Incoming.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.INCOMING], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.incoming], }, }; PersonalSign.storyName = 'personal_sign'; PersonalSign.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.PERSONAL_SIGN], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.personalSign], }, }; Sign.storyName = 'eth_sign'; Sign.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.SIGN], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.sign], }, }; SignTypeData.storyName = 'eth_signTypedData'; SignTypeData.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.SIGN_TYPED_DATA], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.signTypedData], }, }; SimpleSend.storyName = 'simpleSend'; SimpleSend.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.SIMPLE_SEND], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.simpleSend], }, }; Smart.storyName = 'smart'; Smart.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.SMART], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.smart], }, }; Swap.storyName = 'swap'; Swap.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.SWAP], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.swap], }, }; SwapApproval.storyName = 'swapApproval'; SwapApproval.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.SWAP_APPROVAL], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.swapApproval], }, }; TokenMethodApprove.storyName = 'approve'; TokenMethodApprove.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.TOKEN_METHOD_APPROVE], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.tokenMethodApprove], }, }; TokenMethodSafeTransferFrom.storyName = 'safetransferfrom'; TokenMethodSafeTransferFrom.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[ - TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM - ], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.tokenMethodSafeTransferFrom], }, }; TokenMethodTransfer.storyName = 'transfer'; TokenMethodTransfer.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.tokenMethodTransfer], }, }; TokenMethodTransferFrom.storyName = 'transferfrom'; TokenMethodTransferFrom.args = { 'transactionGroup.primaryTransaction': { - ...MOCK_TRANSACTION_BY_TYPE[TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM], + ...MOCK_TRANSACTION_BY_TYPE[TransactionType.tokenMethodTransferFrom], }, }; diff --git a/ui/components/app/transaction-list/transaction-list.component.js b/ui/components/app/transaction-list/transaction-list.component.js index 884e254ff..a86df8c5f 100644 --- a/ui/components/app/transaction-list/transaction-list.component.js +++ b/ui/components/app/transaction-list/transaction-list.component.js @@ -12,7 +12,7 @@ import SmartTransactionListItem from '../transaction-list-item/smart-transaction import Button from '../../ui/button'; import { TOKEN_CATEGORY_HASH } from '../../../helpers/constants/transactions'; import { SWAPS_CHAINID_CONTRACT_ADDRESS_MAP } from '../../../../shared/constants/swaps'; -import { TRANSACTION_TYPES } from '../../../../shared/constants/transaction'; +import { TransactionType } from '../../../../shared/constants/transaction'; import { isEqualCaseInsensitive } from '../../../../shared/modules/string-utils'; const PAGE_INCREMENT = 10; @@ -42,7 +42,7 @@ const tokenTransactionFilter = ({ }) => { if (TOKEN_CATEGORY_HASH[type]) { return false; - } else if (type === TRANSACTION_TYPES.SWAP) { + } else if (type === TransactionType.swap) { return destinationTokenSymbol === 'ETH' || sourceTokenSymbol === 'ETH'; } return true; @@ -125,7 +125,7 @@ export default function TransactionList({
{pendingTransactions.map((transactionGroup, index) => transactionGroup.initialTransaction.transactionType === - TRANSACTION_TYPES.SMART ? ( + TransactionType.smart ? ( +
+ June 1 +
+

+`; + +exports[`TransactionStatusLabel Component should render PENDING properly 1`] = ` +
+
+ [pending] +
+
+`; + +exports[`TransactionStatusLabel Component should render PENDING properly when status is APPROVED 1`] = ` +
+
+
+ [pending] +
+
+
+`; + +exports[`TransactionStatusLabel Component should render QUEUED properly 1`] = ` +
+
+ [queued] +
+
+`; + +exports[`TransactionStatusLabel Component should render UNAPPROVED properly 1`] = ` +
+
+ [unapproved] +
+
+`; diff --git a/ui/components/app/transaction-status-label/index.js b/ui/components/app/transaction-status-label/index.js new file mode 100644 index 000000000..4b7cf12c4 --- /dev/null +++ b/ui/components/app/transaction-status-label/index.js @@ -0,0 +1 @@ +export { default } from './transaction-status-label'; diff --git a/ui/components/app/transaction-status/index.scss b/ui/components/app/transaction-status-label/index.scss similarity index 92% rename from ui/components/app/transaction-status/index.scss rename to ui/components/app/transaction-status-label/index.scss index 6212c0849..79e14bc20 100644 --- a/ui/components/app/transaction-status/index.scss +++ b/ui/components/app/transaction-status-label/index.scss @@ -1,4 +1,4 @@ -.transaction-status { +.transaction-status-label { display: inline; &--confirmed { diff --git a/ui/components/app/transaction-status/transaction-status.component.js b/ui/components/app/transaction-status-label/transaction-status-label.js similarity index 61% rename from ui/components/app/transaction-status/transaction-status.component.js rename to ui/components/app/transaction-status-label/transaction-status-label.js index 000c84a28..c0ea92b4b 100644 --- a/ui/components/app/transaction-status/transaction-status.component.js +++ b/ui/components/app/transaction-status-label/transaction-status-label.js @@ -5,8 +5,8 @@ import Tooltip from '../../ui/tooltip'; import { useI18nContext } from '../../../hooks/useI18nContext'; import { - TRANSACTION_GROUP_STATUSES, - TRANSACTION_STATUSES, + TransactionGroupStatus, + TransactionStatus, } from '../../../../shared/constants/transaction'; const QUEUED_PSEUDO_STATUS = 'queued'; @@ -22,22 +22,22 @@ const QUEUED_PSEUDO_STATUS = 'queued'; * status label will be the date the transaction was finalized. */ const pendingStatusHash = { - [TRANSACTION_STATUSES.SUBMITTED]: TRANSACTION_GROUP_STATUSES.PENDING, - [TRANSACTION_STATUSES.APPROVED]: TRANSACTION_GROUP_STATUSES.PENDING, - [TRANSACTION_STATUSES.SIGNED]: TRANSACTION_GROUP_STATUSES.PENDING, + [TransactionStatus.submitted]: TransactionGroupStatus.pending, + [TransactionStatus.approved]: TransactionGroupStatus.pending, + [TransactionStatus.signed]: TransactionGroupStatus.pending, }; const statusToClassNameHash = { - [TRANSACTION_STATUSES.UNAPPROVED]: 'transaction-status--unapproved', - [TRANSACTION_STATUSES.REJECTED]: 'transaction-status--rejected', - [TRANSACTION_STATUSES.FAILED]: 'transaction-status--failed', - [TRANSACTION_STATUSES.DROPPED]: 'transaction-status--dropped', - [TRANSACTION_GROUP_STATUSES.CANCELLED]: 'transaction-status--cancelled', - [QUEUED_PSEUDO_STATUS]: 'transaction-status--queued', - [TRANSACTION_GROUP_STATUSES.PENDING]: 'transaction-status--pending', + [TransactionStatus.unapproved]: 'transaction-status-label--unapproved', + [TransactionStatus.rejected]: 'transaction-status-label--rejected', + [TransactionStatus.failed]: 'transaction-status-label--failed', + [TransactionStatus.dropped]: 'transaction-status-label--dropped', + [TransactionGroupStatus.cancelled]: 'transaction-status-label--cancelled', + [QUEUED_PSEUDO_STATUS]: 'transaction-status-label--queued', + [TransactionGroupStatus.pending]: 'transaction-status-label--pending', }; -export default function TransactionStatus({ +export default function TransactionStatusLabel({ status, date, error, @@ -50,12 +50,12 @@ export default function TransactionStatus({ let statusKey = status; if (pendingStatusHash[status]) { statusKey = isEarliestNonce - ? TRANSACTION_GROUP_STATUSES.PENDING + ? TransactionGroupStatus.pending : QUEUED_PSEUDO_STATUS; } const statusText = - statusKey === TRANSACTION_STATUSES.CONFIRMED && !statusOnly + statusKey === TransactionStatus.confirmed && !statusOnly ? date : statusKey && t(statusKey); @@ -64,8 +64,8 @@ export default function TransactionStatus({ position="top" title={tooltipText} wrapperClassName={classnames( - 'transaction-status', - `transaction-status--${statusKey}`, + 'transaction-status-label', + `transaction-status-label--${statusKey}`, className, statusToClassNameHash[statusKey], )} @@ -75,7 +75,7 @@ export default function TransactionStatus({ ); } -TransactionStatus.propTypes = { +TransactionStatusLabel.propTypes = { status: PropTypes.string, className: PropTypes.string, date: PropTypes.string, diff --git a/ui/components/app/transaction-status/transaction-status.component.test.js b/ui/components/app/transaction-status-label/transaction-status-label.test.js similarity index 66% rename from ui/components/app/transaction-status/transaction-status.component.test.js rename to ui/components/app/transaction-status-label/transaction-status-label.test.js index 068b47e25..5b508917f 100644 --- a/ui/components/app/transaction-status/transaction-status.component.test.js +++ b/ui/components/app/transaction-status-label/transaction-status-label.test.js @@ -1,8 +1,8 @@ import React from 'react'; import { renderWithProvider } from '../../../../test/lib/render-helpers'; -import TransactionStatus from '.'; +import TransactionStatusLabel from '.'; -describe('TransactionStatus Component', () => { +describe('TransactionStatusLabel Component', () => { it('should render CONFIRMED properly', () => { const confirmedProps = { status: 'confirmed', @@ -10,7 +10,7 @@ describe('TransactionStatus Component', () => { }; const { container } = renderWithProvider( - , + , ); expect(container).toMatchSnapshot(); @@ -23,7 +23,9 @@ describe('TransactionStatus Component', () => { error: { message: 'test-title' }, }; - const { container } = renderWithProvider(); + const { container } = renderWithProvider( + , + ); expect(container).toMatchSnapshot(); }); @@ -35,7 +37,9 @@ describe('TransactionStatus Component', () => { isEarliestNonce: true, }; - const { container } = renderWithProvider(); + const { container } = renderWithProvider( + , + ); expect(container).toMatchSnapshot(); }); @@ -45,7 +49,9 @@ describe('TransactionStatus Component', () => { status: 'queued', }; - const { container } = renderWithProvider(); + const { container } = renderWithProvider( + , + ); expect(container).toMatchSnapshot(); }); @@ -55,7 +61,9 @@ describe('TransactionStatus Component', () => { status: 'unapproved', }; - const { container } = renderWithProvider(); + const { container } = renderWithProvider( + , + ); expect(container).toMatchSnapshot(); }); diff --git a/ui/components/app/transaction-status/__snapshots__/transaction-status.component.test.js.snap b/ui/components/app/transaction-status/__snapshots__/transaction-status.component.test.js.snap deleted file mode 100644 index 14e5eefaa..000000000 --- a/ui/components/app/transaction-status/__snapshots__/transaction-status.component.test.js.snap +++ /dev/null @@ -1,60 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`TransactionStatus Component should render CONFIRMED properly 1`] = ` -
-
- June 1 -
-
-`; - -exports[`TransactionStatus Component should render PENDING properly 1`] = ` -
-
- [pending] -
-
-`; - -exports[`TransactionStatus Component should render PENDING properly when status is APPROVED 1`] = ` -
-
-
- [pending] -
-
-
-`; - -exports[`TransactionStatus Component should render QUEUED properly 1`] = ` -
-
- [queued] -
-
-`; - -exports[`TransactionStatus Component should render UNAPPROVED properly 1`] = ` -
-
- [unapproved] -
-
-`; diff --git a/ui/components/app/transaction-status/index.js b/ui/components/app/transaction-status/index.js deleted file mode 100644 index 61bb74e20..000000000 --- a/ui/components/app/transaction-status/index.js +++ /dev/null @@ -1 +0,0 @@ -export { default } from './transaction-status.component'; diff --git a/ui/components/app/wallet-overview/eth-overview.js b/ui/components/app/wallet-overview/eth-overview.js index 5a8775720..06ecad8f8 100644 --- a/ui/components/app/wallet-overview/eth-overview.js +++ b/ui/components/app/wallet-overview/eth-overview.js @@ -33,7 +33,7 @@ import { MetaMetricsContext } from '../../../contexts/metametrics'; import { EVENT, EVENT_NAMES } from '../../../../shared/constants/metametrics'; import Spinner from '../../ui/spinner'; import { startNewDraftTransaction } from '../../../ducks/send'; -import { ASSET_TYPES } from '../../../../shared/constants/transaction'; +import { AssetType } from '../../../../shared/constants/transaction'; import DepositPopover from '../deposit-popover'; import WalletOverview from './wallet-overview'; @@ -140,7 +140,7 @@ const EthOverview = ({ className }) => { }, }); dispatch( - startNewDraftTransaction({ type: ASSET_TYPES.NATIVE }), + startNewDraftTransaction({ type: AssetType.native }), ).then(() => { history.push(SEND_ROUTE); }); diff --git a/ui/components/app/wallet-overview/token-overview.js b/ui/components/app/wallet-overview/token-overview.js index f701bb308..e057f0383 100644 --- a/ui/components/app/wallet-overview/token-overview.js +++ b/ui/components/app/wallet-overview/token-overview.js @@ -34,7 +34,7 @@ import { INVALID_ASSET_TYPE } from '../../../helpers/constants/error-keys'; import { showModal } from '../../../store/actions'; import { MetaMetricsContext } from '../../../contexts/metametrics'; import { EVENT, EVENT_NAMES } from '../../../../shared/constants/metametrics'; -import { ASSET_TYPES } from '../../../../shared/constants/transaction'; +import { AssetType } from '../../../../shared/constants/transaction'; import DepositPopover from '../deposit-popover'; import WalletOverview from './wallet-overview'; @@ -146,7 +146,7 @@ const TokenOverview = ({ className, token }) => { try { await dispatch( startNewDraftTransaction({ - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: token, }), ); diff --git a/ui/ducks/confirm-transaction/confirm-transaction.duck.test.js b/ui/ducks/confirm-transaction/confirm-transaction.duck.test.js index 816c544eb..2f5e1ff4c 100644 --- a/ui/ducks/confirm-transaction/confirm-transaction.duck.test.js +++ b/ui/ducks/confirm-transaction/confirm-transaction.duck.test.js @@ -1,7 +1,7 @@ import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import sinon from 'sinon'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import ConfirmTransactionReducer, * as actions from './confirm-transaction.duck'; @@ -276,7 +276,7 @@ describe('Confirm Transaction Duck', () => { loadingDefaults: false, metamaskNetworkId: '5', origin: 'faucet.metamask.io', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, time: 1530838113716, txParams: { from: '0xc5ae6383e126f901dcb06131d97a88745bfa88d6', @@ -351,7 +351,7 @@ describe('Confirm Transaction Duck', () => { loadingDefaults: false, metamaskNetworkId: '5', origin: 'faucet.metamask.io', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, time: 1530838113716, txParams: { from: '0xc5ae6383e126f901dcb06131d97a88745bfa88d6', diff --git a/ui/ducks/metamask/metamask.test.js b/ui/ducks/metamask/metamask.test.js index cdd22052b..8b39e355b 100644 --- a/ui/ducks/metamask/metamask.test.js +++ b/ui/ducks/metamask/metamask.test.js @@ -1,4 +1,4 @@ -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import * as actionConstants from '../../store/actionConstants'; import reduceMetamask, { getBlockGasLimit, @@ -84,7 +84,7 @@ describe('MetaMask Reducers', () => { 4768706228115573: { id: 4768706228115573, time: 1487363153561, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, gasMultiplier: 1, metamaskNetworkId: '5', txParams: { @@ -364,7 +364,7 @@ describe('MetaMask Reducers', () => { 4768706228115573: { id: 4768706228115573, time: 1487363153561, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, gasMultiplier: 1, metamaskNetworkId: '5', txParams: { diff --git a/ui/ducks/send/helpers.js b/ui/ducks/send/helpers.js index 6cf35b5f0..d0497c892 100644 --- a/ui/ducks/send/helpers.js +++ b/ui/ducks/send/helpers.js @@ -4,8 +4,8 @@ import { GAS_LIMITS, MIN_GAS_LIMIT_HEX } from '../../../shared/constants/gas'; import { calcTokenAmount } from '../../../shared/lib/transactions-controller-utils'; import { CHAIN_ID_TO_GAS_LIMIT_BUFFER_MAP } from '../../../shared/constants/network'; import { - ASSET_TYPES, - TRANSACTION_ENVELOPE_TYPES, + AssetType, + TransactionEnvelopeType, } from '../../../shared/constants/transaction'; import { readAddressAsContract } from '../../../shared/modules/contract-utils'; import { @@ -191,7 +191,7 @@ export function generateTransactionParams(sendState) { gas: draftTransaction.gas.gasLimit, }; switch (draftTransaction.asset.type) { - case ASSET_TYPES.TOKEN: + case AssetType.token: // When sending a token the to address is the contract address of // the token being sent. The value is set to '0x0' and the data // is generated from the recipient address, token being sent and @@ -204,7 +204,7 @@ export function generateTransactionParams(sendState) { sendToken: draftTransaction.asset.details, }); break; - case ASSET_TYPES.NFT: + case AssetType.NFT: // When sending a token the to address is the contract address of // the token being sent. The value is set to '0x0' and the data // is generated from the recipient address, token being sent and @@ -219,7 +219,7 @@ export function generateTransactionParams(sendState) { tokenId: draftTransaction.asset.details.tokenId, }); break; - case ASSET_TYPES.NATIVE: + case AssetType.native: default: // When sending native currency the to and value fields use the // recipient and amount values and the data key is either null or @@ -233,7 +233,7 @@ export function generateTransactionParams(sendState) { // based on the type of transaction the network supports. We will also set // the type param here. if (sendState.eip1559support) { - txParams.type = TRANSACTION_ENVELOPE_TYPES.FEE_MARKET; + txParams.type = TransactionEnvelopeType.feeMarket; txParams.maxFeePerGas = draftTransaction.gas.maxFeePerGas; txParams.maxPriorityFeePerGas = draftTransaction.gas.maxPriorityFeePerGas; @@ -250,7 +250,7 @@ export function generateTransactionParams(sendState) { } } else { txParams.gasPrice = draftTransaction.gas.gasPrice; - txParams.type = TRANSACTION_ENVELOPE_TYPES.LEGACY; + txParams.type = TransactionEnvelopeType.legacy; } return txParams; diff --git a/ui/ducks/send/helpers.test.js b/ui/ducks/send/helpers.test.js index 404c29d71..69de6bed9 100644 --- a/ui/ducks/send/helpers.test.js +++ b/ui/ducks/send/helpers.test.js @@ -1,9 +1,9 @@ import { ethers } from 'ethers'; import { GAS_LIMITS } from '../../../shared/constants/gas'; import { - ASSET_TYPES, - TOKEN_STANDARDS, - TRANSACTION_ENVELOPE_TYPES, + AssetType, + TokenStandard, + TransactionEnvelopeType, } from '../../../shared/constants/transaction'; import { BURN_ADDRESS } from '../../../shared/modules/hexstring-utils'; import { getInitialSendStateWithExistingTxState } from '../../../test/jest/mocks'; @@ -30,7 +30,7 @@ describe('Send Slice Helpers', () => { value: '0x1', }, asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, balance: '0xaf', details: tokenDetails, }, @@ -64,11 +64,11 @@ describe('Send Slice Helpers', () => { value: '0x1', }, asset: { - type: ASSET_TYPES.NFT, + type: AssetType.NFT, balance: '0xaf', details: { address: '0xToken', - standard: TOKEN_STANDARDS.ERC721, + standard: TokenStandard.ERC721, tokenId: ethers.BigNumber.from(15000).toString(), }, }, @@ -102,7 +102,7 @@ describe('Send Slice Helpers', () => { value: '0x1', }, asset: { - type: ASSET_TYPES.NATIVE, + type: AssetType.native, balance: '0xaf', details: null, }, @@ -132,7 +132,7 @@ describe('Send Slice Helpers', () => { value: '0x1', }, asset: { - type: ASSET_TYPES.NATIVE, + type: AssetType.native, balance: '0xaf', details: null, }, @@ -144,7 +144,7 @@ describe('Send Slice Helpers', () => { maxPriorityFeePerGas: '0x1', gasLimit: GAS_LIMITS.SIMPLE, }, - transactionType: TRANSACTION_ENVELOPE_TYPES.FEE_MARKET, + transactionType: TransactionEnvelopeType.feeMarket, }), eip1559support: true, }); diff --git a/ui/ducks/send/send.js b/ui/ducks/send/send.js index 4222ade30..1b1f2cb13 100644 --- a/ui/ducks/send/send.js +++ b/ui/ducks/send/send.js @@ -97,10 +97,10 @@ import fetchEstimatedL1Fee from '../../helpers/utils/optimism/fetchEstimatedL1Fe import { ETH } from '../../helpers/constants/common'; import { - ASSET_TYPES, - TOKEN_STANDARDS, - TRANSACTION_ENVELOPE_TYPES, - TRANSACTION_TYPES, + AssetType, + TokenStandard, + TransactionEnvelopeType, + TransactionType, } from '../../../shared/constants/transaction'; import { INVALID_ASSET_TYPE } from '../../helpers/constants/error-keys'; import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils'; @@ -122,18 +122,12 @@ import { * import('immer/dist/internal').WritableDraft * )} SendStateDraft * @typedef {( - * import('../../../shared/constants/transaction').AssetTypesString - * )} AssetTypesString - * @typedef {( * import( '../../helpers/constants/common').TokenStandardStrings * )} TokenStandardStrings * @typedef {( * import( '../../../shared/constants/tokens').TokenDetails * )} TokenDetails * @typedef {( - * import('../../../shared/constants/transaction').TransactionTypeString - * )} TransactionTypeString - * @typedef {( * import('@metamask/gas-fee-controller').LegacyGasPriceEstimate * )} LegacyGasPriceEstimate * @typedef {( @@ -297,7 +291,7 @@ export const RECIPIENT_SEARCH_MODES = { * Will be null when asset.type is 'NATIVE'. * @property {string} [error] - Error to display when there is an issue * with the asset. - * @property {AssetTypesString} type - The type of asset that the user + * @property {AssetType} type - The type of asset that the user * is attempting to send. Defaults to 'NATIVE' which represents the native * asset of the chain. Can also be 'TOKEN' or 'NFT'. */ @@ -374,7 +368,7 @@ export const draftTransactionInitialState = { balance: '0x0', details: null, error: null, - type: ASSET_TYPES.NATIVE, + type: AssetType.native, }, fromAccount: null, gas: { @@ -397,7 +391,7 @@ export const draftTransactionInitialState = { recipientWarningAcknowledged: false, }, status: SEND_STATUSES.VALID, - transactionType: TRANSACTION_ENVELOPE_TYPES.LEGACY, + transactionType: TransactionEnvelopeType.legacy, userInputHexData: null, }; @@ -561,7 +555,7 @@ export const computeEstimatedGasLimit = createAsyncThunk( /** * @typedef {object} Asset - * @property {AssetTypesString} type - The type of asset that the user + * @property {AssetType} type - The type of asset that the user * is attempting to send. Defaults to 'NATIVE' which represents the native * asset of the chain. Can also be 'TOKEN' or 'NFT'. * @property {string} balance - A hex string representing the balance @@ -660,8 +654,8 @@ export const initializeSendState = createAsyncThunk( draftTransaction.recipient.address ) { gasLimit = - draftTransaction.asset.type === ASSET_TYPES.TOKEN || - draftTransaction.asset.type === ASSET_TYPES.NFT + draftTransaction.asset.type === AssetType.token || + draftTransaction.asset.type === AssetType.NFT ? GAS_LIMITS.BASE_TOKEN_ESTIMATE : GAS_LIMITS.SIMPLE; // Run our estimateGasLimit logic to get a more accurate estimation of @@ -738,7 +732,7 @@ export const initializeSendState = createAsyncThunk( /** * @typedef {object} GasFeeUpdateParams - * @property {TransactionTypeString} transactionType - The transaction type + * @property {TransactionType} transactionType - The transaction type * @property {string} [maxFeePerGas] - The maximum amount in hex wei to pay * per gas on a FEE_MARKET transaction. * @property {string} [maxPriorityFeePerGas] - The maximum amount in hex @@ -834,8 +828,7 @@ const slice = createSlice({ // use maxFeePerGas as the multiplier if working with a FEE_MARKET transaction // otherwise use gasPrice if ( - draftTransaction.transactionType === - TRANSACTION_ENVELOPE_TYPES.FEE_MARKET + draftTransaction.transactionType === TransactionEnvelopeType.feeMarket ) { draftTransaction.gas.gasTotal = addHexPrefix( calcGasTotal( @@ -853,7 +846,7 @@ const slice = createSlice({ } if ( state.amountMode === AMOUNT_MODES.MAX && - draftTransaction.asset.type === ASSET_TYPES.NATIVE + draftTransaction.asset.type === AssetType.native ) { slice.caseReducers.updateAmountToMax(state); } @@ -909,7 +902,7 @@ const slice = createSlice({ const draftTransaction = state.draftTransactions[state.currentTransactionUUID]; let amount = '0x0'; - if (draftTransaction.asset.type === ASSET_TYPES.TOKEN) { + if (draftTransaction.asset.type === AssetType.token) { const decimals = draftTransaction.asset.details?.decimals ?? 0; const multiplier = Math.pow(10, Number(decimals)); @@ -960,8 +953,8 @@ const slice = createSlice({ draftTransaction.asset.error = asset.error; if ( - draftTransaction.asset.type === ASSET_TYPES.TOKEN || - draftTransaction.asset.type === ASSET_TYPES.NFT + draftTransaction.asset.type === AssetType.token || + draftTransaction.asset.type === AssetType.NFT ) { draftTransaction.asset.details = asset.details; } else { @@ -998,7 +991,7 @@ const slice = createSlice({ case GAS_ESTIMATE_TYPES.FEE_MARKET: slice.caseReducers.updateGasFees(state, { payload: { - transactionType: TRANSACTION_ENVELOPE_TYPES.FEE_MARKET, + transactionType: TransactionEnvelopeType.feeMarket, maxFeePerGas: getGasPriceInHexWei( gasFeeEstimates.medium.suggestedMaxFeePerGas, ), @@ -1013,7 +1006,7 @@ const slice = createSlice({ slice.caseReducers.updateGasFees(state, { payload: { gasPrice: gasPriceEstimate, - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, isAutomaticUpdate: true, }, }); @@ -1023,7 +1016,7 @@ const slice = createSlice({ slice.caseReducers.updateGasFees(state, { payload: { gasPrice: getRoundedGasPrice(gasFeeEstimates.gasPrice), - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, isAutomaticUpdate: true, }, }); @@ -1049,8 +1042,7 @@ const slice = createSlice({ state.draftTransactions[state.currentTransactionUUID]; if (draftTransaction) { if ( - action.payload.transactionType === - TRANSACTION_ENVELOPE_TYPES.FEE_MARKET + action.payload.transactionType === TransactionEnvelopeType.feeMarket ) { draftTransaction.gas.maxFeePerGas = addHexPrefix( action.payload.maxFeePerGas, @@ -1058,8 +1050,7 @@ const slice = createSlice({ draftTransaction.gas.maxPriorityFeePerGas = addHexPrefix( action.payload.maxPriorityFeePerGas, ); - draftTransaction.transactionType = - TRANSACTION_ENVELOPE_TYPES.FEE_MARKET; + draftTransaction.transactionType = TransactionEnvelopeType.feeMarket; } else { if (action.payload.manuallyEdited) { draftTransaction.gas.wasManuallyEdited = true; @@ -1075,7 +1066,7 @@ const slice = createSlice({ action.payload.gasPrice, ); } - draftTransaction.transactionType = TRANSACTION_ENVELOPE_TYPES.LEGACY; + draftTransaction.transactionType = TransactionEnvelopeType.legacy; } slice.caseReducers.calculateGasTotal(state); } @@ -1112,7 +1103,7 @@ const slice = createSlice({ state.gasTotalForLayer1 = action.payload; if ( state.amountMode === AMOUNT_MODES.MAX && - draftTransaction.asset.type === ASSET_TYPES.NATIVE + draftTransaction.asset.type === AssetType.native ) { slice.caseReducers.updateAmountToMax(state); } @@ -1221,7 +1212,7 @@ const slice = createSlice({ draftTransaction.amount.value = addHexPrefix(action.payload); // Once amount has changed, validate the field slice.caseReducers.validateAmountField(state); - if (draftTransaction.asset.type === ASSET_TYPES.NATIVE) { + if (draftTransaction.asset.type === AssetType.native) { // if sending the native asset the amount being sent will impact the // gas field as well because the gas validation takes into // consideration the available balance minus amount sent before @@ -1280,7 +1271,7 @@ const slice = createSlice({ switch (true) { // set error to INSUFFICIENT_FUNDS_FOR_GAS_ERROR if the account balance is lower // than the total price of the transaction inclusive of gas fees. - case draftTransaction.asset.type === ASSET_TYPES.NATIVE && + case draftTransaction.asset.type === AssetType.native && !isBalanceSufficient({ amount: draftTransaction.amount.value, balance: draftTransaction.asset.balance, @@ -1290,7 +1281,7 @@ const slice = createSlice({ break; // set error to INSUFFICIENT_TOKENS_ERROR if the token balance is lower // than the amount of token the user is attempting to send. - case draftTransaction.asset.type === ASSET_TYPES.TOKEN && + case draftTransaction.asset.type === AssetType.token && !isTokenBalanceSufficient({ tokenBalance: draftTransaction.asset.balance ?? '0x0', amount: draftTransaction.amount.value, @@ -1326,7 +1317,7 @@ const slice = createSlice({ state.draftTransactions[state.currentTransactionUUID]; const insufficientFunds = !isBalanceSufficient({ amount: - draftTransaction.asset.type === ASSET_TYPES.NATIVE + draftTransaction.asset.type === AssetType.native ? draftTransaction.amount.value : '0x0', balance: @@ -1423,7 +1414,7 @@ const slice = createSlice({ case Boolean(draftTransaction.amount.error): case Boolean(draftTransaction.gas.error): case Boolean(draftTransaction.asset.error): - case draftTransaction.asset.type === ASSET_TYPES.TOKEN && + case draftTransaction.asset.type === AssetType.token && draftTransaction.asset.details === null: case state.stage === SEND_STAGES.ADD_RECIPIENT: case state.stage === SEND_STAGES.INACTIVE: @@ -1465,7 +1456,7 @@ const slice = createSlice({ action.payload.account.balance; // We need to update the asset balance if the asset is the native // network asset. Once we update the balance we recompute error state. - if (draftTransaction.asset.type === ASSET_TYPES.NATIVE) { + if (draftTransaction.asset.type === AssetType.native) { draftTransaction.asset.balance = action.payload.account.balance; } slice.caseReducers.validateAmountField(state); @@ -1546,7 +1537,7 @@ const slice = createSlice({ // the network from the network dropdown, then the selected asset is // no longer valid and should be set to the native asset for the // network. - draftTransaction.asset.type = ASSET_TYPES.NATIVE; + draftTransaction.asset.type = AssetType.native; draftTransaction.asset.balance = draftTransaction.fromAccount?.balance ?? state.selectedAccount.balance; @@ -1597,7 +1588,7 @@ const slice = createSlice({ // the asset is set to the native network asset, and then validate // the transaction. if (draftTransaction) { - if (draftTransaction?.asset.type === ASSET_TYPES.NATIVE) { + if (draftTransaction?.asset.type === AssetType.native) { draftTransaction.asset.balance = action.payload.account.balance; } slice.caseReducers.validateAmountField(state); @@ -1685,7 +1676,7 @@ const debouncedValidateRecipientUserInput = debounce( * route to the send page *after* dispatching this action resolves to ensure * that the draftTransaction is properly created. * - * @param {AssetTypesString} assetType - The type of asset the transaction + * @param {AssetType} assetType - The type of asset the transaction * being edited was sending. The details of the asset will be retrieved from * the transaction data in state. * @param {string} transactionId - The id of the transaction being edited. @@ -1699,7 +1690,7 @@ export function editExistingTransaction(assetType, transactionId) { const transaction = unapprovedTransactions[transactionId]; const account = getTargetAccount(state, transaction.txParams.from); - if (assetType === ASSET_TYPES.NATIVE) { + if (assetType === AssetType.native) { await dispatch( actions.addNewDraft({ ...draftTransactionInitialState, @@ -1730,17 +1721,14 @@ export function editExistingTransaction(assetType, transactionId) { }), ); await dispatch( - updateSendAsset( - { type: ASSET_TYPES.NATIVE }, - { initialAssetSet: true }, - ), + updateSendAsset({ type: AssetType.native }, { initialAssetSet: true }), ); } else { const tokenData = parseStandardTokenTransactionData( transaction.txParams.data, ); const tokenAmountInDec = - assetType === ASSET_TYPES.TOKEN ? getTokenValueParam(tokenData) : '1'; + assetType === AssetType.token ? getTokenValueParam(tokenData) : '1'; const address = getTokenAddressParam(tokenData); const nickname = getAddressBookEntryOrAccountName(state, address) ?? ''; @@ -1783,7 +1771,7 @@ export function editExistingTransaction(assetType, transactionId) { type: assetType, details: { address: transaction.txParams.to, - ...(assetType === ASSET_TYPES.NFT + ...(assetType === AssetType.NFT ? { tokenId: getTokenIdParam(tokenData) ?? @@ -1821,7 +1809,7 @@ export function updateGasPrice(gasPrice) { dispatch( actions.updateGasFees({ gasPrice, - transactionType: TRANSACTION_ENVELOPE_TYPES.LEGACY, + transactionType: TransactionEnvelopeType.legacy, manuallyEdited: true, }), ); @@ -1945,7 +1933,7 @@ export function updateSendAmount(amount) { const draftTransaction = state[name].draftTransactions[state[name].currentTransactionUUID]; let logAmount = amount; - if (draftTransaction.asset.type === ASSET_TYPES.TOKEN) { + if (draftTransaction.asset.type === AssetType.token) { const multiplier = Math.pow( 10, Number(draftTransaction.asset.details?.decimals || 0), @@ -2004,15 +1992,15 @@ export function updateSendAsset( state[name].selectedAccount.address ?? getSelectedAddress(state); const account = getTargetAccount(state, sendingAddress); - if (type === ASSET_TYPES.NATIVE) { + if (type === AssetType.native) { const unapprovedTxs = getUnapprovedTxs(state); const unapprovedTx = unapprovedTxs?.[draftTransaction.id]; await dispatch( addHistoryEntry( - `sendFlow - user set asset of type ${ - ASSET_TYPES.NATIVE - } with symbol ${state.metamask.provider?.ticker ?? ETH}`, + `sendFlow - user set asset of type ${AssetType.native} with symbol ${ + state.metamask.provider?.ticker ?? ETH + }`, ), ); await dispatch( @@ -2034,9 +2022,9 @@ export function updateSendAsset( // set the hex data of the transaction being editing to be empty. // then the user will not want to send any hex data now that they have change the if ( - unapprovedTx?.type === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM || - unapprovedTx?.type === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER || - unapprovedTx?.type === TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM + unapprovedTx?.type === TransactionType.tokenMethodTransferFrom || + unapprovedTx?.type === TransactionType.tokenMethodTransfer || + unapprovedTx?.type === TransactionType.tokenMethodSafeTransferFrom ) { await dispatch(actions.updateUserInputHexData('')); } @@ -2058,7 +2046,7 @@ export function updateSendAsset( error: null, }; - if (details.standard === TOKEN_STANDARDS.ERC20) { + if (details.standard === TokenStandard.ERC20) { asset.balance = addHexPrefix( calcTokenAmount(details.balance, details.decimals).toString(16), ); @@ -2069,15 +2057,15 @@ export function updateSendAsset( ), ); } else if ( - details.standard === TOKEN_STANDARDS.ERC1155 && - type === ASSET_TYPES.NFT + details.standard === TokenStandard.ERC1155 && + type === AssetType.NFT ) { throw new Error('Sends of ERC1155 tokens are not currently supported'); } else if ( - details.standard === TOKEN_STANDARDS.ERC1155 || - details.standard === TOKEN_STANDARDS.ERC721 + details.standard === TokenStandard.ERC1155 || + details.standard === TokenStandard.ERC721 ) { - if (type === ASSET_TYPES.TOKEN && process.env.NFTS_V1) { + if (type === AssetType.token && process.env.NFTS_V1) { dispatch( showModal({ name: 'CONVERT_TOKEN_TO_NFT', @@ -2149,7 +2137,7 @@ export function updateSendHexData(hexData) { const state = getState(); const draftTransaction = state[name].draftTransactions[state[name].currentTransactionUUID]; - if (draftTransaction.asset.type === ASSET_TYPES.NATIVE) { + if (draftTransaction.asset.type === AssetType.native) { await dispatch(computeEstimatedGasLimit()); } }; @@ -2288,14 +2276,14 @@ export function signTransaction() { } else { let transactionType = draftTransaction.recipient.type === RECIPIENT_TYPES.SMART_CONTRACT - ? TRANSACTION_TYPES.CONTRACT_INTERACTION - : TRANSACTION_TYPES.SIMPLE_SEND; + ? TransactionType.contractInteraction + : TransactionType.simpleSend; - if (draftTransaction.asset.type !== ASSET_TYPES.NATIVE) { + if (draftTransaction.asset.type !== AssetType.native) { transactionType = - draftTransaction.asset.type === ASSET_TYPES.NFT - ? TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM - : TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER; + draftTransaction.asset.type === AssetType.NFT + ? TransactionType.tokenMethodTransferFrom + : TransactionType.tokenMethodTransfer; } await dispatch( addHistoryEntry( @@ -2363,7 +2351,7 @@ export function startNewDraftTransaction(asset) { await dispatch( updateSendAsset({ - type: asset.type ?? ASSET_TYPES.NATIVE, + type: asset.type ?? AssetType.native, details: asset.details, }), ); @@ -2514,7 +2502,7 @@ export function getSendAssetAddress(state) { * @type {Selector} */ export function getIsAssetSendable(state) { - if (getSendAsset(state)?.type === ASSET_TYPES.NATIVE) { + if (getSendAsset(state)?.type === AssetType.native) { return true; } return getSendAsset(state)?.details?.isERC721 === false; diff --git a/ui/ducks/send/send.test.js b/ui/ducks/send/send.test.js index 285a593aa..98d402cf4 100644 --- a/ui/ducks/send/send.test.js +++ b/ui/ducks/send/send.test.js @@ -15,9 +15,9 @@ import { CHAIN_IDS } from '../../../shared/constants/network'; import { GAS_ESTIMATE_TYPES, GAS_LIMITS } from '../../../shared/constants/gas'; import { KEYRING_TYPES } from '../../../shared/constants/keyrings'; import { - ASSET_TYPES, - TOKEN_STANDARDS, - TRANSACTION_ENVELOPE_TYPES, + AssetType, + TokenStandard, + TransactionEnvelopeType, } from '../../../shared/constants/transaction'; import * as Actions from '../../store/actions'; import { setBackgroundConnection } from '../../../test/jest'; @@ -186,7 +186,7 @@ describe('Send Slice', () => { maxFeePerGas: '0x2', gasLimit: GAS_LIMITS.SIMPLE, }, - transactionType: TRANSACTION_ENVELOPE_TYPES.FEE_MARKET, + transactionType: TransactionEnvelopeType.feeMarket, }), action, ); @@ -299,7 +299,7 @@ describe('Send Slice', () => { const action = { type: 'send/updateGasFees', payload: { - transactionType: TRANSACTION_ENVELOPE_TYPES.FEE_MARKET, + transactionType: TransactionEnvelopeType.feeMarket, maxFeePerGas: '0x2', maxPriorityFeePerGas: '0x1', }, @@ -320,7 +320,7 @@ describe('Send Slice', () => { ); expect(draftTransaction.transactionType).toBe( - TRANSACTION_ENVELOPE_TYPES.FEE_MARKET, + TransactionEnvelopeType.feeMarket, ); }); @@ -328,7 +328,7 @@ describe('Send Slice', () => { const action = { type: 'send/updateGasFees', payload: { - transactionType: TRANSACTION_ENVELOPE_TYPES.LEGACY, + transactionType: TransactionEnvelopeType.legacy, gasPrice: '0x1', }, }; @@ -343,7 +343,7 @@ describe('Send Slice', () => { action.payload.gasPrice, ); expect(draftTransaction.transactionType).toBe( - TRANSACTION_ENVELOPE_TYPES.LEGACY, + TransactionEnvelopeType.legacy, ); }); }); @@ -482,7 +482,7 @@ describe('Send Slice', () => { error: CONTRACT_ADDRESS_ERROR, }, asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, }, }); @@ -510,7 +510,7 @@ describe('Send Slice', () => { type: 'send/updateAsset', payload: { asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: { address: '0xTokenAddress', decimals: 0, @@ -713,7 +713,7 @@ describe('Send Slice', () => { const tokenAssetTypeState = { ...getInitialSendStateWithExistingTxState({ asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: { address: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc', }, @@ -840,7 +840,7 @@ describe('Send Slice', () => { value: '0x6fc23ac0', // 1875000000 }, asset: { - type: ASSET_TYPES.NATIVE, + type: AssetType.native, balance: '0x77359400', // 2000000000 }, gas: { @@ -867,7 +867,7 @@ describe('Send Slice', () => { value: '0x77359400', // 2000000000 }, asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, balance: '0x6fc23ac0', // 1875000000 details: { decimals: 0, @@ -994,7 +994,7 @@ describe('Send Slice', () => { it('should set `INVALID` send state status when asset type is `TOKEN` without token details present', () => { const assetErrorState = getInitialSendStateWithExistingTxState({ asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, }, }); @@ -1032,7 +1032,7 @@ describe('Send Slice', () => { const validSendStatusState = { ...getInitialSendStateWithExistingTxState({ asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: { address: '0x000', }, @@ -1410,7 +1410,7 @@ describe('Send Slice', () => { payload: { gasPrice: '0x0', manuallyEdited: true, - transactionType: TRANSACTION_ENVELOPE_TYPES.LEGACY, + transactionType: TransactionEnvelopeType.legacy, }, }, ]; @@ -1536,7 +1536,7 @@ describe('Send Slice', () => { }, send: getInitialSendStateWithExistingTxState({ asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: {}, }, gas: { @@ -1616,7 +1616,7 @@ describe('Send Slice', () => { const store = mockStore(defaultSendAssetState); const newSendAsset = { - type: ASSET_TYPES.NATIVE, + type: AssetType.native, }; await store.dispatch(updateSendAsset(newSendAsset)); @@ -1632,7 +1632,7 @@ describe('Send Slice', () => { expect(actionResult[1].type).toStrictEqual('send/updateAsset'); expect(actionResult[1].payload).toStrictEqual({ asset: { - type: ASSET_TYPES.NATIVE, + type: AssetType.native, balance: '0x0', error: null, details: null, @@ -1667,7 +1667,7 @@ describe('Send Slice', () => { const store = mockStore(defaultSendAssetState); const newSendAsset = { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: { address: 'tokenAddress', symbol: 'tokenSymbol', @@ -1688,7 +1688,7 @@ describe('Send Slice', () => { }); expect(actionResult[3].payload).toStrictEqual({ asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: { address: 'tokenAddress', symbol: 'TokenSymbol', @@ -1718,7 +1718,7 @@ describe('Send Slice', () => { const store = mockStore(defaultSendAssetState); const newSendAsset = { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: { address: 'tokenAddress', symbol: 'tokenSymbol', @@ -2003,7 +2003,7 @@ describe('Send Slice', () => { balance: '', }, asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: {}, }, gas: { @@ -2151,7 +2151,7 @@ describe('Send Slice', () => { const sendMaxModeState = { send: { asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: {}, }, gas: { @@ -2199,7 +2199,7 @@ describe('Send Slice', () => { send: { ...getInitialSendStateWithExistingTxState({ asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: {}, }, gas: { @@ -2424,7 +2424,7 @@ describe('Send Slice', () => { const store = mockStore(editTransactionState); - await store.dispatch(editExistingTransaction(ASSET_TYPES.NATIVE, 1)); + await store.dispatch(editExistingTransaction(AssetType.native, 1)); const actionResult = store.getActions(); expect(actionResult).toHaveLength(7); @@ -2442,7 +2442,7 @@ describe('Send Slice', () => { balance: '0x0', details: null, error: null, - type: ASSET_TYPES.NATIVE, + type: AssetType.native, }, fromAccount: { address: '0xAddress', @@ -2568,7 +2568,7 @@ describe('Send Slice', () => { const store = mockStore(editTransactionState); - await store.dispatch(editExistingTransaction(ASSET_TYPES.NFT, 1)); + await store.dispatch(editExistingTransaction(AssetType.NFT, 1)); const actionResult = store.getActions(); expect(actionResult).toHaveLength(9); expect(actionResult[0]).toMatchObject({ @@ -2585,7 +2585,7 @@ describe('Send Slice', () => { balance: '0x0', details: null, error: null, - type: ASSET_TYPES.NATIVE, + type: AssetType.native, }, fromAccount: { address: '0xAddress', @@ -2631,11 +2631,11 @@ describe('Send Slice', () => { details: { address: '0xCollectibleAddress', balance: '0x1', - standard: TOKEN_STANDARDS.ERC721, + standard: TokenStandard.ERC721, tokenId: '15000', }, error: null, - type: ASSET_TYPES.NFT, + type: AssetType.NFT, }, initialAssetSet: true, }, @@ -2760,7 +2760,7 @@ describe('Send Slice', () => { const store = mockStore(editTransactionState); - await store.dispatch(editExistingTransaction(ASSET_TYPES.TOKEN, 1)); + await store.dispatch(editExistingTransaction(AssetType.token, 1)); const actionResult = store.getActions(); expect(actionResult).toHaveLength(9); @@ -2776,7 +2776,7 @@ describe('Send Slice', () => { balance: '0x0', details: null, error: null, - type: ASSET_TYPES.NATIVE, + type: AssetType.native, }, fromAccount: { address: '0xAddress', @@ -2819,7 +2819,7 @@ describe('Send Slice', () => { payload: { asset: { balance: '0x0', - type: ASSET_TYPES.TOKEN, + type: AssetType.token, error: null, details: { balance: '0x0', @@ -3007,7 +3007,7 @@ describe('Send Slice', () => { asset: { balance: '0x0', details: { address: '0x0' }, - type: ASSET_TYPES.TOKEN, + type: AssetType.token, }, }), }), @@ -3022,7 +3022,7 @@ describe('Send Slice', () => { getIsAssetSendable({ send: getInitialSendStateWithExistingTxState({ asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, details: { isERC721: true }, }, }), diff --git a/ui/ducks/swaps/swaps.js b/ui/ducks/swaps/swaps.js index 9af2ee183..bc4234203 100644 --- a/ui/ducks/swaps/swaps.js +++ b/ui/ducks/swaps/swaps.js @@ -79,9 +79,9 @@ import { SLIPPAGE, } from '../../../shared/constants/swaps'; import { - TRANSACTION_TYPES, + TransactionType, IN_PROGRESS_TRANSACTION_STATUSES, - SMART_TRANSACTION_STATUSES, + SmartTransactionStatus, } from '../../../shared/constants/transaction'; import { getGasFeeEstimates, getTokens } from '../metamask/metamask'; import { ORIGIN_METAMASK } from '../../../shared/constants/app'; @@ -434,7 +434,7 @@ export const getPendingSmartTransactions = (state) => { return []; } return currentSmartTransactions.filter( - (stx) => stx.status === SMART_TRANSACTION_STATUSES.PENDING, + (stx) => stx.status === SmartTransactionStatus.pending, ); }; @@ -986,14 +986,14 @@ export const signAndSendSwapsSmartTransaction = ({ sourceTokenSymbol, swapMetaData, swapTokenValue, - type: TRANSACTION_TYPES.SWAP, + type: TransactionType.swap, }), ); if (approvalTxUuid) { await dispatch( updateSmartTransaction(approvalTxUuid, { origin: ORIGIN_METAMASK, - type: TRANSACTION_TYPES.SWAP_APPROVAL, + type: TransactionType.swapApproval, sourceTokenSymbol, }), ); @@ -1203,12 +1203,12 @@ export const signAndSendTransactions = ( } const approveTxMeta = await addUnapprovedTransaction( { ...approveTxParams, amount: '0x0' }, - TRANSACTION_TYPES.SWAP_APPROVAL, + TransactionType.swapApproval, ); await dispatch(setApproveTxId(approveTxMeta.id)); finalApproveTxMeta = await dispatch( updateSwapApprovalTransaction(approveTxMeta.id, { - type: TRANSACTION_TYPES.SWAP_APPROVAL, + type: TransactionType.swapApproval, sourceTokenSymbol: sourceTokenInfo.symbol, }), ); @@ -1223,7 +1223,7 @@ export const signAndSendTransactions = ( const tradeTxMeta = await addUnapprovedTransaction( usedTradeTxParams, - TRANSACTION_TYPES.SWAP, + TransactionType.swap, ); dispatch(setTradeTxId(tradeTxMeta.id)); @@ -1247,7 +1247,7 @@ export const signAndSendTransactions = ( estimatedBaseFee: decEstimatedBaseFee, sourceTokenSymbol: sourceTokenInfo.symbol, destinationTokenSymbol: destinationTokenInfo.symbol, - type: TRANSACTION_TYPES.SWAP, + type: TransactionType.swap, destinationTokenDecimals: destinationTokenInfo.decimals, destinationTokenAddress: destinationTokenInfo.address, swapMetaData, diff --git a/ui/helpers/constants/transactions.js b/ui/helpers/constants/transactions.js index 4bc5974cd..955dd6aa0 100644 --- a/ui/helpers/constants/transactions.js +++ b/ui/helpers/constants/transactions.js @@ -1,23 +1,23 @@ import { - TRANSACTION_TYPES, - TRANSACTION_STATUSES, + TransactionType, + TransactionStatus, } from '../../../shared/constants/transaction'; export const PENDING_STATUS_HASH = { - [TRANSACTION_STATUSES.UNAPPROVED]: true, - [TRANSACTION_STATUSES.APPROVED]: true, - [TRANSACTION_STATUSES.SUBMITTED]: true, - [TRANSACTION_STATUSES.PENDING]: true, + [TransactionStatus.unapproved]: true, + [TransactionStatus.approved]: true, + [TransactionStatus.submitted]: true, + [TransactionStatus.pending]: true, }; export const PRIORITY_STATUS_HASH = { ...PENDING_STATUS_HASH, - [TRANSACTION_STATUSES.CONFIRMED]: true, + [TransactionStatus.confirmed]: true, }; export const TOKEN_CATEGORY_HASH = { - [TRANSACTION_TYPES.TOKEN_METHOD_APPROVE]: true, - [TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL]: true, - [TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER]: true, - [TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM]: true, + [TransactionType.tokenMethodApprove]: true, + [TransactionType.tokenMethodSetApprovalForAll]: true, + [TransactionType.tokenMethodTransfer]: true, + [TransactionType.tokenMethodTransferFrom]: true, }; diff --git a/ui/helpers/utils/token-util.js b/ui/helpers/utils/token-util.js index 3585d4fe9..04e63db9c 100644 --- a/ui/helpers/utils/token-util.js +++ b/ui/helpers/utils/token-util.js @@ -6,7 +6,7 @@ import { import { getTokenStandardAndDetails } from '../../store/actions'; import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils'; import { parseStandardTokenTransactionData } from '../../../shared/modules/transaction.utils'; -import { ERC20 } from '../../../shared/constants/transaction'; +import { TokenStandard } from '../../../shared/constants/transaction'; import { getTokenValueParam } from '../../../shared/lib/metamask-controller-utils'; import { calcTokenAmount } from '../../../shared/lib/transactions-controller-utils'; import * as util from './util'; @@ -278,7 +278,7 @@ export async function getAssetDetails( const decimals = tokenDetails?.decimals && Number(tokenDetails.decimals?.toString(10)); - if (tokenDetails?.standard === ERC20) { + if (tokenDetails?.standard === TokenStandard.ERC20) { tokenId = undefined; } diff --git a/ui/helpers/utils/transactions.util.js b/ui/helpers/utils/transactions.util.js index b7c6a9def..80b7ced4f 100644 --- a/ui/helpers/utils/transactions.util.js +++ b/ui/helpers/utils/transactions.util.js @@ -3,10 +3,10 @@ import log from 'loglevel'; import { addHexPrefix } from '../../../app/scripts/lib/util'; import { - TRANSACTION_TYPES, - TRANSACTION_GROUP_STATUSES, - TRANSACTION_STATUSES, - TRANSACTION_ENVELOPE_TYPES, + TransactionType, + TransactionGroupStatus, + TransactionStatus, + TransactionEnvelopeType, } from '../../../shared/constants/transaction'; import { addCurrencies } from '../../../shared/modules/conversion.utils'; import { readAddressAsContract } from '../../../shared/modules/contract-utils'; @@ -98,11 +98,11 @@ export function getFourBytePrefix(data = '') { */ export function isTokenMethodAction(type) { return [ - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, - TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, - TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL, - TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, - TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM, + TransactionType.tokenMethodTransfer, + TransactionType.tokenMethodApprove, + TransactionType.tokenMethodSetApprovalForAll, + TransactionType.tokenMethodTransferFrom, + TransactionType.tokenMethodSafeTransferFrom, ].includes(type); } @@ -148,7 +148,7 @@ export function sumHexes(...args) { } export function isLegacyTransaction(txParams) { - return txParams?.type === TRANSACTION_ENVELOPE_TYPES.LEGACY; + return txParams?.type === TransactionEnvelopeType.legacy; } /** @@ -168,14 +168,14 @@ export function getStatusKey(transaction) { // There was an on-chain failure if (receiptStatus === '0x0') { - return TRANSACTION_STATUSES.FAILED; + return TransactionStatus.failed; } if ( - status === TRANSACTION_STATUSES.CONFIRMED && - type === TRANSACTION_TYPES.CANCEL + status === TransactionStatus.confirmed && + type === TransactionType.cancel ) { - return TRANSACTION_GROUP_STATUSES.CANCELLED; + return TransactionGroupStatus.cancelled; } return transaction.status; @@ -193,34 +193,34 @@ export function getStatusKey(transaction) { */ export function getTransactionTypeTitle(t, type, nativeCurrency = 'ETH') { switch (type) { - case TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER: { + case TransactionType.tokenMethodTransfer: { return t('transfer'); } - case TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM: { + case TransactionType.tokenMethodTransferFrom: { return t('transferFrom'); } - case TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM: { + case TransactionType.tokenMethodSafeTransferFrom: { return t('safeTransferFrom'); } - case TRANSACTION_TYPES.TOKEN_METHOD_APPROVE: { + case TransactionType.tokenMethodApprove: { return t('approve'); } - case TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL: { + case TransactionType.tokenMethodSetApprovalForAll: { return t('setApprovalForAll'); } - case TRANSACTION_TYPES.SIMPLE_SEND: { + case TransactionType.simpleSend: { return t('sendingNativeAsset', [nativeCurrency]); } - case TRANSACTION_TYPES.CONTRACT_INTERACTION: { + case TransactionType.contractInteraction: { return t('contractInteraction'); } - case TRANSACTION_TYPES.DEPLOY_CONTRACT: { + case TransactionType.deployContract: { return t('contractDeployment'); } - case TRANSACTION_TYPES.SWAP: { + case TransactionType.swap: { return t('swap'); } - case TRANSACTION_TYPES.SWAP_APPROVAL: { + case TransactionType.swapApproval: { return t('swapApproval'); } default: { diff --git a/ui/helpers/utils/transactions.util.test.js b/ui/helpers/utils/transactions.util.test.js index 16a1ba16c..cdf2b9810 100644 --- a/ui/helpers/utils/transactions.util.test.js +++ b/ui/helpers/utils/transactions.util.test.js @@ -1,9 +1,9 @@ import { HttpProvider } from 'ethjs'; import nock from 'nock'; import { - TRANSACTION_GROUP_STATUSES, - TRANSACTION_STATUSES, - TRANSACTION_ENVELOPE_TYPES, + TransactionGroupStatus, + TransactionStatus, + TransactionEnvelopeType, } from '../../../shared/constants/transaction'; import * as utils from './transactions.util'; @@ -13,27 +13,27 @@ describe('Transactions utils', () => { const tests = [ { transaction: { - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txReceipt: { status: '0x0', }, }, - expected: TRANSACTION_STATUSES.FAILED, + expected: TransactionStatus.failed, }, { transaction: { - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, txReceipt: { status: '0x1', }, }, - expected: TRANSACTION_STATUSES.CONFIRMED, + expected: TransactionStatus.confirmed, }, { transaction: { - status: TRANSACTION_GROUP_STATUSES.PENDING, + status: TransactionGroupStatus.pending, }, - expected: TRANSACTION_GROUP_STATUSES.PENDING, + expected: TransactionGroupStatus.pending, }, ]; @@ -46,13 +46,13 @@ describe('Transactions utils', () => { describe('isLegacyTransaction', () => { it('should return true if transaction is type-0', () => { expect( - utils.isLegacyTransaction({ type: TRANSACTION_ENVELOPE_TYPES.LEGACY }), + utils.isLegacyTransaction({ type: TransactionEnvelopeType.legacy }), ).toStrictEqual(true); }); it('should return false if transaction is not type-0', () => { expect( utils.isLegacyTransaction({ - type: TRANSACTION_ENVELOPE_TYPES.FEE_MARKET, + type: TransactionEnvelopeType.feeMarket, }), ).toStrictEqual(false); }); diff --git a/ui/hooks/gasFeeInput/useGasFeeInputs.test.js b/ui/hooks/gasFeeInput/useGasFeeInputs.test.js index ad8300d75..4779a5cb7 100644 --- a/ui/hooks/gasFeeInput/useGasFeeInputs.test.js +++ b/ui/hooks/gasFeeInput/useGasFeeInputs.test.js @@ -1,6 +1,6 @@ import { act, renderHook } from '@testing-library/react-hooks'; import { useSelector } from 'react-redux'; -import { TRANSACTION_ENVELOPE_TYPES } from '../../../shared/constants/transaction'; +import { TransactionEnvelopeType } from '../../../shared/constants/transaction'; import { GAS_RECOMMENDATIONS, EDIT_GAS_MODES, @@ -99,7 +99,7 @@ describe('useGasFeeInputs', () => { value: '3782DACE9D90000', gasLimit: '0x5028', gasPrice: '0x5028', - type: TRANSACTION_ENVELOPE_TYPES.LEGACY, + type: TransactionEnvelopeType.legacy, }, }), ); diff --git a/ui/hooks/useAssetDetails.test.js b/ui/hooks/useAssetDetails.test.js index 3fc591303..6060c2dc2 100644 --- a/ui/hooks/useAssetDetails.test.js +++ b/ui/hooks/useAssetDetails.test.js @@ -4,7 +4,7 @@ import { renderHook } from '@testing-library/react-hooks'; import configureStore from '../store/store'; import * as Actions from '../store/actions'; -import { ERC1155, ERC20, ERC721 } from '../../shared/constants/transaction'; +import { TokenStandard } from '../../shared/constants/transaction'; import { useAssetDetails } from './useAssetDetails'; const renderUseAssetDetails = ({ @@ -70,7 +70,7 @@ describe('useAssetDetails', () => { const toAddress = '000000000000000000000000000000000000dead'; const transactionData = `0xa9059cbb000000000000000000000000${toAddress}00000000000000000000000000000000000000000000000000000000000001f4`; - const standard = ERC20; + const standard = TokenStandard.ERC20; const symbol = 'WETH'; const balance = '1'; const decimals = 18; @@ -118,7 +118,7 @@ describe('useAssetDetails', () => { const name = 'BoredApeYachtClub'; const image = 'https://bafybeihw3gvmthmvrenfmcvagtais5tv7r4nmiezgsv7nyknjubxw4lite.ipfs.dweb.link'; - const standard = ERC721; + const standard = TokenStandard.ERC721; getTokenStandardAndDetailsStub.mockImplementation(() => Promise.resolve({ @@ -162,7 +162,7 @@ describe('useAssetDetails', () => { const image = 'https://bafybeihw3gvmthmvrenfmcvagtais5tv7r4nmiezgsv7nyknjubxw4lite.ipfs.dweb.link'; - const standard = ERC1155; + const standard = TokenStandard.ERC1155; getTokenStandardAndDetailsStub.mockImplementation(() => Promise.resolve({ diff --git a/ui/hooks/useSwappedTokenValue.js b/ui/hooks/useSwappedTokenValue.js index c5d50817e..5a5d3bc92 100644 --- a/ui/hooks/useSwappedTokenValue.js +++ b/ui/hooks/useSwappedTokenValue.js @@ -1,6 +1,6 @@ import { useSelector } from 'react-redux'; import { getSwapsTokensReceivedFromTxMeta } from '../../shared/lib/transactions-controller-utils'; -import { TRANSACTION_TYPES } from '../../shared/constants/transaction'; +import { TransactionType } from '../../shared/constants/transaction'; import { isSwapsDefaultTokenAddress, isSwapsDefaultTokenSymbol, @@ -45,7 +45,7 @@ export function useSwappedTokenValue(transactionGroup, currentAsset) { )); const swapTokenValue = - type === TRANSACTION_TYPES.SWAP && isViewingReceivedTokenFromSwap + type === TransactionType.swap && isViewingReceivedTokenFromSwap ? getSwapsTokensReceivedFromTxMeta( primaryTransaction.destinationTokenSymbol, initialTransaction, @@ -55,7 +55,7 @@ export function useSwappedTokenValue(transactionGroup, currentAsset) { null, chainId, ) - : type === TRANSACTION_TYPES.SWAP && primaryTransaction.swapTokenValue; + : type === TransactionType.swap && primaryTransaction.swapTokenValue; const isNegative = typeof swapTokenValue === 'string' diff --git a/ui/hooks/useTokenData.test.js b/ui/hooks/useTokenData.test.js index 3be40dc0c..0f6a0cae4 100644 --- a/ui/hooks/useTokenData.test.js +++ b/ui/hooks/useTokenData.test.js @@ -1,14 +1,14 @@ /* eslint-disable jest/no-conditional-expect */ import { BigNumber } from '@ethersproject/bignumber'; import { renderHook } from '@testing-library/react-hooks'; -import { TRANSACTION_TYPES } from '../../shared/constants/transaction'; +import { TransactionType } from '../../shared/constants/transaction'; import { useTokenData } from './useTokenData'; const tests = [ { data: '0xa9059cbb000000000000000000000000ffe5bc4e8f1f969934d773fa67da095d2e491a970000000000000000000000000000000000000000000000000000000000003a98', tokenData: { - name: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + name: TransactionType.tokenMethodTransfer, args: [ '0xffe5bc4e8f1f969934d773fa67da095d2e491a97', BigNumber.from(15000), @@ -18,7 +18,7 @@ const tests = [ { data: '0xa9059cbb000000000000000000000000ffe5bc4e8f1f969934d773fa67da095d2e491a9700000000000000000000000000000000000000000000000000000000000061a8', tokenData: { - name: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + name: TransactionType.tokenMethodTransfer, args: [ '0xffe5bc4e8f1f969934d773fa67da095d2e491a97', BigNumber.from(25000), @@ -28,7 +28,7 @@ const tests = [ { data: '0xa9059cbb000000000000000000000000ffe5bc4e8f1f969934d773fa67da095d2e491a970000000000000000000000000000000000000000000000000000000000002710', tokenData: { - name: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + name: TransactionType.tokenMethodTransfer, args: [ '0xffe5bc4e8f1f969934d773fa67da095d2e491a97', BigNumber.from(10000), diff --git a/ui/hooks/useTransactionDisplayData.js b/ui/hooks/useTransactionDisplayData.js index c9e269e91..24f65dd73 100644 --- a/ui/hooks/useTransactionDisplayData.js +++ b/ui/hooks/useTransactionDisplayData.js @@ -22,9 +22,9 @@ import { } from '../helpers/constants/transactions'; import { getCollectibles, getTokens } from '../ducks/metamask/metamask'; import { - TRANSACTION_TYPES, - TRANSACTION_GROUP_CATEGORIES, - TRANSACTION_STATUSES, + TransactionType, + TransactionGroupCategory, + TransactionStatus, } from '../../shared/constants/transaction'; import { captureSingleException } from '../store/actions'; import { isEqualCaseInsensitive } from '../../shared/modules/string-utils'; @@ -51,11 +51,11 @@ import { useCurrentAsset } from './useCurrentAsset'; const signatureTypes = [ null, undefined, - TRANSACTION_TYPES.SIGN, - TRANSACTION_TYPES.PERSONAL_SIGN, - TRANSACTION_TYPES.SIGN_TYPED_DATA, - TRANSACTION_TYPES.ETH_DECRYPT, - TRANSACTION_TYPES.ETH_GET_ENCRYPTION_PUBLIC_KEY, + TransactionType.sign, + TransactionType.personalSign, + TransactionType.signTypedData, + TransactionType.ethDecrypt, + TransactionType.ethGetEncryptionPublicKey, ]; /** @@ -108,7 +108,7 @@ export function useTransactionDisplayData(transactionGroup) { const displayedStatusKey = getStatusKey(primaryTransaction); const isPending = displayedStatusKey in PENDING_STATUS_HASH; - const isSubmitted = displayedStatusKey === TRANSACTION_STATUSES.SUBMITTED; + const isSubmitted = displayedStatusKey === TransactionStatus.submitted; const primaryValue = primaryTransaction.txParams?.value; const date = formatDateWithYearContext(initialTransaction.time); @@ -189,12 +189,12 @@ export function useTransactionDisplayData(transactionGroup) { } = useSwappedTokenValue(transactionGroup, currentAsset); if (signatureTypes.includes(type)) { - category = TRANSACTION_GROUP_CATEGORIES.SIGNATURE_REQUEST; + category = TransactionGroupCategory.signatureRequest; title = t('signatureRequest'); subtitle = origin; subtitleContainsOrigin = true; - } else if (type === TRANSACTION_TYPES.SWAP) { - category = TRANSACTION_GROUP_CATEGORIES.SWAP; + } else if (type === TransactionType.swap) { + category = TransactionGroupCategory.swap; title = t('swapTokenToToken', [ initialTransaction.sourceTokenSymbol, initialTransaction.destinationTokenSymbol, @@ -213,60 +213,60 @@ export function useTransactionDisplayData(transactionGroup) { } else { prefix = '-'; } - } else if (type === TRANSACTION_TYPES.SWAP_APPROVAL) { - category = TRANSACTION_GROUP_CATEGORIES.APPROVAL; + } else if (type === TransactionType.swapApproval) { + category = TransactionGroupCategory.approval; title = t('swapApproval', [primaryTransaction.sourceTokenSymbol]); subtitle = origin; subtitleContainsOrigin = true; primarySuffix = primaryTransaction.sourceTokenSymbol; - } else if (type === TRANSACTION_TYPES.TOKEN_METHOD_APPROVE) { - category = TRANSACTION_GROUP_CATEGORIES.APPROVAL; + } else if (type === TransactionType.tokenMethodApprove) { + category = TransactionGroupCategory.approval; prefix = ''; title = t('approveSpendLimit', [token?.symbol || t('token')]); subtitle = origin; subtitleContainsOrigin = true; - } else if (type === TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL) { - category = TRANSACTION_GROUP_CATEGORIES.APPROVAL; + } else if (type === TransactionType.tokenMethodSetApprovalForAll) { + category = TransactionGroupCategory.approval; prefix = ''; title = t('setApprovalForAllTitle', [token?.symbol || t('token')]); subtitle = origin; subtitleContainsOrigin = true; - } else if (type === TRANSACTION_TYPES.CONTRACT_INTERACTION) { - category = TRANSACTION_GROUP_CATEGORIES.INTERACTION; + } else if (type === TransactionType.contractInteraction) { + category = TransactionGroupCategory.interaction; const transactionTypeTitle = getTransactionTypeTitle(t, type); title = (methodData?.name && camelCaseToCapitalize(methodData.name)) || transactionTypeTitle; subtitle = origin; subtitleContainsOrigin = true; - } else if (type === TRANSACTION_TYPES.DEPLOY_CONTRACT) { + } else if (type === TransactionType.deployContract) { // @todo Should perhaps be a separate group? - category = TRANSACTION_GROUP_CATEGORIES.INTERACTION; + category = TransactionGroupCategory.interaction; title = getTransactionTypeTitle(t, type); subtitle = origin; subtitleContainsOrigin = true; - } else if (type === TRANSACTION_TYPES.INCOMING) { - category = TRANSACTION_GROUP_CATEGORIES.RECEIVE; + } else if (type === TransactionType.incoming) { + category = TransactionGroupCategory.receive; title = t('receive'); prefix = ''; subtitle = t('fromAddress', [shortenAddress(senderAddress)]); } else if ( - type === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM || - type === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER + type === TransactionType.tokenMethodTransferFrom || + type === TransactionType.tokenMethodTransfer ) { - category = TRANSACTION_GROUP_CATEGORIES.SEND; + category = TransactionGroupCategory.send; title = t('sendSpecifiedTokens', [ token?.symbol || collectible?.name || t('token'), ]); recipientAddress = getTokenAddressParam(tokenData); subtitle = t('toAddress', [shortenAddress(recipientAddress)]); - } else if (type === TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM) { - category = TRANSACTION_GROUP_CATEGORIES.SEND; + } else if (type === TransactionType.tokenMethodSafeTransferFrom) { + category = TransactionGroupCategory.send; title = t('safeTransferFrom'); recipientAddress = getTokenAddressParam(tokenData); subtitle = t('toAddress', [shortenAddress(recipientAddress)]); - } else if (type === TRANSACTION_TYPES.SIMPLE_SEND) { - category = TRANSACTION_GROUP_CATEGORIES.SEND; + } else if (type === TransactionType.simpleSend) { + category = TransactionGroupCategory.send; title = t('send'); subtitle = t('toAddress', [shortenAddress(recipientAddress)]); } else { @@ -301,12 +301,12 @@ export function useTransactionDisplayData(transactionGroup) { subtitle, subtitleContainsOrigin, primaryCurrency: - type === TRANSACTION_TYPES.SWAP && isPending ? '' : primaryCurrency, + type === TransactionType.swap && isPending ? '' : primaryCurrency, senderAddress, recipientAddress, secondaryCurrency: (isTokenCategory && !tokenFiatAmount) || - (type === TRANSACTION_TYPES.SWAP && !swapTokenFiatAmount) + (type === TransactionType.swap && !swapTokenFiatAmount) ? undefined : secondaryCurrency, displayedStatusKey, diff --git a/ui/hooks/useTransactionDisplayData.test.js b/ui/hooks/useTransactionDisplayData.test.js index 8eb224e1b..970ee1b4e 100644 --- a/ui/hooks/useTransactionDisplayData.test.js +++ b/ui/hooks/useTransactionDisplayData.test.js @@ -16,9 +16,9 @@ import messages from '../../app/_locales/en/messages.json'; import { ASSET_ROUTE, DEFAULT_ROUTE } from '../helpers/constants/routes'; import { CHAIN_IDS } from '../../shared/constants/network'; import { - TRANSACTION_TYPES, - TRANSACTION_GROUP_CATEGORIES, - TRANSACTION_STATUSES, + TransactionType, + TransactionGroupCategory, + TransactionStatus, } from '../../shared/constants/transaction'; import * as i18nhooks from './useI18nContext'; import * as useTokenFiatAmountHooks from './useTokenFiatAmount'; @@ -27,7 +27,7 @@ import { useTransactionDisplayData } from './useTransactionDisplayData'; const expectedResults = [ { title: 'Send', - category: TRANSACTION_GROUP_CATEGORIES.SEND, + category: TransactionGroupCategory.send, subtitle: 'To: 0xffe...1a97', subtitleContainsOrigin: false, date: 'May 12, 2020', @@ -36,12 +36,12 @@ const expectedResults = [ recipientAddress: '0xffe5bc4e8f1f969934d773fa67da095d2e491a97', secondaryCurrency: '-1 ETH', isPending: false, - displayedStatusKey: TRANSACTION_STATUSES.CONFIRMED, + displayedStatusKey: TransactionStatus.confirmed, isSubmitted: false, }, { title: 'Send', - category: TRANSACTION_GROUP_CATEGORIES.SEND, + category: TransactionGroupCategory.send, subtitle: 'To: 0x0cc...8848', subtitleContainsOrigin: false, date: 'May 12, 2020', @@ -50,11 +50,11 @@ const expectedResults = [ recipientAddress: '0x0ccc8aeeaf5ce790f3b448325981a143fdef8848', secondaryCurrency: '-2 ETH', isPending: false, - displayedStatusKey: TRANSACTION_STATUSES.CONFIRMED, + displayedStatusKey: TransactionStatus.confirmed, }, { title: 'Send', - category: TRANSACTION_GROUP_CATEGORIES.SEND, + category: TransactionGroupCategory.send, subtitle: 'To: 0xffe...1a97', subtitleContainsOrigin: false, date: 'May 12, 2020', @@ -63,11 +63,11 @@ const expectedResults = [ recipientAddress: '0xffe5bc4e8f1f969934d773fa67da095d2e491a97', secondaryCurrency: '-2 ETH', isPending: false, - displayedStatusKey: TRANSACTION_STATUSES.CONFIRMED, + displayedStatusKey: TransactionStatus.confirmed, }, { title: 'Receive', - category: TRANSACTION_GROUP_CATEGORIES.RECEIVE, + category: TransactionGroupCategory.receive, subtitle: 'From: 0x31b...4523', subtitleContainsOrigin: false, date: 'May 12, 2020', @@ -76,11 +76,11 @@ const expectedResults = [ recipientAddress: '0x9eca64466f257793eaa52fcfff5066894b76a149', secondaryCurrency: '18.75 ETH', isPending: false, - displayedStatusKey: TRANSACTION_STATUSES.CONFIRMED, + displayedStatusKey: TransactionStatus.confirmed, }, { title: 'Receive', - category: TRANSACTION_GROUP_CATEGORIES.RECEIVE, + category: TransactionGroupCategory.receive, subtitle: 'From: 0x9ec...a149', subtitleContainsOrigin: false, date: 'May 8, 2020', @@ -89,11 +89,11 @@ const expectedResults = [ recipientAddress: '0x9eca64466f257793eaa52fcfff5066894b76a149', secondaryCurrency: '0 ETH', isPending: false, - displayedStatusKey: TRANSACTION_STATUSES.CONFIRMED, + displayedStatusKey: TransactionStatus.confirmed, }, { title: 'Receive', - category: TRANSACTION_GROUP_CATEGORIES.RECEIVE, + category: TransactionGroupCategory.receive, subtitle: 'From: 0xee0...febb', subtitleContainsOrigin: false, date: 'May 24, 2020', @@ -102,11 +102,11 @@ const expectedResults = [ recipientAddress: '0x9eca64466f257793eaa52fcfff5066894b76a149', secondaryCurrency: '1 ETH', isPending: false, - displayedStatusKey: TRANSACTION_STATUSES.CONFIRMED, + displayedStatusKey: TransactionStatus.confirmed, }, { title: 'Swap ETH to ABC', - category: TRANSACTION_TYPES.SWAP, + category: TransactionType.swap, subtitle: '', subtitleContainsOrigin: false, date: 'May 12, 2020', @@ -115,11 +115,11 @@ const expectedResults = [ recipientAddress: '0xabca64466f257793eaa52fcfff5066894b76a149', secondaryCurrency: undefined, isPending: false, - displayedStatusKey: TRANSACTION_STATUSES.CONFIRMED, + displayedStatusKey: TransactionStatus.confirmed, }, { title: 'Contract deployment', - category: TRANSACTION_GROUP_CATEGORIES.INTERACTION, + category: TransactionGroupCategory.interaction, subtitle: 'metamask.github.io', subtitleContainsOrigin: true, date: 'May 12, 2020', @@ -128,11 +128,11 @@ const expectedResults = [ recipientAddress: undefined, secondaryCurrency: '-0 ETH', isPending: false, - displayedStatusKey: TRANSACTION_STATUSES.CONFIRMED, + displayedStatusKey: TransactionStatus.confirmed, }, { title: 'Safe transfer from', - category: TRANSACTION_GROUP_CATEGORIES.SEND, + category: TransactionGroupCategory.send, subtitle: 'To: 0xe7d...dd98', subtitleContainsOrigin: true, primaryCurrency: '-0 ETH', @@ -140,7 +140,7 @@ const expectedResults = [ recipientAddress: '0xe7d522230eff653bb0a9b4385f0be0815420dd98', secondaryCurrency: '-0 ETH', isPending: false, - displayedStatusKey: TRANSACTION_STATUSES.CONFIRMED, + displayedStatusKey: TransactionStatus.confirmed, }, ]; diff --git a/ui/hooks/useTransactionEventFragment.js b/ui/hooks/useTransactionEventFragment.js index 992d7625b..1a10a7157 100644 --- a/ui/hooks/useTransactionEventFragment.js +++ b/ui/hooks/useTransactionEventFragment.js @@ -7,7 +7,7 @@ import { updateEventFragment, } from '../store/actions'; import { selectMatchingFragment } from '../selectors'; -import { TRANSACTION_EVENTS } from '../../shared/constants/transaction'; +import { TransactionMetaMetricsEvent } from '../../shared/constants/transaction'; export const useTransactionEventFragment = () => { const { transaction } = useGasFeeContext(); @@ -26,7 +26,7 @@ export const useTransactionEventFragment = () => { if (!fragment) { await createTransactionEventFragment( transaction.id, - TRANSACTION_EVENTS.APPROVED, + TransactionMetaMetricsEvent.approved, ); } updateEventFragment(`transaction-added-${transaction.id}`, params); diff --git a/ui/pages/add-collectible/add-collectible.js b/ui/pages/add-collectible/add-collectible.js index 30aefa6dc..33353f900 100644 --- a/ui/pages/add-collectible/add-collectible.js +++ b/ui/pages/add-collectible/add-collectible.js @@ -25,7 +25,7 @@ import { getIsMainnet, getUseNftDetection } from '../../selectors'; import { getCollectiblesDetectionNoticeDismissed } from '../../ducks/metamask/metamask'; import CollectiblesDetectionNotice from '../../components/app/collectibles-detection-notice'; import { MetaMetricsContext } from '../../contexts/metametrics'; -import { ASSET_TYPES } from '../../../shared/constants/transaction'; +import { AssetType } from '../../../shared/constants/transaction'; import { EVENT, EVENT_NAMES } from '../../../shared/constants/metametrics'; export default function AddCollectible() { @@ -84,7 +84,7 @@ export default function AddCollectible() { token_contract_address: address, token_symbol: tokenDetails?.symbol, tokenId: tokenId.toString(), - asset_type: ASSET_TYPES.NFT, + asset_type: AssetType.NFT, token_standard: tokenDetails?.standard, source: EVENT.SOURCE.TOKEN.CUSTOM, }, diff --git a/ui/pages/confirm-add-suggested-token/confirm-add-suggested-token.js b/ui/pages/confirm-add-suggested-token/confirm-add-suggested-token.js index 26363fdd9..935168921 100644 --- a/ui/pages/confirm-add-suggested-token/confirm-add-suggested-token.js +++ b/ui/pages/confirm-add-suggested-token/confirm-add-suggested-token.js @@ -15,8 +15,8 @@ import { getSuggestedAssets } from '../../selectors'; import { rejectWatchAsset, acceptWatchAsset } from '../../store/actions'; import { EVENT, EVENT_NAMES } from '../../../shared/constants/metametrics'; import { - ASSET_TYPES, - TOKEN_STANDARDS, + AssetType, + TokenStandard, } from '../../../shared/constants/transaction'; function getTokenName(name, symbol) { @@ -125,8 +125,8 @@ const ConfirmAddSuggestedToken = () => { token_decimal_precision: asset.decimals, unlisted: asset.unlisted, source: EVENT.SOURCE.TOKEN.DAPP, - token_standard: TOKEN_STANDARDS.ERC20, - asset_type: ASSET_TYPES.TOKEN, + token_standard: TokenStandard.ERC20, + asset_type: AssetType.token, }, }); }), diff --git a/ui/pages/confirm-approve/confirm-approve-content/confirm-approve-content.component.js b/ui/pages/confirm-approve/confirm-approve-content/confirm-approve-content.component.js index 1d43a3169..2323b9846 100644 --- a/ui/pages/confirm-approve/confirm-approve-content/confirm-approve-content.component.js +++ b/ui/pages/confirm-approve/confirm-approve-content/confirm-approve-content.component.js @@ -26,11 +26,7 @@ import { SECOND } from '../../../../shared/constants/time'; import { ConfirmPageContainerWarning } from '../../../components/app/confirm-page-container/confirm-page-container-content'; import GasDetailsItem from '../../../components/app/gas-details-item'; import LedgerInstructionField from '../../../components/app/ledger-instruction-field'; -import { - ERC1155, - ERC20, - ERC721, -} from '../../../../shared/constants/transaction'; +import { TokenStandard } from '../../../../shared/constants/transaction'; import { CHAIN_IDS, TEST_CHAINS } from '../../../../shared/constants/network'; import ContractDetailsModal from '../../../components/app/modals/contract-details-modal/contract-details-modal'; @@ -342,7 +338,7 @@ export default class ConfirmApproveContent extends Component { tokenSymbol, tokenBalance, } = this.props; - if (assetStandard === ERC20) { + if (assetStandard === TokenStandard.ERC20) { return (
@@ -373,7 +369,10 @@ export default class ConfirmApproveContent extends Component {
); - } else if (assetStandard === ERC721 || assetStandard === ERC1155) { + } else if ( + assetStandard === TokenStandard.ERC721 || + assetStandard === TokenStandard.ERC1155 + ) { return (
@@ -462,13 +461,13 @@ export default class ConfirmApproveContent extends Component { let titleTokenDescription = t('token'); if ( - assetStandard === ERC20 || + assetStandard === TokenStandard.ERC20 || (tokenSymbol && !tokenId && !isSetApproveForAll) ) { titleTokenDescription = tokenSymbol; } else if ( - assetStandard === ERC721 || - assetStandard === ERC1155 || + assetStandard === TokenStandard.ERC721 || + assetStandard === TokenStandard.ERC1155 || // if we don't have an asset standard but we do have either both an assetname and a tokenID or both a tokenSymbol and tokenId we assume its an NFT (assetName && tokenId) || (tokenSymbol && tokenId) @@ -556,8 +555,8 @@ export default class ConfirmApproveContent extends Component { title = t('revokeAllTokensTitle', [titleTokenDescription]); } } else if ( - assetStandard === ERC721 || - assetStandard === ERC1155 || + assetStandard === TokenStandard.ERC721 || + assetStandard === TokenStandard.ERC1155 || // if we don't have an asset standard but we do have either both an assetname and a tokenID or both a tokenSymbol and tokenId we assume its an NFT (assetName && tokenId) || (tokenSymbol && tokenId) @@ -591,8 +590,8 @@ export default class ConfirmApproveContent extends Component { ]); } else if ( isSetApproveForAll || - assetStandard === ERC721 || - assetStandard === ERC1155 || + assetStandard === TokenStandard.ERC721 || + assetStandard === TokenStandard.ERC1155 || // if we don't have an asset standard but we do have either both an assetname and a tokenID or both a tokenSymbol and tokenId we assume its an NFT (assetName && tokenId) || (tokenSymbol && tokenId) @@ -673,7 +672,7 @@ export default class ConfirmApproveContent extends Component {
{this.renderDescription()}
- {assetStandard === ERC20 || + {assetStandard === TokenStandard.ERC20 || (tokenSymbol && !tokenId && !isSetApproveForAll) ? ( @@ -771,7 +770,7 @@ export default class ConfirmApproveContent extends Component { )} )} - {assetStandard === ERC20 ? ( + {assetStandard === TokenStandard.ERC20 ? (
{ @@ -19,7 +19,7 @@ const props = { tokenAmount: '10', origin: 'https://metamask.github.io/test-dapp/', tokenSymbol: 'TST', - assetStandard: ERC20, + assetStandard: TokenStandard.ERC20, tokenImage: 'https://metamask.github.io/test-dapp/metamask-fox.svg', tokenBalance: '15', showCustomizeGasModal: jest.fn(), diff --git a/ui/pages/confirm-approve/confirm-approve-content/confirm-approve-content.stories.js b/ui/pages/confirm-approve/confirm-approve-content/confirm-approve-content.stories.js index edbff288d..b472e0121 100644 --- a/ui/pages/confirm-approve/confirm-approve-content/confirm-approve-content.stories.js +++ b/ui/pages/confirm-approve/confirm-approve-content/confirm-approve-content.stories.js @@ -1,5 +1,5 @@ import React from 'react'; -import { ERC20 } from '../../../../shared/constants/transaction'; +import { TokenStandard } from '../../../../shared/constants/transaction'; import ConfirmApproveContent from '.'; export default { @@ -117,7 +117,7 @@ export default { tokenAmount: '10', origin: 'https://metamask.github.io/test-dapp/', tokenSymbol: 'TST', - assetStandard: ERC20, + assetStandard: TokenStandard.ERC20, tokenImage: 'https://metamask.github.io/test-dapp/metamask-fox.svg', tokenBalance: '15', data: '0x095ea7b30000000000000000000000009bc5baf874d2da8d216ae9f137804184ee5afef40000000000000000000000000000000000000000000000000000000000011170', diff --git a/ui/pages/confirm-approve/confirm-approve.js b/ui/pages/confirm-approve/confirm-approve.js index 4fa2fe8fe..14158d2fe 100644 --- a/ui/pages/confirm-approve/confirm-approve.js +++ b/ui/pages/confirm-approve/confirm-approve.js @@ -35,7 +35,7 @@ import EditGasFeePopover from '../../components/app/edit-gas-fee-popover'; import EditGasPopover from '../../components/app/edit-gas-popover/edit-gas-popover.component'; import Loading from '../../components/ui/loading-screen'; import { parseStandardTokenTransactionData } from '../../../shared/modules/transaction.utils'; -import { ERC1155, ERC20, ERC721 } from '../../../shared/constants/transaction'; +import { TokenStandard } from '../../../shared/constants/transaction'; import { calcTokenAmount } from '../../../shared/lib/transactions-controller-utils'; import TokenAllowance from '../token-allowance/token-allowance'; import { getCustomTxParamsData } from './confirm-approve.util'; @@ -142,9 +142,12 @@ export default function ConfirmApprove({ const { iconUrl: siteImage = '' } = subjectMetadata[origin] || {}; let tokensText; - if (assetStandard === ERC20) { + if (assetStandard === TokenStandard.ERC20) { tokensText = `${Number(tokenAmount)} ${tokenSymbol}`; - } else if (assetStandard === ERC721 || assetStandard === ERC1155) { + } else if ( + assetStandard === TokenStandard.ERC721 || + assetStandard === TokenStandard.ERC1155 + ) { tokensText = assetName; } @@ -168,7 +171,7 @@ export default function ConfirmApprove({ if (assetStandard === undefined) { return ; } - if (improvedTokenAllowanceEnabled && assetStandard === ERC20) { + if (improvedTokenAllowanceEnabled && assetStandard === TokenStandard.ERC20) { return ( diff --git a/ui/pages/confirm-approve/confirm-approve.util.js b/ui/pages/confirm-approve/confirm-approve.util.js index e54ea573d..48fc367ba 100644 --- a/ui/pages/confirm-approve/confirm-approve.util.js +++ b/ui/pages/confirm-approve/confirm-approve.util.js @@ -1,6 +1,6 @@ import { calcTokenValue } from '../../../shared/lib/swaps-utils'; import { decimalToHex } from '../../../shared/lib/transactions-controller-utils'; -import { TRANSACTION_TYPES } from '../../../shared/constants/transaction'; +import { TransactionType } from '../../../shared/constants/transaction'; import { parseStandardTokenTransactionData } from '../../../shared/modules/transaction.utils'; import { getTokenAddressParam } from '../../helpers/utils/token-util'; @@ -12,7 +12,7 @@ export function getCustomTxParamsData( if (!tokenData) { throw new Error('Invalid data'); - } else if (tokenData.name !== TRANSACTION_TYPES.TOKEN_METHOD_APPROVE) { + } else if (tokenData.name !== TransactionType.tokenMethodApprove) { throw new Error( `Invalid data; should be 'approve' method, but instead is '${tokenData.name}'`, ); diff --git a/ui/pages/confirm-contract-interaction/confirm-contract-interaction.js b/ui/pages/confirm-contract-interaction/confirm-contract-interaction.js index 98be8bc3b..55cf9f32b 100644 --- a/ui/pages/confirm-contract-interaction/confirm-contract-interaction.js +++ b/ui/pages/confirm-contract-interaction/confirm-contract-interaction.js @@ -7,7 +7,7 @@ import { SEND_ROUTE } from '../../helpers/constants/routes'; import { editExistingTransaction } from '../../ducks/send'; import { clearConfirmTransaction } from '../../ducks/confirm-transaction/confirm-transaction.duck'; -import { ASSET_TYPES } from '../../../shared/constants/transaction'; +import { AssetType } from '../../../shared/constants/transaction'; export default function ConfirmContractInteraction() { const dispatch = useDispatch(); @@ -15,7 +15,7 @@ export default function ConfirmContractInteraction() { const handleEditTransaction = async ({ txData }) => { const { id } = txData; - await dispatch(editExistingTransaction(ASSET_TYPES.NATIVE, id.toString())); + await dispatch(editExistingTransaction(AssetType.native, id.toString())); dispatch(clearConfirmTransaction()); }; diff --git a/ui/pages/confirm-import-token/confirm-import-token.js b/ui/pages/confirm-import-token/confirm-import-token.js index dbf32b63b..5a340cbb1 100644 --- a/ui/pages/confirm-import-token/confirm-import-token.js +++ b/ui/pages/confirm-import-token/confirm-import-token.js @@ -15,8 +15,8 @@ import { getPendingTokens } from '../../ducks/metamask/metamask'; import { addTokens, clearPendingTokens } from '../../store/actions'; import { EVENT, EVENT_NAMES } from '../../../shared/constants/metametrics'; import { - ASSET_TYPES, - TOKEN_STANDARDS, + AssetType, + TokenStandard, } from '../../../shared/constants/transaction'; const getTokenName = (name, symbol) => { @@ -50,8 +50,8 @@ const ConfirmImportToken = () => { source: pendingToken.isCustom ? EVENT.SOURCE.TOKEN.CUSTOM : EVENT.SOURCE.TOKEN.LIST, - token_standard: TOKEN_STANDARDS.ERC20, - asset_type: ASSET_TYPES.TOKEN, + token_standard: TokenStandard.ERC20, + asset_type: AssetType.token, }, }); }); diff --git a/ui/pages/confirm-send-ether/confirm-send-ether.container.js b/ui/pages/confirm-send-ether/confirm-send-ether.container.js index 80318ea46..83bd08126 100644 --- a/ui/pages/confirm-send-ether/confirm-send-ether.container.js +++ b/ui/pages/confirm-send-ether/confirm-send-ether.container.js @@ -3,7 +3,7 @@ import { compose } from 'redux'; import { withRouter } from 'react-router-dom'; import { editExistingTransaction } from '../../ducks/send'; import { clearConfirmTransaction } from '../../ducks/confirm-transaction/confirm-transaction.duck'; -import { ASSET_TYPES } from '../../../shared/constants/transaction'; +import { AssetType } from '../../../shared/constants/transaction'; import ConfirmSendEther from './confirm-send-ether.component'; const mapStateToProps = (state) => { @@ -20,9 +20,7 @@ const mapDispatchToProps = (dispatch) => { return { editTransaction: async (txData) => { const { id } = txData; - await dispatch( - editExistingTransaction(ASSET_TYPES.NATIVE, id.toString()), - ); + await dispatch(editExistingTransaction(AssetType.native, id.toString())); dispatch(clearConfirmTransaction()); }, }; diff --git a/ui/pages/confirm-send-token/confirm-send-token.container.js b/ui/pages/confirm-send-token/confirm-send-token.container.js index 62cee9ac3..ad0163c0f 100644 --- a/ui/pages/confirm-send-token/confirm-send-token.container.js +++ b/ui/pages/confirm-send-token/confirm-send-token.container.js @@ -5,7 +5,7 @@ import { clearConfirmTransaction } from '../../ducks/confirm-transaction/confirm import { showSendTokenPage } from '../../store/actions'; import { editExistingTransaction } from '../../ducks/send'; import { sendTokenTokenAmountAndToAddressSelector } from '../../selectors'; -import { ASSET_TYPES } from '../../../shared/constants/transaction'; +import { AssetType } from '../../../shared/constants/transaction'; import ConfirmSendToken from './confirm-send-token.component'; const mapStateToProps = (state) => { @@ -20,7 +20,7 @@ const mapDispatchToProps = (dispatch) => { return { editExistingTransaction: async ({ txData }) => { const { id } = txData; - await dispatch(editExistingTransaction(ASSET_TYPES.TOKEN, id.toString())); + await dispatch(editExistingTransaction(AssetType.token, id.toString())); await dispatch(clearConfirmTransaction()); await dispatch(showSendTokenPage()); }, diff --git a/ui/pages/confirm-send-token/confirm-send-token.js b/ui/pages/confirm-send-token/confirm-send-token.js index 9a8625e34..64f38c350 100644 --- a/ui/pages/confirm-send-token/confirm-send-token.js +++ b/ui/pages/confirm-send-token/confirm-send-token.js @@ -16,9 +16,8 @@ import { import { clearConfirmTransaction } from '../../ducks/confirm-transaction/confirm-transaction.duck'; import { showSendTokenPage } from '../../store/actions'; import { - ASSET_TYPES, - ERC20, - ERC721, + AssetType, + TokenStandard, } from '../../../shared/constants/transaction'; export default function ConfirmSendToken({ @@ -40,7 +39,7 @@ export default function ConfirmSendToken({ const handleEditTransaction = async ({ txData }) => { const { id } = txData; - await dispatch(editExistingTransaction(ASSET_TYPES.TOKEN, id.toString())); + await dispatch(editExistingTransaction(AssetType.token, id.toString())); dispatch(clearConfirmTransaction()); dispatch(showSendTokenPage()); }; @@ -57,10 +56,10 @@ export default function ConfirmSendToken({ let title, subtitle; - if (assetStandard === ERC721) { + if (assetStandard === TokenStandard.ERC721) { title = assetName; subtitle = `#${tokenId}`; - } else if (assetStandard === ERC20) { + } else if (assetStandard === TokenStandard.ERC20) { title = `${tokenAmount} ${tokenSymbol}`; } diff --git a/ui/pages/confirm-token-transaction-base/confirm-token-transaction-base.js b/ui/pages/confirm-token-transaction-base/confirm-token-transaction-base.js index 552635435..6caf0371c 100644 --- a/ui/pages/confirm-token-transaction-base/confirm-token-transaction-base.js +++ b/ui/pages/confirm-token-transaction-base/confirm-token-transaction-base.js @@ -21,7 +21,7 @@ import { getConversionRate, getNativeCurrency, } from '../../ducks/metamask/metamask'; -import { ERC1155, ERC20, ERC721 } from '../../../shared/constants/transaction'; +import { TokenStandard } from '../../../shared/constants/transaction'; import { hexWEIToDecETH } from '../../../shared/lib/transactions-controller-utils'; export default function ConfirmTokenTransactionBase({ @@ -49,10 +49,13 @@ export default function ConfirmTokenTransactionBase({ ); let title, subtitle; - if (assetStandard === ERC721 || assetStandard === ERC1155) { + if ( + assetStandard === TokenStandard.ERC721 || + assetStandard === TokenStandard.ERC1155 + ) { title = assetName; subtitle = `#${tokenId}`; - } else if (assetStandard === ERC20) { + } else if (assetStandard === TokenStandard.ERC20) { title = `${tokenAmount} ${tokenSymbol}`; } diff --git a/ui/pages/confirm-transaction-base/confirm-transaction-base.component.js b/ui/pages/confirm-transaction-base/confirm-transaction-base.component.js index 7f48d808e..8ed361f7b 100644 --- a/ui/pages/confirm-transaction-base/confirm-transaction-base.component.js +++ b/ui/pages/confirm-transaction-base/confirm-transaction-base.component.js @@ -23,8 +23,8 @@ import ActionableMessage from '../../components/ui/actionable-message'; import Disclosure from '../../components/ui/disclosure'; import { EVENT } from '../../../shared/constants/metametrics'; import { - TRANSACTION_TYPES, - TRANSACTION_STATUSES, + TransactionType, + TransactionStatus, } from '../../../shared/constants/transaction'; import { getMethodName } from '../../helpers/utils/metrics'; import { @@ -198,8 +198,8 @@ export default class ConfirmTransactionBase extends Component { } = prevProps; const statusUpdated = transactionStatus !== prevTxStatus; const txDroppedOrConfirmed = - transactionStatus === TRANSACTION_STATUSES.DROPPED || - transactionStatus === TRANSACTION_STATUSES.CONFIRMED; + transactionStatus === TransactionStatus.dropped || + transactionStatus === TransactionStatus.confirmed; if ( nextNonce !== prevNextNonce || @@ -305,7 +305,7 @@ export default class ConfirmTransactionBase extends Component { functionType: actionKey || getMethodName(methodData.name) || - TRANSACTION_TYPES.CONTRACT_INTERACTION, + TransactionType.contractInteraction, origin, }, }); @@ -762,11 +762,11 @@ export default class ConfirmTransactionBase extends Component { ); const allowedTransactionTypes = - txData.type === TRANSACTION_TYPES.CONTRACT_INTERACTION || - txData.type === TRANSACTION_TYPES.SIMPLE_SEND || - txData.type === TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM || - txData.type === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM || - txData.type === TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER; + txData.type === TransactionType.contractInteraction || + txData.type === TransactionType.simpleSend || + txData.type === TransactionType.tokenMethodSafeTransferFrom || + txData.type === TransactionType.tokenMethodTransferFrom || + txData.type === TransactionType.tokenMethodTransfer; const networkId = CHAIN_ID_TO_NETWORK_ID_MAP[chainId]; const caip2ChainId = `eip155:${networkId ?? stripHexPrefix(chainId)}`; @@ -833,7 +833,7 @@ export default class ConfirmTransactionBase extends Component { functionType: actionKey || getMethodName(methodData.name) || - TRANSACTION_TYPES.CONTRACT_INTERACTION, + TransactionType.contractInteraction, origin, }, }); @@ -986,7 +986,7 @@ export default class ConfirmTransactionBase extends Component { } const isContractInteraction = - txData.type === TRANSACTION_TYPES.CONTRACT_INTERACTION; + txData.type === TransactionType.contractInteraction; return ( { const { balance } = accounts[fromAddress]; const { name: fromName } = identities[fromAddress]; let toAddress = txParamsToAddress; - if (type !== TRANSACTION_TYPES.SIMPLE_SEND) { + if (type !== TransactionType.simpleSend) { toAddress = propsToAddress || tokenToAddress || txParamsToAddress; } @@ -170,7 +170,7 @@ const mapStateToProps = (state, ownProps) => { const fullTxData = getFullTxData( state, txId, - TRANSACTION_STATUSES.UNAPPROVED, + TransactionStatus.unapproved, customTxParamsData, ); diff --git a/ui/pages/confirm-transaction-switch/confirm-transaction-switch.component.js b/ui/pages/confirm-transaction-switch/confirm-transaction-switch.component.js index 4c6f964fa..2211ef81a 100644 --- a/ui/pages/confirm-transaction-switch/confirm-transaction-switch.component.js +++ b/ui/pages/confirm-transaction-switch/confirm-transaction-switch.component.js @@ -17,7 +17,7 @@ import { CONFIRM_SET_APPROVAL_FOR_ALL_PATH, } from '../../helpers/constants/routes'; import { MESSAGE_TYPE } from '../../../shared/constants/app'; -import { TRANSACTION_TYPES } from '../../../shared/constants/transaction'; +import { TransactionType } from '../../../shared/constants/transaction'; export default class ConfirmTransactionSwitch extends Component { static propTypes = { @@ -28,35 +28,35 @@ export default class ConfirmTransactionSwitch extends Component { const { txData } = this.props; const { id, txParams: { data } = {}, type } = txData; - if (type === TRANSACTION_TYPES.DEPLOY_CONTRACT) { + if (type === TransactionType.deployContract) { const pathname = `${CONFIRM_TRANSACTION_ROUTE}/${id}${CONFIRM_DEPLOY_CONTRACT_PATH}`; return ; } - if (type === TRANSACTION_TYPES.SIMPLE_SEND) { + if (type === TransactionType.simpleSend) { const pathname = `${CONFIRM_TRANSACTION_ROUTE}/${id}${CONFIRM_SEND_ETHER_PATH}`; return ; } if (data) { switch (type) { - case TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER: { + case TransactionType.tokenMethodTransfer: { const pathname = `${CONFIRM_TRANSACTION_ROUTE}/${id}${CONFIRM_SEND_TOKEN_PATH}`; return ; } - case TRANSACTION_TYPES.TOKEN_METHOD_APPROVE: { + case TransactionType.tokenMethodApprove: { const pathname = `${CONFIRM_TRANSACTION_ROUTE}/${id}${CONFIRM_APPROVE_PATH}`; return ; } - case TRANSACTION_TYPES.TOKEN_METHOD_SET_APPROVAL_FOR_ALL: { + case TransactionType.tokenMethodSetApprovalForAll: { const pathname = `${CONFIRM_TRANSACTION_ROUTE}/${id}${CONFIRM_SET_APPROVAL_FOR_ALL_PATH}`; return ; } - case TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM: { + case TransactionType.tokenMethodTransferFrom: { const pathname = `${CONFIRM_TRANSACTION_ROUTE}/${id}${CONFIRM_TRANSFER_FROM_PATH}`; return ; } - case TRANSACTION_TYPES.TOKEN_METHOD_SAFE_TRANSFER_FROM: { + case TransactionType.tokenMethodSafeTransferFrom: { const pathname = `${CONFIRM_TRANSACTION_ROUTE}/${id}${CONFIRM_SAFE_TRANSFER_FROM_PATH}`; return ; } diff --git a/ui/pages/confirm-transaction/conf-tx.js b/ui/pages/confirm-transaction/conf-tx.js index acadc401a..47334a38a 100644 --- a/ui/pages/confirm-transaction/conf-tx.js +++ b/ui/pages/confirm-transaction/conf-tx.js @@ -12,7 +12,7 @@ import SignatureRequestOriginal from '../../components/app/signature-request-ori import Loading from '../../components/ui/loading-screen'; import { getMostRecentOverviewPage } from '../../ducks/history/history'; import { MESSAGE_TYPE } from '../../../shared/constants/app'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import { getSendTo } from '../../ducks/send'; function mapStateToProps(state) { @@ -237,7 +237,7 @@ class ConfirmTxScreen extends Component { const unconfTxList = txHelper(unapprovedTxs, {}, {}, {}, network, chainId); - if (prevTx && prevTx.status === TRANSACTION_STATUSES.DROPPED) { + if (prevTx && prevTx.status === TransactionStatus.dropped) { this.props.dispatch( actions.showModal({ name: 'TRANSACTION_CONFIRMED', diff --git a/ui/pages/import-token/import-token.component.js b/ui/pages/import-token/import-token.component.js index fdfa6eb62..f9f5b6c35 100644 --- a/ui/pages/import-token/import-token.component.js +++ b/ui/pages/import-token/import-token.component.js @@ -21,7 +21,7 @@ import ActionableMessage from '../../components/ui/actionable-message/actionable import Typography from '../../components/ui/typography'; import { TYPOGRAPHY, FONT_WEIGHT } from '../../helpers/constants/design-system'; import Button from '../../components/ui/button'; -import { TOKEN_STANDARDS } from '../../../shared/constants/transaction'; +import { TokenStandard } from '../../../shared/constants/transaction'; import { STATIC_MAINNET_TOKEN_LIST } from '../../../shared/constants/tokens'; import TokenSearch from './token-search'; import TokenList from './token-list'; @@ -125,7 +125,7 @@ class ImportToken extends Component { customDecimals: 0, searchResults: [], selectedTokens: {}, - standard: TOKEN_STANDARDS.NONE, + standard: TokenStandard.NONE, tokenSelectorError: null, customAddressError: null, customSymbolError: null, diff --git a/ui/pages/send/gas-display/gas-display.js b/ui/pages/send/gas-display/gas-display.js index a27d52014..c3c345602 100644 --- a/ui/pages/send/gas-display/gas-display.js +++ b/ui/pages/send/gas-display/gas-display.js @@ -21,11 +21,7 @@ import { FONT_STYLE, FONT_WEIGHT, } from '../../../helpers/constants/design-system'; -import { - ERC1155, - ERC20, - ERC721, -} from '../../../../shared/constants/transaction'; +import { TokenStandard } from '../../../../shared/constants/transaction'; import LoadingHeartBeat from '../../../components/ui/loading-heartbeat'; import TransactionDetailItem from '../../../components/app/transaction-detail-item'; import { NETWORK_TO_NAME_MAP } from '../../../../shared/constants/network'; @@ -96,11 +92,13 @@ export default function GasDisplay({ gasError }) { let title; if ( - draftTransaction?.asset.details?.standard === ERC721 || - draftTransaction?.asset.details?.standard === ERC1155 + draftTransaction?.asset.details?.standard === TokenStandard.ERC721 || + draftTransaction?.asset.details?.standard === TokenStandard.ERC1155 ) { title = draftTransaction?.asset.details?.name; - } else if (draftTransaction?.asset.details?.standard === ERC20) { + } else if ( + draftTransaction?.asset.details?.standard === TokenStandard.ERC20 + ) { title = `${hexWEIToDecETH(draftTransaction.amount.value)} ${ draftTransaction?.asset.details?.symbol }`; diff --git a/ui/pages/send/send-content/send-amount-row/__snapshots__/send-amount-row.test.js.snap b/ui/pages/send/send-content/send-amount-row/__snapshots__/send-amount-row.test.js.snap index 307491078..1e40d3e95 100644 --- a/ui/pages/send/send-content/send-amount-row/__snapshots__/send-amount-row.test.js.snap +++ b/ui/pages/send/send-content/send-amount-row/__snapshots__/send-amount-row.test.js.snap @@ -1,79 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`SendAmountRow Component render Collectible Asset Type should match snapshot for token collectible type 1`] = ` -
-
-
- Amount: - -
-
-
-
-
-
- -
- ETH -
-
-
- No conversion rate available -
-
- -
-
-
-
-
-
-`; +exports[`SendAmountRow Component render Collectible Asset Type should match snapshot for token collectible type 1`] = `
`; exports[`SendAmountRow Component render Native Asset Type should match snapshot for native asset type 1`] = `
diff --git a/ui/pages/send/send-content/send-amount-row/send-amount-row.component.js b/ui/pages/send/send-content/send-amount-row/send-amount-row.component.js index 3320bf414..19f78dcd7 100644 --- a/ui/pages/send/send-content/send-amount-row/send-amount-row.component.js +++ b/ui/pages/send/send-content/send-amount-row/send-amount-row.component.js @@ -3,7 +3,7 @@ import PropTypes from 'prop-types'; import SendRowWrapper from '../send-row-wrapper'; import UserPreferencedCurrencyInput from '../../../../components/app/user-preferenced-currency-input'; import UserPreferencedTokenInput from '../../../../components/app/user-preferenced-token-input'; -import { ASSET_TYPES } from '../../../../../shared/constants/transaction'; +import { AssetType } from '../../../../../shared/constants/transaction'; import AmountMaxButton from './amount-max-button'; export default class SendAmountRow extends Component { @@ -25,7 +25,7 @@ export default class SendAmountRow extends Component { renderInput() { const { amount, inError, asset } = this.props; - return asset.type === ASSET_TYPES.TOKEN ? ( + return asset.type === AssetType.token ? ( { standard: 'ERC20', }, error: null, - type: ASSET_TYPES.TOKEN, + type: AssetType.token, }, }, }, @@ -74,7 +74,7 @@ describe('SendAmountRow Component', () => { balance: '', details: null, error: null, - type: ASSET_TYPES.COLLECTIBLE, + type: AssetType.NFT, }, }, }, diff --git a/ui/pages/send/send-content/send-asset-row/send-asset-row.component.js b/ui/pages/send/send-content/send-asset-row/send-asset-row.component.js index 9bbda50ac..0adf4930a 100644 --- a/ui/pages/send/send-content/send-asset-row/send-asset-row.component.js +++ b/ui/pages/send/send-content/send-asset-row/send-asset-row.component.js @@ -9,9 +9,8 @@ import { PRIMARY } from '../../../../helpers/constants/common'; import { isEqualCaseInsensitive } from '../../../../../shared/modules/string-utils'; import { EVENT } from '../../../../../shared/constants/metametrics'; import { - ASSET_TYPES, - ERC20, - ERC721, + AssetType, + TokenStandard, } from '../../../../../shared/constants/transaction'; export default class SendAssetRow extends Component { @@ -64,7 +63,8 @@ export default class SendAssetRow extends Component { const sendableTokens = this.props.tokens.filter((token) => !token.isERC721); const sendableCollectibles = this.props.collectibles.filter( (collectible) => - collectible.isCurrentlyOwned && collectible.standard === ERC721, + collectible.isCurrentlyOwned && + collectible.standard === TokenStandard.ERC721, ); this.setState({ sendableTokens, sendableCollectibles }); } @@ -75,11 +75,11 @@ export default class SendAssetRow extends Component { getAssetSelected = (type, token) => { switch (type) { - case ASSET_TYPES.NATIVE: + case AssetType.native: return this.props.nativeCurrency; - case ASSET_TYPES.TOKEN: - return ERC20; - case ASSET_TYPES.NFT: + case AssetType.token: + return TokenStandard.ERC20; + case AssetType.NFT: return token?.standard; default: return null; @@ -103,7 +103,7 @@ export default class SendAssetRow extends Component { }); this.props.updateSendAsset({ type, - details: type === ASSET_TYPES.NATIVE ? null : token, + details: type === AssetType.native ? null : token, }); }, ); @@ -137,14 +137,14 @@ export default class SendAssetRow extends Component { collectibles, } = this.props; - if (type === ASSET_TYPES.TOKEN) { + if (type === AssetType.token) { const token = tokens.find(({ address }) => isEqualCaseInsensitive(address, details.address), ); if (token) { return this.renderToken(token); } - } else if (type === ASSET_TYPES.NFT) { + } else if (type === AssetType.NFT) { const collectible = collectibles.find( ({ address, tokenId }) => isEqualCaseInsensitive(address, details.address) && @@ -168,9 +168,7 @@ export default class SendAssetRow extends Component {
{this.renderNativeCurrency(true)} - this.selectToken(ASSET_TYPES.TOKEN, token) - } + clickHandler={(token) => this.selectToken(AssetType.token, token)} /> {this.state.sendableCollectibles.map((collectible) => @@ -201,7 +199,7 @@ export default class SendAssetRow extends Component { ? 'send-v2__asset-dropdown__asset' : 'send-v2__asset-dropdown__single-asset' } - onClick={() => this.selectToken(ASSET_TYPES.NATIVE)} + onClick={() => this.selectToken(AssetType.native)} >
this.selectToken(ASSET_TYPES.TOKEN, token)} + onClick={() => this.selectToken(AssetType.token, token)} >
@@ -268,7 +266,7 @@ export default class SendAssetRow extends Component {
this.selectToken(ASSET_TYPES.NFT, collectible)} + onClick={() => this.selectToken(AssetType.NFT, collectible)} >
diff --git a/ui/pages/send/send-content/send-content.component.js b/ui/pages/send/send-content/send-content.component.js index d82829c51..b5f1c26e8 100644 --- a/ui/pages/send/send-content/send-content.component.js +++ b/ui/pages/send/send-content/send-content.component.js @@ -9,7 +9,7 @@ import { GAS_PRICE_EXCESSIVE_ERROR_KEY, INSUFFICIENT_FUNDS_FOR_GAS_ERROR_KEY, } from '../../../helpers/constants/error-keys'; -import { ASSET_TYPES } from '../../../../shared/constants/transaction'; +import { AssetType } from '../../../../shared/constants/transaction'; import { CONTRACT_ADDRESS_LINK } from '../../../helpers/constants/common'; import GasDisplay from '../gas-display'; import SendAmountRow from './send-amount-row'; @@ -63,8 +63,8 @@ export default class SendContent extends Component { } const showHexData = this.props.showHexData && - asset.type !== ASSET_TYPES.TOKEN && - asset.type !== ASSET_TYPES.NFT; + asset.type !== AssetType.token && + asset.type !== AssetType.NFT; const showKnownRecipientWarning = recipient.warning === 'knownAddressRecipient'; diff --git a/ui/pages/send/send-header/send-header.component.js b/ui/pages/send/send-header/send-header.component.js index d71b6ef99..701831a2d 100644 --- a/ui/pages/send/send-header/send-header.component.js +++ b/ui/pages/send/send-header/send-header.component.js @@ -11,7 +11,7 @@ import { resetSendState, SEND_STAGES, } from '../../../ducks/send'; -import { ASSET_TYPES } from '../../../../shared/constants/transaction'; +import { AssetType } from '../../../../shared/constants/transaction'; export default function SendHeader() { const history = useHistory(); @@ -26,7 +26,7 @@ export default function SendHeader() { history.push(mostRecentOverviewPage); }; - let title = asset?.type === ASSET_TYPES.NATIVE ? t('send') : t('sendTokens'); + let title = asset?.type === AssetType.native ? t('send') : t('sendTokens'); if ( draftTransactionExists === false || diff --git a/ui/pages/send/send-header/send-header.component.test.js b/ui/pages/send/send-header/send-header.component.test.js index 428a653ef..c38132409 100644 --- a/ui/pages/send/send-header/send-header.component.test.js +++ b/ui/pages/send/send-header/send-header.component.test.js @@ -5,7 +5,7 @@ import thunk from 'redux-thunk'; import { fireEvent } from '@testing-library/react'; import { SEND_STAGES } from '../../../ducks/send'; import { renderWithProvider } from '../../../../test/jest'; -import { ASSET_TYPES } from '../../../../shared/constants/transaction'; +import { AssetType } from '../../../../shared/constants/transaction'; import { getInitialSendStateWithExistingTxState, INITIAL_SEND_STATE_FOR_EXISTING_DRAFT, @@ -59,7 +59,7 @@ describe('SendHeader Component', () => { stage: SEND_STAGES.DRAFT, asset: { ...INITIAL_SEND_STATE_FOR_EXISTING_DRAFT.asset, - type: ASSET_TYPES.NATIVE, + type: AssetType.native, }, }, gas: { basicEstimateStatus: 'LOADING' }, @@ -76,7 +76,7 @@ describe('SendHeader Component', () => { send: { ...getInitialSendStateWithExistingTxState({ asset: { - type: ASSET_TYPES.TOKEN, + type: AssetType.token, }, }), stage: SEND_STAGES.DRAFT, diff --git a/ui/pages/send/send.js b/ui/pages/send/send.js index a23c29a0f..6307340ff 100644 --- a/ui/pages/send/send.js +++ b/ui/pages/send/send.js @@ -20,7 +20,7 @@ import { getSendHexDataFeatureFlagState } from '../../ducks/metamask/metamask'; import { showQrScanner } from '../../store/actions'; import { MetaMetricsContext } from '../../contexts/metametrics'; import { EVENT } from '../../../shared/constants/metametrics'; -import { ASSET_TYPES } from '../../../shared/constants/transaction'; +import { AssetType } from '../../../shared/constants/transaction'; import SendHeader from './send-header'; import AddRecipient from './send-content/add-recipient'; import SendContent from './send-content'; @@ -64,7 +64,7 @@ export default function SendTransactionScreen() { startedNewDraftTransaction.current === false ) { startedNewDraftTransaction.current = true; - dispatch(startNewDraftTransaction({ type: ASSET_TYPES.NATIVE })); + dispatch(startNewDraftTransaction({ type: AssetType.native })); } }, [draftTransactionExists, dispatch]); diff --git a/ui/pages/send/send.utils.js b/ui/pages/send/send.utils.js index 2c45e1ccf..317a6f8cd 100644 --- a/ui/pages/send/send.utils.js +++ b/ui/pages/send/send.utils.js @@ -9,7 +9,7 @@ import { } from '../../../shared/modules/conversion.utils'; import { addHexPrefix } from '../../../app/scripts/lib/util'; -import { ERC20, ERC721 } from '../../../shared/constants/transaction'; +import { TokenStandard } from '../../../shared/constants/transaction'; import { calcTokenAmount } from '../../../shared/lib/transactions-controller-utils'; import { TOKEN_TRANSFER_FUNCTION_SIGNATURE, @@ -165,13 +165,13 @@ function generateERC721TransferData({ function getAssetTransferData({ sendToken, fromAddress, toAddress, amount }) { switch (sendToken.standard) { - case ERC721: + case TokenStandard.ERC721: return generateERC721TransferData({ toAddress, fromAddress, tokenId: sendToken.tokenId, }); - case ERC20: + case TokenStandard.ERC20: default: return generateERC20TransferData({ toAddress, diff --git a/ui/pages/swaps/index.js b/ui/pages/swaps/index.js index 0aedc8e87..b62c9a910 100644 --- a/ui/pages/swaps/index.js +++ b/ui/pages/swaps/index.js @@ -84,7 +84,7 @@ import { import { useGasFeeEstimates } from '../../hooks/useGasFeeEstimates'; import FeatureToggledRoute from '../../helpers/higher-order-components/feature-toggled-route'; import { EVENT } from '../../../shared/constants/metametrics'; -import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; +import { TransactionStatus } from '../../../shared/constants/transaction'; import ActionableMessage from '../../components/ui/actionable-message'; import { MetaMetricsContext } from '../../contexts/metametrics'; import { getSwapsTokensReceivedFromTxMeta } from '../../../shared/lib/transactions-controller-utils'; @@ -192,12 +192,12 @@ export default function Swap() { approveTxData, chainId, ); - const tradeConfirmed = tradeTxData?.status === TRANSACTION_STATUSES.CONFIRMED; + const tradeConfirmed = tradeTxData?.status === TransactionStatus.confirmed; const approveError = - approveTxData?.status === TRANSACTION_STATUSES.FAILED || + approveTxData?.status === TransactionStatus.failed || approveTxData?.txReceipt?.status === '0x0'; const tradeError = - tradeTxData?.status === TRANSACTION_STATUSES.FAILED || + tradeTxData?.status === TransactionStatus.failed || tradeTxData?.txReceipt?.status === '0x0'; const conversionError = approveError || tradeError; diff --git a/ui/pages/swaps/smart-transaction-status/smart-transaction-status.js b/ui/pages/swaps/smart-transaction-status/smart-transaction-status.js index f59ad29e5..744ad0aa0 100644 --- a/ui/pages/swaps/smart-transaction-status/smart-transaction-status.js +++ b/ui/pages/swaps/smart-transaction-status/smart-transaction-status.js @@ -49,7 +49,7 @@ import { setBackgroundSwapRouteState, } from '../../../store/actions'; import { EVENT } from '../../../../shared/constants/metametrics'; -import { SMART_TRANSACTION_STATUSES } from '../../../../shared/constants/transaction'; +import { SmartTransactionStatus } from '../../../../shared/constants/transaction'; import SwapsFooter from '../swaps-footer'; import { @@ -67,7 +67,7 @@ import UnknownIcon from './unknown-icon'; import ArrowIcon from './arrow-icon'; import TimerIcon from './timer-icon'; -export default function SmartTransactionStatus() { +export default function SmartTransactionStatusPage() { const [cancelSwapLinkClicked, setCancelSwapLinkClicked] = useState(false); const t = useContext(I18nContext); const history = useHistory(); @@ -106,7 +106,7 @@ export default function SmartTransactionStatus() { const USDConversionRate = useSelector(getUSDConversionRate); const currentCurrency = useSelector(getCurrentCurrency); - let smartTransactionStatus = SMART_TRANSACTION_STATUSES.PENDING; + let smartTransactionStatus = SmartTransactionStatus.pending; let latestSmartTransaction = {}; let latestSmartTransactionUuid; let cancellationFeeWei; @@ -116,7 +116,7 @@ export default function SmartTransactionStatus() { currentSmartTransactions[currentSmartTransactions.length - 1]; latestSmartTransactionUuid = latestSmartTransaction?.uuid; smartTransactionStatus = - latestSmartTransaction?.status || SMART_TRANSACTION_STATUSES.PENDING; + latestSmartTransaction?.status || SmartTransactionStatus.pending; cancellationFeeWei = latestSmartTransaction?.statusMetadata?.cancellationFeeWei; } @@ -156,10 +156,10 @@ export default function SmartTransactionStatus() { const trackEvent = useContext(MetaMetricsContext); const isSmartTransactionPending = - smartTransactionStatus === SMART_TRANSACTION_STATUSES.PENDING; + smartTransactionStatus === SmartTransactionStatus.pending; const showCloseButtonOnly = isSmartTransactionPending || - smartTransactionStatus === SMART_TRANSACTION_STATUSES.SUCCESS; + smartTransactionStatus === SmartTransactionStatus.success; const txHash = latestSmartTransaction?.statusMetadata?.minedHash; useEffect(() => { @@ -220,7 +220,7 @@ export default function SmartTransactionStatus() { headerText = t('stxPendingPubliclySubmittingSwap'); } } - if (smartTransactionStatus === SMART_TRANSACTION_STATUSES.SUCCESS) { + if (smartTransactionStatus === SmartTransactionStatus.success) { headerText = t('stxSuccess'); if ( fetchParamsDestinationTokenInfo.symbol || @@ -235,7 +235,7 @@ export default function SmartTransactionStatus() { } else if ( smartTransactionStatus === 'cancelled_user_cancelled' || latestSmartTransaction?.statusMetadata?.minedTx === - SMART_TRANSACTION_STATUSES.CANCELLED + SmartTransactionStatus.cancelled ) { headerText = t('stxUserCancelled'); description = t('stxUserCancelledDescription'); @@ -473,7 +473,7 @@ export default function SmartTransactionStatus() { {showCancelSwapLink && latestSmartTransactionUuid && isSmartTransactionPending && } - {smartTransactionStatus === SMART_TRANSACTION_STATUSES.SUCCESS ? ( + {smartTransactionStatus === SmartTransactionStatus.success ? ( ) : null} { - return ; +export const SmartTransactionStatusLabelComponent = () => { + return ; }; diff --git a/ui/pages/swaps/smart-transaction-status/smart-transaction-status.test.js b/ui/pages/swaps/smart-transaction-status/smart-transaction-status.test.js index 836344d7a..4d71002bc 100644 --- a/ui/pages/swaps/smart-transaction-status/smart-transaction-status.test.js +++ b/ui/pages/swaps/smart-transaction-status/smart-transaction-status.test.js @@ -9,7 +9,7 @@ import { fireEvent, } from '../../../../test/jest'; import { CHAIN_IDS } from '../../../../shared/constants/network'; -import SmartTransactionStatus from '.'; +import SmartTransactionStatusLabel from '.'; const middleware = [thunk]; setBackgroundConnection({ @@ -39,10 +39,13 @@ jest.mock('../../../ducks/swaps/swaps', () => { }; }); -describe('SmartTransactionStatus', () => { +describe('SmartTransactionStatusLabel', () => { it('renders the component with initial props', () => { const store = configureMockStore(middleware)(createSwapsMockStore()); - const { getByText } = renderWithProvider(, store); + const { getByText } = renderWithProvider( + , + store, + ); expect(getByText('Publicly submitting your Swap...')).toBeInTheDocument(); expect(getByText('Close')).toBeInTheDocument(); }); @@ -55,7 +58,10 @@ describe('SmartTransactionStatus', () => { ][1]; latestSmartTransaction.status = 'success'; const store = configureMockStore(middleware)(mockStore); - const { getByText } = renderWithProvider(, store); + const { getByText } = renderWithProvider( + , + store, + ); expect(getByText('Swap complete!')).toBeInTheDocument(); expect(getByText('Your USDC is now available.')).toBeInTheDocument(); expect(getByText('Create a new swap')).toBeInTheDocument(); @@ -70,7 +76,10 @@ describe('SmartTransactionStatus', () => { ][1]; latestSmartTransaction.status = 'reverted'; const store = configureMockStore(middleware)(mockStore); - const { getByText } = renderWithProvider(, store); + const { getByText } = renderWithProvider( + , + store, + ); expect(getByText('Swap failed')).toBeInTheDocument(); expect(getByText('customer support')).toBeInTheDocument(); expect(getByText('Close')).toBeInTheDocument(); @@ -84,7 +93,10 @@ describe('SmartTransactionStatus', () => { ][1]; latestSmartTransaction.status = 'cancelled_user_cancelled'; const store = configureMockStore(middleware)(mockStore); - const { getByText } = renderWithProvider(, store); + const { getByText } = renderWithProvider( + , + store, + ); expect(getByText('Swap cancelled')).toBeInTheDocument(); expect( getByText( @@ -102,7 +114,10 @@ describe('SmartTransactionStatus', () => { ][1]; latestSmartTransaction.status = 'deadline_missed'; const store = configureMockStore(middleware)(mockStore); - const { getByText } = renderWithProvider(, store); + const { getByText } = renderWithProvider( + , + store, + ); expect(getByText('Swap would have failed')).toBeInTheDocument(); expect( getByText( @@ -120,7 +135,10 @@ describe('SmartTransactionStatus', () => { ][1]; latestSmartTransaction.status = 'unknown'; const store = configureMockStore(middleware)(mockStore); - const { getByText } = renderWithProvider(, store); + const { getByText } = renderWithProvider( + , + store, + ); expect(getByText('Status unknown')).toBeInTheDocument(); expect( getByText( @@ -132,7 +150,10 @@ describe('SmartTransactionStatus', () => { it('cancels a transaction', () => { const store = configureMockStore(middleware)(createSwapsMockStore()); - const { getByText } = renderWithProvider(, store); + const { getByText } = renderWithProvider( + , + store, + ); expect(getByText('Publicly submitting your Swap...')).toBeInTheDocument(); const cancelLink = getByText('Cancel swap for ~0'); expect(cancelLink).toBeInTheDocument(); @@ -145,7 +166,10 @@ describe('SmartTransactionStatus', () => { it('clicks on the Close button', () => { const store = configureMockStore(middleware)(createSwapsMockStore()); - const { getByText } = renderWithProvider(, store); + const { getByText } = renderWithProvider( + , + store, + ); expect(getByText('Publicly submitting your Swap...')).toBeInTheDocument(); const closeButton = getByText('Close'); expect(closeButton).toBeInTheDocument(); diff --git a/ui/selectors/confirm-transaction.js b/ui/selectors/confirm-transaction.js index 4be828d44..cd199f954 100644 --- a/ui/selectors/confirm-transaction.js +++ b/ui/selectors/confirm-transaction.js @@ -14,7 +14,7 @@ import { getGasFeeEstimates, getNativeCurrency, } from '../ducks/metamask/metamask'; -import { TRANSACTION_ENVELOPE_TYPES } from '../../shared/constants/transaction'; +import { TransactionEnvelopeType } from '../../shared/constants/transaction'; import { decGWEIToHexWEI } from '../helpers/utils/conversions.util'; import { GAS_ESTIMATE_TYPES, @@ -273,7 +273,7 @@ export const transactionFeeSelector = function (state, txData) { if (networkAndAccountSupportsEIP1559) { const { gasPrice = '0' } = gasFeeEstimates; const selectedGasEstimates = gasFeeEstimates[txData.userFeeLevel] || {}; - if (txData.txParams?.type === TRANSACTION_ENVELOPE_TYPES.LEGACY) { + if (txData.txParams?.type === TransactionEnvelopeType.legacy) { gasEstimationObject.gasPrice = txData.txParams?.gasPrice ?? decGWEIToHexWEI(gasPrice); } else { diff --git a/ui/selectors/confirm-transaction.test.js b/ui/selectors/confirm-transaction.test.js index 3799428b7..b44197020 100644 --- a/ui/selectors/confirm-transaction.test.js +++ b/ui/selectors/confirm-transaction.test.js @@ -1,5 +1,5 @@ import { CHAIN_IDS } from '../../shared/constants/network'; -import { TRANSACTION_TYPES } from '../../shared/constants/transaction'; +import { TransactionType } from '../../shared/constants/transaction'; import { unconfirmedTransactionsCountSelector, sendTokenTokenAmountAndToAddressSelector, @@ -47,7 +47,7 @@ describe('Confirm Transaction Selector', () => { const state = { confirmTransaction: { tokenData: { - name: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + name: TransactionType.tokenMethodTransfer, args: getEthersArrayLikeFromObj({ _to: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc', _value: { toString: () => '1' }, diff --git a/ui/selectors/nonce-sorted-transactions-selector.test.js b/ui/selectors/nonce-sorted-transactions-selector.test.js index 09509a201..4cd6840df 100644 --- a/ui/selectors/nonce-sorted-transactions-selector.test.js +++ b/ui/selectors/nonce-sorted-transactions-selector.test.js @@ -1,8 +1,8 @@ import { head, last } from 'lodash'; import { CHAIN_IDS } from '../../shared/constants/network'; import { - TRANSACTION_STATUSES, - TRANSACTION_TYPES, + TransactionStatus, + TransactionType, } from '../../shared/constants/transaction'; import { nonceSortedTransactionsSelector } from './transactions'; @@ -18,7 +18,7 @@ const SENDERS = { const INCOMING_TX = { id: '0-incoming', - type: TRANSACTION_TYPES.INCOMING, + type: TransactionType.incoming, txParams: { value: '0x0', from: RECIPIENTS.ONE, @@ -27,9 +27,9 @@ const INCOMING_TX = { }; const SIGNING_REQUEST = { - type: TRANSACTION_TYPES.SIGNING_REQUEST, + type: TransactionType.sign, id: '0-signing', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, }; const SIMPLE_SEND_TX = { @@ -38,7 +38,7 @@ const SIMPLE_SEND_TX = { from: SENDERS.ONE, to: RECIPIENTS.ONE, }, - type: TRANSACTION_TYPES.SIMPLE_SEND, + type: TransactionType.simpleSend, }; const TOKEN_SEND_TX = { @@ -49,13 +49,13 @@ const TOKEN_SEND_TX = { value: '0x0', data: '0xdata', }, - type: TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, + type: TransactionType.tokenMethodTransfer, }; const RETRY_TX = { ...SIMPLE_SEND_TX, id: '0-retry', - type: TRANSACTION_TYPES.RETRY, + type: TransactionType.retry, }; const CANCEL_TX = { @@ -65,7 +65,7 @@ const CANCEL_TX = { from: SENDERS.ONE, to: SENDERS.ONE, }, - type: TRANSACTION_TYPES.CANCEL, + type: TransactionType.cancel, }; const getStateTree = ({ @@ -92,7 +92,7 @@ const duplicateTx = (base, overrides) => { const { nonce = '0x0', time = 0, - status = TRANSACTION_STATUSES.CONFIRMED, + status = TransactionStatus.confirmed, txReceipt, } = overrides ?? {}; return { @@ -110,7 +110,7 @@ const duplicateTx = (base, overrides) => { describe('nonceSortedTransactionsSelector', () => { it('should properly group a simple send that is superseded by a retry', () => { const txList = [ - duplicateTx(SIMPLE_SEND_TX, { status: TRANSACTION_STATUSES.DROPPED }), + duplicateTx(SIMPLE_SEND_TX, { status: TransactionStatus.dropped }), duplicateTx(RETRY_TX, { time: 1 }), ]; @@ -132,7 +132,7 @@ describe('nonceSortedTransactionsSelector', () => { it('should properly group a failed off-chain simple send that is superseded by a retry', () => { const txList = [ - duplicateTx(SIMPLE_SEND_TX, { status: TRANSACTION_STATUSES.FAILED }), + duplicateTx(SIMPLE_SEND_TX, { status: TransactionStatus.failed }), duplicateTx(RETRY_TX, { time: 1 }), ]; @@ -154,7 +154,7 @@ describe('nonceSortedTransactionsSelector', () => { it('should properly group a simple send that is superseded by a cancel', () => { const txList = [ - duplicateTx(SIMPLE_SEND_TX, { status: TRANSACTION_STATUSES.DROPPED }), + duplicateTx(SIMPLE_SEND_TX, { status: TransactionStatus.dropped }), duplicateTx(CANCEL_TX, { time: 1 }), ]; @@ -176,8 +176,8 @@ describe('nonceSortedTransactionsSelector', () => { it('should properly group a simple send and retry that is superseded by a cancel', () => { const txList = [ - duplicateTx(SIMPLE_SEND_TX, { status: TRANSACTION_STATUSES.DROPPED }), - duplicateTx(RETRY_TX, { time: 1, status: TRANSACTION_STATUSES.DROPPED }), + duplicateTx(SIMPLE_SEND_TX, { status: TransactionStatus.dropped }), + duplicateTx(RETRY_TX, { time: 1, status: TransactionStatus.dropped }), duplicateTx(CANCEL_TX, { time: 2 }), ]; @@ -202,7 +202,7 @@ describe('nonceSortedTransactionsSelector', () => { // changing expectations from today. It will also allow us to invert this // test case when we move and change grouping logic. const txList = [ - duplicateTx(TOKEN_SEND_TX, { status: TRANSACTION_STATUSES.DROPPED }), + duplicateTx(TOKEN_SEND_TX, { status: TransactionStatus.dropped }), duplicateTx(SIMPLE_SEND_TX, { time: 1 }), ]; @@ -269,8 +269,8 @@ describe('nonceSortedTransactionsSelector', () => { it('should not set a failed off-chain transaction as primary, allowing additional retries', () => { const txList = [ - duplicateTx(SIMPLE_SEND_TX, { status: TRANSACTION_STATUSES.SUBMITTED }), - duplicateTx(RETRY_TX, { status: TRANSACTION_STATUSES.FAILED, time: 1 }), + duplicateTx(SIMPLE_SEND_TX, { status: TransactionStatus.submitted }), + duplicateTx(RETRY_TX, { status: TransactionStatus.failed, time: 1 }), ]; const state = getStateTree({ txList }); @@ -298,9 +298,9 @@ describe('nonceSortedTransactionsSelector', () => { // This is desired because we have no way currently to tell the intent // of the transactions. const txList = [ - duplicateTx(SIMPLE_SEND_TX, { status: TRANSACTION_STATUSES.FAILED }), + duplicateTx(SIMPLE_SEND_TX, { status: TransactionStatus.failed }), duplicateTx(SIMPLE_SEND_TX, { - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, time: 1, }), ]; @@ -323,9 +323,9 @@ describe('nonceSortedTransactionsSelector', () => { it('should set a failed on-chain transaction as primary', () => { const txList = [ - duplicateTx(SIMPLE_SEND_TX, { status: TRANSACTION_STATUSES.SUBMITTED }), + duplicateTx(SIMPLE_SEND_TX, { status: TransactionStatus.submitted }), duplicateTx(RETRY_TX, { - status: TRANSACTION_STATUSES.FAILED, + status: TransactionStatus.failed, txReceipt: { status: '0x0' }, time: 1, }), diff --git a/ui/selectors/selectors.js b/ui/selectors/selectors.js index 25ef4d09c..2b1c402cf 100644 --- a/ui/selectors/selectors.js +++ b/ui/selectors/selectors.js @@ -71,7 +71,7 @@ import { import { isEqualCaseInsensitive } from '../../shared/modules/string-utils'; import { hexToDecimal } from '../../shared/lib/metamask-controller-utils'; import { formatMoonpaySymbol } from '../helpers/utils/moonpay'; -import { TRANSACTION_STATUSES } from '../../shared/constants/transaction'; +import { TransactionStatus } from '../../shared/constants/transaction'; ///: BEGIN:ONLY_INCLUDE_IN(flask) import { SNAPS_VIEW_ROUTE } from '../helpers/constants/routes'; import { getPermissionSubjects } from './permissions'; @@ -869,7 +869,7 @@ export const getTransaction = createDeepEqualSelector( export const getFullTxData = createDeepEqualSelector( getTxData, (state, transactionId, status) => { - if (status === TRANSACTION_STATUSES.UNAPPROVED) { + if (status === TransactionStatus.unapproved) { return getUnapprovedTransaction(state, transactionId); } return getTransaction(state, transactionId); diff --git a/ui/selectors/transactions.js b/ui/selectors/transactions.js index 879703550..d4cdddf0c 100644 --- a/ui/selectors/transactions.js +++ b/ui/selectors/transactions.js @@ -5,9 +5,9 @@ import { } from '../helpers/constants/transactions'; import txHelper from '../helpers/utils/tx-helper'; import { - TRANSACTION_STATUSES, - TRANSACTION_TYPES, - SMART_TRANSACTION_STATUSES, + TransactionStatus, + TransactionType, + SmartTransactionStatus, } from '../../shared/constants/transaction'; import { transactionMatchesNetwork } from '../../shared/modules/transaction.utils'; import { hexToDecimal } from '../../shared/lib/metamask-controller-utils'; @@ -18,8 +18,8 @@ import { } from './selectors'; const INVALID_INITIAL_TRANSACTION_TYPES = [ - TRANSACTION_TYPES.CANCEL, - TRANSACTION_TYPES.RETRY, + TransactionType.cancel, + TransactionType.retry, ]; export const incomingTxListSelector = (state) => { @@ -58,9 +58,9 @@ export const smartTransactionsListSelector = (state) => ?.filter((stx) => !stx.confirmed) .map((stx) => ({ ...stx, - transactionType: TRANSACTION_TYPES.SMART, + transactionType: TransactionType.smart, status: stx.status?.startsWith('cancelled') - ? SMART_TRANSACTION_STATUSES.CANCELLED + ? SmartTransactionStatus.cancelled : stx.status, })); @@ -252,7 +252,7 @@ export const nonceSortedTransactionsSelector = createSelector( txReceipt, } = transaction; - if (typeof nonce === 'undefined' || type === TRANSACTION_TYPES.INCOMING) { + if (typeof nonce === 'undefined' || type === TransactionType.incoming) { const transactionGroup = { transactions: [transaction], initialTransaction: transaction, @@ -262,7 +262,7 @@ export const nonceSortedTransactionsSelector = createSelector( nonce, }; - if (type === TRANSACTION_TYPES.INCOMING) { + if (type === TransactionType.incoming) { incomingTransactionGroups.push(transactionGroup); } else { insertTransactionGroupByTime( @@ -303,8 +303,7 @@ export const nonceSortedTransactionsSelector = createSelector( // known outside of the user's local MetaMask and the nonce // associated will be applied to the next. isEphemeral: - status === TRANSACTION_STATUSES.FAILED && - txReceipt?.status !== '0x0', + status === TransactionStatus.failed && txReceipt?.status !== '0x0', // We never want to use a speed up (retry) or cancel as the initial // transaction in a group, regardless of time order. This is because // useTransactionDisplayData cannot parse a retry or cancel because @@ -323,7 +322,7 @@ export const nonceSortedTransactionsSelector = createSelector( // A confirmed transaction is the most valid transaction status to // display because no other transaction of the same nonce can have a // more valid status. - isConfirmed: status === TRANSACTION_STATUSES.CONFIRMED, + isConfirmed: status === TransactionStatus.confirmed, // Initial transactions usually are the earliest transaction by time, // but not always. THis value shows whether this transaction occurred // before the current initial. @@ -333,17 +332,17 @@ export const nonceSortedTransactionsSelector = createSelector( // effects. This value is used to determine if the entire transaction // group should be marked as having had a retry. isValidRetry: - type === TRANSACTION_TYPES.RETRY && + type === TransactionType.retry && (status in PRIORITY_STATUS_HASH || - status === TRANSACTION_STATUSES.DROPPED), + status === TransactionStatus.dropped), // We only allow users to cancel the transaction in certain scenarios // to help shield from expensive operations and other unwanted side // effects. This value is used to determine if the entire transaction // group should be marked as having had a cancel. isValidCancel: - type === TRANSACTION_TYPES.CANCEL && + type === TransactionType.cancel && (status in PRIORITY_STATUS_HASH || - status === TRANSACTION_STATUSES.DROPPED), + status === TransactionStatus.dropped), }; // We should never assign a retry or cancel transaction as the initial, @@ -378,8 +377,7 @@ export const nonceSortedTransactionsSelector = createSelector( // block. When this happens, and we have another transaction to // consider in a nonce group, we should use the new transaction. isEphemeral: - nonceProps.primaryTransaction.status === - TRANSACTION_STATUSES.FAILED && + nonceProps.primaryTransaction.status === TransactionStatus.failed && nonceProps.primaryTransaction?.txReceipt?.status !== '0x0', }; @@ -399,8 +397,7 @@ export const nonceSortedTransactionsSelector = createSelector( // block. When this happens, and we have another transaction to // consider in a nonce group, we should use the new transaction. isEphemeral: - nonceProps.initialTransaction.status === - TRANSACTION_STATUSES.FAILED && + nonceProps.initialTransaction.status === TransactionStatus.failed && nonceProps.initialTransaction.txReceipt?.status !== '0x0', }; @@ -440,13 +437,13 @@ export const nonceSortedTransactionsSelector = createSelector( initialTransaction: transaction, primaryTransaction: transaction, hasRetried: - transaction.type === TRANSACTION_TYPES.RETRY && + transaction.type === TransactionType.retry && (transaction.status in PRIORITY_STATUS_HASH || - transaction.status === TRANSACTION_STATUSES.DROPPED), + transaction.status === TransactionStatus.dropped), hasCancelled: - transaction.type === TRANSACTION_TYPES.CANCEL && + transaction.type === TransactionType.cancel && (transaction.status in PRIORITY_STATUS_HASH || - transaction.status === TRANSACTION_STATUSES.DROPPED), + transaction.status === TransactionStatus.dropped), }; insertOrderedNonce(orderedNonces, nonce); @@ -524,6 +521,6 @@ export const submittedPendingTransactionsSelector = createSelector( transactionsSelector, (transactions = []) => transactions.filter( - (transaction) => transaction.status === TRANSACTION_STATUSES.SUBMITTED, + (transaction) => transaction.status === TransactionStatus.submitted, ), ); diff --git a/ui/selectors/transactions.test.js b/ui/selectors/transactions.test.js index 2977fde09..b8eab61eb 100644 --- a/ui/selectors/transactions.test.js +++ b/ui/selectors/transactions.test.js @@ -1,5 +1,5 @@ import { CHAIN_IDS } from '../../shared/constants/network'; -import { TRANSACTION_STATUSES } from '../../shared/constants/transaction'; +import { TransactionStatus } from '../../shared/constants/transaction'; import { unapprovedMessagesSelector, transactionsSelector, @@ -20,7 +20,7 @@ describe('Transaction Selectors', () => { origin: 'origin', }, time: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, type: 'eth_sign', }; @@ -50,7 +50,7 @@ describe('Transaction Selectors', () => { origin: 'origin', }, time: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, type: 'personal_sign', }; @@ -81,7 +81,7 @@ describe('Transaction Selectors', () => { origin: 'origin', }, time: 1, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, type: 'eth_signTypedData', }; @@ -217,7 +217,7 @@ describe('Transaction Selectors', () => { to: '0xRecipient', nonce: '0x0', }, - status: TRANSACTION_STATUSES.SUBMITTED, + status: TransactionStatus.submitted, }; const unapprovedTx = { @@ -228,7 +228,7 @@ describe('Transaction Selectors', () => { to: '0xRecipient', nonce: '0x1', }, - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, }; const approvedTx = { @@ -239,7 +239,7 @@ describe('Transaction Selectors', () => { to: '0xRecipient', nonce: '0x2', }, - status: TRANSACTION_STATUSES.APPROVED, + status: TransactionStatus.approved, }; const confirmedTx = { @@ -250,7 +250,7 @@ describe('Transaction Selectors', () => { to: '0xRecipient', nonce: '0x3', }, - status: TRANSACTION_STATUSES.CONFIRMED, + status: TransactionStatus.confirmed, }; const state = { diff --git a/ui/store/actions.js b/ui/store/actions.js index fc3be09fd..21cdc6289 100644 --- a/ui/store/actions.js +++ b/ui/store/actions.js @@ -884,7 +884,7 @@ export function updateTransaction(txData, dontShowLoadingIndicator) { * The transaction parameters * @param {import( * '../../shared/constants/transaction' - * ).TransactionTypeString} type - The type of the transaction being added. + * ).TransactionType} type - The type of the transaction being added. * @param {Array<{event: string, timestamp: number}>} sendFlowHistory - The * history of the send flow at time of creation. * @returns {import('../../shared/constants/transaction').TransactionMeta} @@ -923,7 +923,7 @@ export function addUnapprovedTransactionAndRouteToConfirmationPage( * The transaction parameters * @param {import( * '../../shared/constants/transaction' - * ).TransactionTypeString} type - The type of the transaction being added. + * ).TransactionType} type - The type of the transaction being added. * @returns {import('../../shared/constants/transaction').TransactionMeta} */ export async function addUnapprovedTransaction(txParams, type) { diff --git a/ui/store/actions.test.js b/ui/store/actions.test.js index 07777762d..3015521ba 100644 --- a/ui/store/actions.test.js +++ b/ui/store/actions.test.js @@ -3,7 +3,7 @@ import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import enLocale from '../../app/_locales/en/messages.json'; import MetaMaskController from '../../app/scripts/metamask-controller'; -import { TRANSACTION_STATUSES } from '../../shared/constants/transaction'; +import { TransactionStatus } from '../../shared/constants/transaction'; import { DEVICE_NAMES } from '../../shared/constants/hardware-wallets'; import { GAS_LIMITS } from '../../shared/constants/gas'; import * as actions from './actions'; @@ -819,7 +819,7 @@ describe('Actions', () => { const txData = { id: '1', - status: TRANSACTION_STATUSES.UNAPPROVED, + status: TransactionStatus.unapproved, metamaskNetworkId: currentNetworkId, txParams, };