-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathtransactions.js
More file actions
791 lines (716 loc) · 27 KB
/
transactions.js
File metadata and controls
791 lines (716 loc) · 27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
import { ApprovalType } from '@metamask/controller-utils';
import { createSelector } from 'reselect';
import {
TransactionStatus,
TransactionType,
} from '@metamask/transaction-controller';
import { SmartTransactionStatuses } from '@metamask/smart-transactions-controller';
import {
isCorrectDeveloperTransactionType,
isCorrectSignatureApprovalType,
} from '../../shared/lib/confirmation.utils';
import {
PRIORITY_STATUS_HASH,
PENDING_STATUS_HASH,
EXCLUDED_TRANSACTION_TYPES,
} from '../helpers/constants/transactions';
import txHelper from '../helpers/utils/tx-helper';
import { SmartTransactionStatus } from '../../shared/constants/transaction';
import { hexToDecimal } from '../../shared/lib/conversion.utils';
import {
getProviderConfig,
getCurrentChainId,
} from '../../shared/lib/selectors/networks';
import {
createDeepEqualSelector,
createShallowEqualInputAndResultSelector,
createParameterizedShallowEqualSelector,
} from '../../shared/lib/selectors/selector-creators';
import { oldestPendingConfirmationSelector } from '../pages/confirmations/selectors/confirm';
import { getSelectedInternalAccount } from './accounts';
import {
hasPendingApprovals,
getApprovalRequestsByType,
getPendingApprovals,
} from './approvals';
import { EMPTY_ARRAY, EMPTY_OBJECT } from './shared';
/**
* Returns all transactions array sorted by time in ascending order.
*
* @param {object} state - Root state
* @returns {object[]} Sorted array of transaction objects
*/
export const getTransactions = createSelector(
(state) => state.metamask?.transactions,
(transactions) => {
if (!transactions?.length) {
return EMPTY_ARRAY;
}
return [...transactions].sort((a, b) => a.time - b.time); // Ascending
},
);
/**
* Returns unapproved transactions as a map indexed by transaction ID.
*
* @param {object} state - Root state
* @returns {Record<string, object>} Object with transaction IDs as keys
*/
export const getUnapprovedTransactions =
createShallowEqualInputAndResultSelector(
getTransactions,
createUnapprovedTransactionsMap,
);
// Parameterized selector creator with LRU cache for multiple chainId arguments.
// This prevents cache thrashing when switching between different chains.
const createChainIdSelector = createParameterizedShallowEqualSelector(10);
/**
* Returns transactions filtered by the given chainId.
* Uses an LRU cache (size 10) to memoize results for multiple chainIds.
*
* @param {object} state - Root state
* @param {string} chainId - The chain ID to filter transactions by
* @returns {object[]} Array of transaction objects for the specified chain
* @example
* const mainnetTxs = getTransactionsByChainId(state, '0x1');
* const polygonTxs = getTransactionsByChainId(state, '0x89');
*/
export const getTransactionsByChainId = createChainIdSelector(
getTransactions,
(_, chainId) => chainId,
(transactions, chainId) => {
if (!transactions.length || !chainId) {
return EMPTY_ARRAY;
}
return transactions.filter(
(transaction) => transaction.chainId === chainId,
);
},
);
/**
* Returns transactions for the current network.
*
* @deprecated Use `getTransactionsByChainId(state, chainId)` instead with explicit chainId.
* This selector relies on providerConfig which we're moving away from.
* @param {object} state - Root state
* @returns {object[]} Array of transaction objects
*/
export const getCurrentNetworkTransactions = (state) => {
const providerConfig = getProviderConfigSafe(state);
if (!providerConfig?.chainId) {
return EMPTY_ARRAY;
}
return getTransactionsByChainId(state, providerConfig.chainId);
};
export const incomingTxListSelectorAllChains = createDeepEqualSelector(
(state) => {
const allNetworkTransactions = getTransactions(state);
const { address: selectedAddress } = getSelectedInternalAccount(state);
return allNetworkTransactions.filter(
(tx) =>
tx.type === TransactionType.incoming &&
tx.txParams.to === selectedAddress,
);
},
(transactions) => transactions,
);
export const getApprovedAndSignedTransactions = createDeepEqualSelector(
(state) => {
// Fetch transactions across all networks to address a nonce management limitation.
// This issue arises when a pending transaction exists on one network, and the user initiates another transaction on a different network.
const transactions = getTransactions(state);
return transactions.filter((transaction) =>
[TransactionStatus.approved, TransactionStatus.signed].includes(
transaction.status,
),
);
},
(transactions) => transactions,
);
export const incomingTxListSelector = createDeepEqualSelector(
(state) => {
const currentNetworkTransactions = getCurrentNetworkTransactions(state);
const { address: selectedAddress } = getSelectedInternalAccount(state);
return currentNetworkTransactions.filter(
(tx) =>
tx.type === TransactionType.incoming &&
tx.txParams.to === selectedAddress,
);
},
(transactions) => transactions,
);
export const unapprovedPersonalMsgsSelector = (state) =>
state.metamask.unapprovedPersonalMsgs;
export const unapprovedDecryptMsgsSelector = (state) =>
state.metamask.unapprovedDecryptMsgs;
export const unapprovedEncryptionPublicKeyMsgsSelector = (state) =>
state.metamask.unapprovedEncryptionPublicKeyMsgs;
export const unapprovedTypedMessagesSelector = (state) =>
state.metamask.unapprovedTypedMessages;
// Memoized to prevent new array creation on every render
export const smartTransactionsListSelector = createSelector(
getSelectedInternalAccount,
(state) => state.metamask.smartTransactionsState?.smartTransactions,
getCurrentChainId,
(selectedInternalAccount, smartTransactions, chainId) => {
// The statuses listed below are allowed in the Activity list for Smart Swaps.
// SUCCESS and REVERTED statuses are excluded because smart transactions with
// those statuses are already in the regular transaction list.
// TODO: When Swaps and non-Swaps transactions are treated the same,
// we will only allow the PENDING smart transaction status in the Activity list.
const allowedSwapsSmartTransactionStatusesForActivityList = [
SmartTransactionStatuses.PENDING,
SmartTransactionStatuses.UNKNOWN,
SmartTransactionStatuses.RESOLVED,
SmartTransactionStatuses.CANCELLED,
];
const selectedAddress = selectedInternalAccount?.address;
const chainSmartTransactions = smartTransactions?.[chainId];
if (!chainSmartTransactions?.length) {
return EMPTY_ARRAY;
}
return chainSmartTransactions
.filter((smartTransaction) => {
if (
smartTransaction.txParams?.from !== selectedAddress ||
smartTransaction.confirmed
) {
return false;
}
// If a swap or non-swap smart transaction is pending, we want to show it in the Activity list.
if (smartTransaction.status === SmartTransactionStatuses.PENDING) {
return true;
}
// In the future we should have the same behavior for Swaps and non-Swaps transactions.
// For that we need to submit Smart Swaps via the TransactionController as we do for
// non-Swaps Smart Transactions.
return (
(smartTransaction.type === TransactionType.swap ||
smartTransaction.type === TransactionType.swapApproval) &&
allowedSwapsSmartTransactionStatusesForActivityList.includes(
smartTransaction.status,
)
);
})
.map((stx) => ({
...stx,
isSmartTransaction: true,
status: stx.status?.startsWith('cancelled')
? SmartTransactionStatus.cancelled
: stx.status,
}));
},
);
export const selectedAddressTxListSelectorAllChain = createSelector(
getSelectedInternalAccount,
getTransactions,
smartTransactionsListSelector,
(selectedInternalAccount, transactions = [], smTransactions = []) => {
return transactions
.filter(
({ txParams }) => txParams.from === selectedInternalAccount.address,
)
.filter(({ type }) => !EXCLUDED_TRANSACTION_TYPES.has(type))
.concat(smTransactions);
},
);
export const selectedAddressTxListSelector = createSelector(
getSelectedInternalAccount,
getCurrentNetworkTransactions,
smartTransactionsListSelector,
(selectedInternalAccount, transactions = [], smTransactions = []) => {
return transactions
.filter(
({ txParams }) => txParams.from === selectedInternalAccount.address,
)
.filter(({ type }) => !EXCLUDED_TRANSACTION_TYPES.has(type))
.concat(smTransactions);
},
);
export const unapprovedMessagesSelector = createSelector(
unapprovedPersonalMsgsSelector,
unapprovedDecryptMsgsSelector,
unapprovedEncryptionPublicKeyMsgsSelector,
unapprovedTypedMessagesSelector,
getCurrentChainId,
(
unapprovedPersonalMsgs = {},
unapprovedDecryptMsgs = {},
unapprovedEncryptionPublicKeyMsgs = {},
unapprovedTypedMessages = {},
chainId,
) =>
txHelper(
{},
unapprovedPersonalMsgs,
unapprovedDecryptMsgs,
unapprovedEncryptionPublicKeyMsgs,
unapprovedTypedMessages,
chainId,
) || [],
);
export const transactionSubSelectorAllChains = createSelector(
unapprovedMessagesSelector,
incomingTxListSelectorAllChains,
(unapprovedMessages = [], incomingTxList = []) => {
return unapprovedMessages.concat(incomingTxList);
},
);
export const transactionSubSelector = createSelector(
unapprovedMessagesSelector,
incomingTxListSelector,
(unapprovedMessages = [], incomingTxList = []) => {
return unapprovedMessages.concat(incomingTxList);
},
);
export const transactionsSelector = createSelector(
transactionSubSelector,
selectedAddressTxListSelector,
(subSelectorTxList = [], selectedAddressTxList = []) => {
const txsToRender = selectedAddressTxList.concat(subSelectorTxList);
return [...txsToRender].sort((a, b) => b.time - a.time);
},
);
export const transactionsSelectorAllChains = createSelector(
transactionSubSelectorAllChains,
selectedAddressTxListSelectorAllChain,
(subSelectorTxList = [], selectedAddressTxList = []) => {
const txsToRender = selectedAddressTxList.concat(subSelectorTxList);
return [...txsToRender].sort((a, b) => b.time - a.time);
},
);
/**
* @name insertOrderedNonce
* @private
* @description Inserts (mutates) a nonce into an array of ordered nonces, sorted in ascending
* order.
* @param {string[]} nonces - Array of nonce strings in hex
* @param {string} nonceToInsert - Nonce string in hex to be inserted into the array of nonces.
*/
const insertOrderedNonce = (nonces, nonceToInsert) => {
let insertIndex = nonces.length;
for (let i = 0; i < nonces.length; i++) {
const nonce = nonces[i];
if (
Number(hexToDecimal(nonce.split('-')[0])) >
Number(hexToDecimal(nonceToInsert.split('-')[0]))
) {
insertIndex = i;
break;
}
}
nonces.splice(insertIndex, 0, nonceToInsert);
};
/**
* @name insertTransactionByTime
* @private
* @description Inserts (mutates) a transaction object into an array of ordered transactions, sorted
* in ascending order by time.
* @param {object[]} transactions - Array of transaction objects.
* @param {object} transaction - Transaction object to be inserted into the array of transactions.
*/
const insertTransactionByTime = (transactions, transaction) => {
const { time } = transaction;
let insertIndex = transactions.length;
for (let i = 0; i < transactions.length; i++) {
const tx = transactions[i];
if (tx.time > time) {
insertIndex = i;
break;
}
}
transactions.splice(insertIndex, 0, transaction);
};
/**
* Contains transactions and properties associated with those transactions of the same nonce.
*
* @typedef {object} transactionGroup
* @property {string} nonce - The nonce that the transactions within this transactionGroup share.
* @property {object[]} transactions - An array of transaction (txMeta) objects.
* @property {object} initialTransaction - The transaction (txMeta) with the lowest "time".
* @property {object} primaryTransaction - Either the latest transaction or the confirmed
* transaction.
* @property {boolean} hasRetried - True if a transaction in the group was a retry transaction.
* @property {boolean} hasCancelled - True if a transaction in the group was a cancel transaction.
*/
/**
* @name insertTransactionGroupByTime
* @private
* @description Inserts (mutates) a transactionGroup object into an array of ordered
* transactionGroups, sorted in ascending order by nonce.
* @param {transactionGroup[]} transactionGroups - Array of transactionGroup objects.
* @param {transactionGroup} transactionGroup - transactionGroup object to be inserted into the
* array of transactionGroups.
*/
const insertTransactionGroupByTime = (transactionGroups, transactionGroup) => {
const { primaryTransaction: { time: groupToInsertTime } = {} } =
transactionGroup;
let insertIndex = transactionGroups.length;
for (let i = 0; i < transactionGroups.length; i++) {
const txGroup = transactionGroups[i];
const { primaryTransaction: { time } = {} } = txGroup;
if (time > groupToInsertTime) {
insertIndex = i;
break;
}
}
transactionGroups.splice(insertIndex, 0, transactionGroup);
};
/**
* @name mergeNonNonceTransactionGroups
* @private
* @description Inserts (mutates) transactionGroups that are not to be ordered by nonce into an array
* of nonce-ordered transactionGroups by time.
* @param {transactionGroup[]} orderedTransactionGroups - Array of transactionGroups ordered by
* nonce.
* @param {transactionGroup[]} nonNonceTransactionGroups - Array of transactionGroups not intended to be ordered by nonce,
* but intended to be ordered by timestamp
*/
const mergeNonNonceTransactionGroups = (
orderedTransactionGroups,
nonNonceTransactionGroups,
) => {
nonNonceTransactionGroups.forEach((transactionGroup) => {
insertTransactionGroupByTime(orderedTransactionGroups, transactionGroup);
});
};
export const groupAndSortTransactionsByNonce = (transactions) => {
const unapprovedTransactionGroups = [];
const incomingTransactionGroups = [];
const orderedNonces = [];
const nonceToTransactionsMap = {};
const INVALID_INITIAL_TRANSACTION_TYPES = [
TransactionType.cancel,
TransactionType.retry,
];
transactions.forEach((transaction) => {
const {
networkClientId,
txParams: { nonce } = {},
status,
type,
time: txTime,
txReceipt,
} = transaction;
const nonceNetworkKey = `${nonce}-${networkClientId}`;
// Don't group transactions by nonce if:
// 1. Tx nonce is undefined
// 2. Tx is incoming (deposit)
const shouldNotBeGrouped =
typeof nonce === 'undefined' || type === TransactionType.incoming;
if (shouldNotBeGrouped) {
const transactionGroup = {
transactions: [transaction],
initialTransaction: transaction,
primaryTransaction: transaction,
hasRetried: false,
hasCancelled: false,
nonce,
};
if (type === TransactionType.incoming) {
incomingTransactionGroups.push(transactionGroup);
} else {
insertTransactionGroupByTime(
unapprovedTransactionGroups,
transactionGroup,
);
}
} else if (nonceNetworkKey in nonceToTransactionsMap) {
const nonceProps = nonceToTransactionsMap[nonceNetworkKey];
insertTransactionByTime(nonceProps.transactions, transaction);
const {
primaryTransaction: { time: primaryTxTime = 0 } = {},
initialTransaction: { time: initialTxTime = 0 } = {},
} = nonceProps;
const currentTransaction = {
// A on-chain failure means the current transaction was submitted and
// considered for inclusion in a block but something prevented it
// from being included, such as slippage on gas prices and conversion
// when doing a swap. These transactions will have a '0x0' value in
// the txReceipt.status field.
isOnChainFailure: txReceipt?.status === '0x0',
// Another type of failure is a "off chain" or "network" failure,
// where the error occurs on the JSON RPC call to the network client
// (Like Infura). These transactions are never broadcast for
// inclusion and the nonce associated with them is not consumed. When
// this occurs the next transaction will have the same nonce as the
// current, failed transaction. A failed on chain transaction will
// not have the FAILED status although it should (future TODO: add a
// new FAILED_ON_CHAIN) status. I use the word "Ephemeral" here
// because a failed transaction that does not get broadcast is not
// known outside of the user's local MetaMask and the nonce
// associated will be applied to the next.
isEphemeral:
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
// it lacks information on whether it's a simple send, token transfer,
// etc.
isRetryOrCancel: INVALID_INITIAL_TRANSACTION_TYPES.includes(type),
// Primary transactions usually are the latest transaction by time,
// but not always. This value shows whether this transaction occurred
// after the current primary.
occurredAfterPrimary: txTime > primaryTxTime,
// Priority Statuses are those that are either already confirmed
// on-chain, submitted to the network, or waiting for user approval.
// These statuses typically indicate a transaction that needs to have
// its status reflected in the UI.
hasPriorityStatus: status in PRIORITY_STATUS_HASH,
// 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 === 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.
occurredBeforeInitial: txTime < initialTxTime,
// We only allow users to retry 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 retry.
isValidRetry:
type === TransactionType.retry &&
(status in PRIORITY_STATUS_HASH ||
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 === TransactionType.cancel &&
(status in PRIORITY_STATUS_HASH ||
status === TransactionStatus.dropped),
eligibleForInitial:
!INVALID_INITIAL_TRANSACTION_TYPES.includes(type) &&
status !== TransactionStatus.failed,
shouldBePrimary:
status === TransactionStatus.confirmed || txReceipt?.status === '0x0',
};
const previousPrimaryTransaction = {
isEphemeral:
nonceProps.primaryTransaction.status === TransactionStatus.failed &&
nonceProps.primaryTransaction?.txReceipt?.status !== '0x0',
};
const previousInitialTransaction = {
isEphemeral:
nonceProps.initialTransaction.status === TransactionStatus.failed &&
nonceProps.initialTransaction.txReceipt?.status !== '0x0',
};
if (
currentTransaction.shouldBePrimary ||
previousPrimaryTransaction.isEphemeral ||
(currentTransaction.occurredAfterPrimary &&
currentTransaction.hasPriorityStatus)
) {
nonceProps.primaryTransaction = transaction;
}
if (
(currentTransaction.occurredBeforeInitial &&
currentTransaction.eligibleForInitial) ||
(previousInitialTransaction.isEphemeral &&
currentTransaction.eligibleForInitial)
) {
nonceProps.initialTransaction = transaction;
}
if (currentTransaction.isValidRetry) {
nonceProps.hasRetried = true;
}
if (currentTransaction.isValidCancel) {
nonceProps.hasCancelled = true;
}
} else {
nonceToTransactionsMap[nonceNetworkKey] = {
nonce,
transactions: [transaction],
initialTransaction: transaction,
primaryTransaction: transaction,
hasRetried:
type === TransactionType.retry &&
(status in PRIORITY_STATUS_HASH ||
status === TransactionStatus.dropped),
hasCancelled:
type === TransactionType.cancel &&
(status in PRIORITY_STATUS_HASH ||
status === TransactionStatus.dropped),
};
insertOrderedNonce(orderedNonces, nonceNetworkKey);
}
});
const orderedTransactionGroups = orderedNonces.map(
(nonce) => nonceToTransactionsMap[nonce],
);
mergeNonNonceTransactionGroups(
orderedTransactionGroups,
incomingTransactionGroups,
);
return unapprovedTransactionGroups
.concat(orderedTransactionGroups)
.map((txGroup) => {
if (
INVALID_INITIAL_TRANSACTION_TYPES.includes(
txGroup.initialTransaction?.type,
)
) {
const nonRetryOrCancel = txGroup.transactions.find(
(tx) => !INVALID_INITIAL_TRANSACTION_TYPES.includes(tx.type),
);
if (nonRetryOrCancel) {
return { ...txGroup, initialTransaction: nonRetryOrCancel };
}
}
return txGroup;
});
};
/**
* @name nonceSortedTransactionsSelector
* @description Returns an array of transactionGroups sorted by nonce in ascending order.
* @returns {transactionGroup[]}
*/
export const nonceSortedTransactionsSelector = createSelector(
transactionsSelector,
(transactions = []) => groupAndSortTransactionsByNonce(transactions),
);
/**
* @name nonceSortedTransactionsSelectorAllChains
* @description Returns an array of transactionGroups sorted by nonce in ascending order.
* @returns {transactionGroup[]}
*/
export const nonceSortedTransactionsSelectorAllChains = createSelector(
transactionsSelectorAllChains,
(transactions = []) => groupAndSortTransactionsByNonce(transactions),
);
/**
* @name nonceSortedPendingTransactionsSelectorAllChains
* @description Returns an array of transactionGroups where transactions are still pending sorted by
* nonce in descending order for all chains.
* @returns {transactionGroup[]}
*/
export const nonceSortedPendingTransactionsSelectorAllChains = createSelector(
nonceSortedTransactionsSelectorAllChains,
(transactions = []) =>
transactions.filter(
({ primaryTransaction }) =>
primaryTransaction.status in PENDING_STATUS_HASH,
),
);
/**
* @name nonceSortedCompletedTransactionsSelectorAllChains
* @description Returns an array of transactionGroups where transactions are confirmed sorted by
* nonce in descending order for all chains.
* @returns {transactionGroup[]}
*/
export const nonceSortedCompletedTransactionsSelectorAllChains = createSelector(
nonceSortedTransactionsSelectorAllChains,
(transactions = []) =>
transactions
.filter(
({ primaryTransaction }) =>
!(primaryTransaction.status in PENDING_STATUS_HASH),
)
.reverse(),
);
/**
* @name nonceSortedPendingTransactionsSelector
* @description Returns an array of transactionGroups where transactions are still pending sorted by
* nonce in descending order.
* @returns {transactionGroup[]}
*/
export const nonceSortedPendingTransactionsSelector = createSelector(
nonceSortedTransactionsSelector,
(transactions = []) =>
transactions.filter(
({ primaryTransaction }) =>
primaryTransaction.status in PENDING_STATUS_HASH,
),
);
/**
* @name nonceSortedCompletedTransactionsSelector
* @description Returns an array of transactionGroups where transactions are confirmed sorted by
* nonce in descending order.
* @returns {transactionGroup[]}
*/
export const nonceSortedCompletedTransactionsSelector = createSelector(
nonceSortedTransactionsSelector,
(transactions = []) =>
transactions
.filter(
({ primaryTransaction }) =>
!(primaryTransaction.status in PENDING_STATUS_HASH),
)
.reverse(),
);
export const submittedPendingTransactionsSelector = createSelector(
transactionsSelector,
(transactions = []) =>
transactions.filter(
(transaction) => transaction.status === TransactionStatus.submitted,
),
);
const TRANSACTION_APPROVAL_TYPES = [
ApprovalType.EthDecrypt,
ApprovalType.EthGetEncryptionPublicKey,
ApprovalType.EthSignTypedData,
ApprovalType.PersonalSign,
];
export function hasTransactionPendingApprovals(state) {
const unapprovedTxRequests = getApprovalRequestsByType(
state,
ApprovalType.Transaction,
);
return (
unapprovedTxRequests.length > 0 ||
hasPendingApprovals(state, TRANSACTION_APPROVAL_TYPES)
);
}
export function selectTransactionMetadata(state, transactionId) {
return state.metamask.transactions.find(
(transaction) => transaction.id === transactionId,
);
}
export const selectTransactionSender = createSelector(
(state, transactionId) => selectTransactionMetadata(state, transactionId),
(transaction) => transaction?.txParams?.from,
);
/**
* Creates a map of unapproved transactions indexed by transaction ID.
*
* @param {object[]} transactions - Array of transaction objects
* @returns {Record<string, object>} Object with transaction IDs as keys
*/
function createUnapprovedTransactionsMap(transactions) {
if (!transactions?.length) {
return EMPTY_OBJECT;
}
const result = {};
for (const transaction of transactions) {
if (transaction.status === TransactionStatus.unapproved) {
result[transaction.id] = transaction;
}
}
return Object.keys(result).length > 0 ? result : EMPTY_OBJECT;
}
// Safe wrapper that prevents crashes when provider config is unavailable
function getProviderConfigSafe(state) {
try {
return getProviderConfig(state);
} catch {
return null;
}
}
const selectIsTransactionTypeRedesigned = createSelector(
(state, transactionId) =>
selectTransactionMetadata(state, transactionId)?.type,
(transactionType) => isCorrectDeveloperTransactionType(transactionType),
);
export const selectIsRedesignedConfirmationType = createSelector(
(state, paramsId) => {
const id = paramsId ?? oldestPendingConfirmationSelector(state)?.id;
return selectIsTransactionTypeRedesigned(state, id);
},
(state, paramsId) => {
const id = paramsId ?? oldestPendingConfirmationSelector(state)?.id;
return getPendingApprovals(state).find((a) => a.id === id)?.type;
},
(isRedesignedTx, approvalType) =>
isRedesignedTx || isCorrectSignatureApprovalType(approvalType),
);