Skip to content

Instantly share code, notes, and snippets.

@arcticmatt
Last active May 1, 2022 02:05
Show Gist options
  • Save arcticmatt/35883dfb95867edaf05dc56427aa3253 to your computer and use it in GitHub Desktop.
Save arcticmatt/35883dfb95867edaf05dc56427aa3253 to your computer and use it in GitHub Desktop.
import { Connection } from "@solana/web3.js";
import { Maybe } from "types/UtilityTypes";
import arraySum from "utils/array/arraySum";
import sleepMs from "utils/sleepMs";
async function getRecentPerformanceSamples(
connection: Connection,
minutesLookback: number
) {
const recentPerfSamples = await connection.getRecentPerformanceSamples();
let stoppingIndex = recentPerfSamples.length;
let secondsSum = 0;
for (let i = 0; i < recentPerfSamples.length; i++) {
secondsSum += recentPerfSamples[i].samplePeriodSecs;
if (secondsSum >= minutesLookback * 60) {
stoppingIndex = i + 1;
break;
}
}
return recentPerfSamples.slice(0, stoppingIndex);
}
export default async function getRecentAverageTps(
connection: Connection,
minutesLookback = 10,
retries = 5
): Promise<Maybe<number>> {
for (let i = 0; i < retries; i++) {
try {
const recentPerfSamples = await getRecentPerformanceSamples(
connection,
minutesLookback
);
const tpsSamples = recentPerfSamples.map(
(perfSample) =>
perfSample.numTransactions / Math.max(perfSample.samplePeriodSecs, 1)
);
return arraySum(tpsSamples) / tpsSamples.length;
} catch {
await sleepMs(i * 1000);
continue;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment