You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.9 KiB
47 lines
1.9 KiB
4 years ago
|
import { useEffect, useState } from 'react';
|
||
5 years ago
|
|
||
|
/**
|
||
|
* 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.
|
||
|
* @param {Object} transactionGroup - the transaction group to check against
|
||
|
* @param {boolean} isEarliestNonce - Whether this group is currently the earliest nonce
|
||
|
*/
|
||
4 years ago
|
export function useShouldShowSpeedUp(transactionGroup, isEarliestNonce) {
|
||
4 years ago
|
const { transactions, hasRetried } = transactionGroup;
|
||
|
const [earliestTransaction = {}] = transactions;
|
||
|
const { submittedTime } = earliestTransaction;
|
||
5 years ago
|
const [speedUpEnabled, setSpeedUpEnabled] = useState(() => {
|
||
4 years ago
|
return Date.now() - submittedTime > 5000 && isEarliestNonce && !hasRetried;
|
||
|
});
|
||
5 years ago
|
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
|
||
4 years ago
|
let timeoutId;
|
||
5 years ago
|
if (!hasRetried && isEarliestNonce && !speedUpEnabled) {
|
||
|
if (Date.now() - submittedTime > 5000) {
|
||
4 years ago
|
setSpeedUpEnabled(true);
|
||
5 years ago
|
} else {
|
||
|
timeoutId = setTimeout(() => {
|
||
4 years ago
|
setSpeedUpEnabled(true);
|
||
|
clearTimeout(timeoutId);
|
||
|
}, 5001 - (Date.now() - submittedTime));
|
||
5 years ago
|
}
|
||
|
}
|
||
|
// 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) {
|
||
4 years ago
|
clearTimeout(timeoutId);
|
||
5 years ago
|
}
|
||
4 years ago
|
};
|
||
|
}, [submittedTime, speedUpEnabled, hasRetried, isEarliestNonce]);
|
||
5 years ago
|
|
||
4 years ago
|
return speedUpEnabled;
|
||
5 years ago
|
}
|