Skip to content

Instantly share code, notes, and snippets.

@SteveHere
Created March 22, 2023 03:08
Show Gist options
  • Save SteveHere/236b0a8b3d627d1f4a19ce20edd4adeb to your computer and use it in GitHub Desktop.
Save SteveHere/236b0a8b3d627d1f4a19ce20edd4adeb to your computer and use it in GitHub Desktop.
Tampermonkey script for Polygonscan's gas tracker graph
// ==UserScript==
// @name Logarithmic X-axis
// @version 0.1
// @description Logarithmic X-axis for Polygonscan's gas tracker graph
// @match https://polygonscan.com/gastracker*
// @author SteveHere
// @grant none
// ==/UserScript==
const lower_bound = 25, upper_bound = 1000;
setTimeout(()=>{
const span = ({id, text}={}) => Object.assign(document.createElement('span'), { ...(id && {id: id}), ...(text && {innerText: text}) });
const div = ({style}={}) => Object.assign(document.createElement('div'), { ...(style && {style: style}) });
let not_included_lt = div(), not_included_gt = div({ style: 'margin-top: 1em;' });
not_included_lt.append( span({text: `Omitted TXs < ${lower_bound} gwei: `}), span({id: 'omittedTxsLT'}) );
not_included_gt.append( span({text: `Omitted TXs > ${upper_bound} gwei: `}), span({id: 'omittedTxsGT'}) );
document.getElementById('containerchart').parentElement.append(not_included_lt, not_included_gt);
window.txSort = x => x.sort((a, b) => a[0] - b[0]);
window.txCount = x => x.reduce((acc, [a, b])=> acc + b, 0);
window.asyncRefreshChart = async function() {
const response = await fetch('https://gpoly.blockscan.com/gasapi.ashx?apikey=key&method=pendingpooltxgweidata');
const data = await response.json();
if (data.status === '1') {
const elevationData = JSON.parse(data.result.data);
{
const [pendingCountElement, avgTxnsPerBlockElement, avgNetworkUtilizationElement, lastUpdatedElement] =
['pendingcount', 'avgtxnsperblock', 'avgnetworkutilization', 'lastupdated'].map(id => document.getElementById(id));
const today = new Date(), options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' };
[pendingCountElement.innerHTML, avgTxnsPerBlockElement.innerHTML, avgNetworkUtilizationElement.innerHTML, lastUpdatedElement.innerHTML] = [
` <b>${data.result.pendingcount} Txns</b>`,
`<b>${data.result.avgtxnsperblock} Txns</b>`,
`<b>${(data.result.avgnetworkutilization * 100).toFixed(2)}%</b>`,
`<b>${today.toLocaleDateString('en-UK', options)} ${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}</b>`
];
}
{
const buckets = elevationData.reduce((acc, [gas, txs]) => {
acc[2 - (gas < lower_bound) - (gas <= upper_bound)].push([gas, txs])
return acc
}, [[], [], []]);
chart1.series[0].update({ data: window.txSort(buckets[1]) }, false);
chart1.redraw();
(range => {
document.getElementById('omittedTxsLT').innerText = (x=>`${window.txCount(x)} - ${JSON.stringify(x.map(([a,b])=>[`${a} - ${a+range}`, b]))}`)(
window.txSort([...buckets[0].reduce((acc, [gas, txs]) => (k=>acc.set(k, (acc.get(k) || 0) + txs))(gas - gas % range), new Map()).entries()])
);
})(2)
document.getElementById('omittedTxsGT').innerText = (x=>`${window.txCount(x)} - ${JSON.stringify(x)}`)( window.txSort(buckets[2]) );
}
} else { console.log('Error!'); }
}
window.asyncGuard = false;
window.refreshchartData = function() {
if (window.asyncGuard){ console.log("Still refreshing"); return; }
window.asyncGuard = true;
try { window.asyncRefreshChart(); } catch (error) { console.log('Error!', error); }
window.asyncGuard = false;
}
Highcharts.chart('containerchart', {
chart: { type: 'column' },
title: { text: 'Pending Transaction Pool (Sorted by Gas Price)' },
credits: { enabled: false },
xAxis: {
type: "logarithmic",
minRange: 1,
labels: { format: '{value} Gwei' },
title: { text: 'GasPrice' },
accessibility: { rangeDescription: 'Gas Prices in Gwei for the interval' },
},
yAxis: {
startOnTick: true, endOnTick: false,
maxPadding: 0.35, min: 0,
title: { text: null },
labels: { format: '{value} Tx' },
accessibility: {
description: 'Transactions',
rangeDescription: 'Range: Number of Transactions'
}
},
tooltip: {
headerFormat: 'GasPrice: {point.x:.1f} Gwei<br>',
pointFormat: '{point.y} txn ',
shared: true
},
legend: { enabled: false },
plotOptions: { series: { minPointLength: 10, pointWidth: 1 } },
series: [{
data: elevationData.filter(([a,b])=>a >= 1).sort((a, b) => a[0] - b[0]),
fillOpacity: 0.5,
name: 'GasPrices',
marker: { enabled: false },
threshold: null, turboThreshold: 10000,
point: {
events: {
mouseOver: function() {
var point = this, chart = point.series.chart, r = chart.renderer, space = 9;
chart.group = r.g('group').attr({
zIndex: 4
}).add()
r.rect(point.plotX + chart.plotLeft, chart.plotTop, 1, point.plotY - space).attr({
fill: 'gray'
}).add(chart.group)
r.rect(point.plotX + chart.plotLeft, point.plotY + chart.plotTop + space, 1, chart.plotSizeY - point.plotY - space).attr({
fill: 'gray'
}).add(chart.group)
// Translate the crosshair (-50%, 0) to center
chart.group.translate(-1, 0)
},
mouseOut: function() {
var chart = this.series.chart;
// Destroy the previous crosshair when mouseOut over the point
if (chart.group) { chart.group.destroy() }
}
}
},
}]
});
var chart1 = $('#containerchart').highcharts();
console.log("Changed to log-scale");
}, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment