2021-02-04 19:15:23 +01:00
|
|
|
import { useEffect, useState } from 'react';
|
2021-06-10 21:27:03 +02:00
|
|
|
import { SECOND } from '../../shared/constants/time';
|
2020-05-26 22:49:11 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Evaluates whether the transaction is eligible to be sped up, and registers
|
|
|
|
* an effect to check the logic again after the transaction has surpassed 5 seconds
|
|
|
|
* of queue time.
|
2022-01-07 16:57:33 +01:00
|
|
|
*
|
2022-08-24 20:57:47 +02:00
|
|
|
* @param {object} transactionGroup - the transaction group to check against
|
2020-05-26 22:49:11 +02:00
|
|
|
* @param {boolean} isEarliestNonce - Whether this group is currently the earliest nonce
|
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
export function useShouldShowSpeedUp(transactionGroup, isEarliestNonce) {
|
2021-02-04 19:15:23 +01:00
|
|
|
const { transactions, hasRetried } = transactionGroup;
|
|
|
|
const [earliestTransaction = {}] = transactions;
|
|
|
|
const { submittedTime } = earliestTransaction;
|
2020-05-26 22:49:11 +02:00
|
|
|
const [speedUpEnabled, setSpeedUpEnabled] = useState(() => {
|
2021-02-04 19:15:23 +01:00
|
|
|
return Date.now() - submittedTime > 5000 && isEarliestNonce && !hasRetried;
|
|
|
|
});
|
2020-05-26 22:49:11 +02:00
|
|
|
useEffect(() => {
|
|
|
|
// because this hook is optimized to only run on changes we have to
|
|
|
|
// key into the changing time delta between submittedTime and now()
|
|
|
|
// and if the status of the transaction changes based on that difference
|
|
|
|
// trigger a setState call to tell react to re-render. This effect will
|
|
|
|
// also immediately set retryEnabled and not create a timeout if the
|
|
|
|
// condition is already met. This effect will run anytime the variables
|
|
|
|
// for determining enabled status change
|
2021-02-04 19:15:23 +01:00
|
|
|
let timeoutId;
|
2020-05-26 22:49:11 +02:00
|
|
|
if (!hasRetried && isEarliestNonce && !speedUpEnabled) {
|
2021-06-10 21:27:03 +02:00
|
|
|
if (Date.now() - submittedTime > SECOND * 5) {
|
2021-02-04 19:15:23 +01:00
|
|
|
setSpeedUpEnabled(true);
|
2020-05-26 22:49:11 +02:00
|
|
|
} else {
|
|
|
|
timeoutId = setTimeout(() => {
|
2021-02-04 19:15:23 +01:00
|
|
|
setSpeedUpEnabled(true);
|
|
|
|
clearTimeout(timeoutId);
|
|
|
|
}, 5001 - (Date.now() - submittedTime));
|
2020-05-26 22:49:11 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// Anytime the effect is re-ran, make sure to remove a previously set timeout
|
|
|
|
// so as to avoid multiple timers potentially overlapping
|
|
|
|
return () => {
|
|
|
|
if (timeoutId) {
|
2021-02-04 19:15:23 +01:00
|
|
|
clearTimeout(timeoutId);
|
2020-05-26 22:49:11 +02:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
|
|
|
}, [submittedTime, speedUpEnabled, hasRetried, isEarliestNonce]);
|
2020-05-26 22:49:11 +02:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
return speedUpEnabled;
|
2020-05-26 22:49:11 +02:00
|
|
|
}
|