1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-26 20:39:08 +01:00
metamask-extension/ui/hooks/gasFeeInput/useMaxPriorityFeePerGasInput.js
2022-12-09 00:07:06 +05:30

83 lines
2.4 KiB
JavaScript

import { useSelector } from 'react-redux';
import { useEffect, useState } from 'react';
import { checkNetworkAndAccountSupports1559 } from '../../selectors';
import { isLegacyTransaction } from '../../helpers/utils/transactions.util';
import { hexWEIToDecGWEI } from '../../../shared/lib/transactions-controller-utils';
import { feeParamsAreCustom, getGasFeeEstimate } from './utils';
const getMaxPriorityFeePerGasFromTransaction = (
transaction,
gasFeeEstimates,
) => {
if (gasFeeEstimates?.[transaction?.userFeeLevel]) {
return gasFeeEstimates[transaction.userFeeLevel]
.suggestedMaxPriorityFeePerGas;
}
const { maxPriorityFeePerGas, maxFeePerGas, gasPrice } =
transaction?.txParams || {};
return Number(
hexWEIToDecGWEI(maxPriorityFeePerGas || maxFeePerGas || gasPrice),
);
};
/**
* @typedef {object} MaxPriorityFeePerGasInputReturnType
* @property {DecGweiString} [maxPriorityFeePerGas] - the maxPriorityFeePerGas
* input value.
* @property {(DecGweiString) => void} setMaxPriorityFeePerGas - state setter
* method to update the maxPriorityFeePerGas.
*/
/**
* @param options
* @param options.estimateToUse
* @param options.gasEstimateType
* @param options.gasFeeEstimates
* @param options.transaction
* @returns {MaxPriorityFeePerGasInputReturnType}
*/
export function useMaxPriorityFeePerGasInput({
estimateToUse,
gasEstimateType,
gasFeeEstimates,
transaction,
}) {
const supportsEIP1559 =
useSelector(checkNetworkAndAccountSupports1559) &&
!isLegacyTransaction(transaction?.txParams);
const initialMaxPriorityFeePerGas = supportsEIP1559
? getMaxPriorityFeePerGasFromTransaction(transaction, gasFeeEstimates)
: 0;
const [maxPriorityFeePerGas, setMaxPriorityFeePerGas] = useState(() => {
if (initialMaxPriorityFeePerGas && feeParamsAreCustom(transaction)) {
return initialMaxPriorityFeePerGas;
}
return null;
});
useEffect(() => {
if (supportsEIP1559 && initialMaxPriorityFeePerGas) {
setMaxPriorityFeePerGas(initialMaxPriorityFeePerGas);
}
}, [initialMaxPriorityFeePerGas, setMaxPriorityFeePerGas, supportsEIP1559]);
const maxPriorityFeePerGasToUse =
maxPriorityFeePerGas ??
getGasFeeEstimate(
'suggestedMaxPriorityFeePerGas',
gasFeeEstimates,
gasEstimateType,
estimateToUse,
initialMaxPriorityFeePerGas || 0,
);
return {
maxPriorityFeePerGas: maxPriorityFeePerGasToUse,
setMaxPriorityFeePerGas,
};
}