getGasInEIP1559 method
Implementation
Future<Map<String, EIP1559Information>> getGasInEIP1559(
{int historicalBlocks = 10}) async {
final List<String> rates = ['slow', 'medium', 'fast'];
final List<Map<String, dynamic>> history = [];
final Map<String, EIP1559Information> result = {};
final Map<String, dynamic> feeHistory = await getFeeHistory(
historicalBlocks,
atBlock: const BlockNum.current(),
rewardPercentiles: [25, 50, 75],
);
for (int index = 0; index < historicalBlocks; index++) {
history.add({
'blockNumber': feeHistory['oldestBlock'] + BigInt.from(index),
'baseFeePerGas': feeHistory['baseFeePerGas'][index],
'gasUsedRatio': feeHistory['gasUsedRatio'][index],
'priorityFeePerGas': feeHistory['reward'][index],
});
}
final BlockInformation latestBlock = await getBlockInformation(
blockNumber: const BlockNum.current().toString(),
);
final BigInt baseFee = latestBlock.baseFeePerGas!.getInWei;
for (int index = 0; index < rates.length; index++) {
final List<BigInt> allPriorityFee = history.map<BigInt>((e) {
return e['priorityFeePerGas'][index] as BigInt;
}).toList();
final BigInt priorityFee = allPriorityFee.max;
final BigInt estimatedGas = BigInt.from(
0.9 * baseFee.toDouble() + priorityFee.toDouble(),
);
final BigInt maxFee = BigInt.from(1.5 * estimatedGas.toDouble());
if (priorityFee >= maxFee || priorityFee <= BigInt.zero) {
throw Exception('Max fee must exceed the priority fee');
}
result[rates[index]] = EIP1559Information(
lastBaseFeePerGas: EtherAmount.inWei(baseFee),
maxPriorityFeePerGas: EtherAmount.inWei(priorityFee),
maxFeePerGas: EtherAmount.inWei(maxFee),
estimatedGas: estimatedGas,
);
}
return result;
}