Skip to content

Instantly share code, notes, and snippets.

@cheekybastard
Created April 2, 2023 04:07
Show Gist options
  • Save cheekybastard/4db854ea6db7af89ae04b7cf6ebbcb72 to your computer and use it in GitHub Desktop.
Save cheekybastard/4db854ea6db7af89ae04b7cf6ebbcb72 to your computer and use it in GitHub Desktop.

Revisions

  1. cheekybastard created this gist Apr 2, 2023.
    48 changes: 48 additions & 0 deletions polygon_blocktime.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    // https://rxjs.dev/api
    const { from, timer } = require('rxjs');
    const { last, map, catchError, switchMap } = require('rxjs/operators');
    // https://danfo.jsdata.org/
    const dfd = require('danfojs-node');

    let latestBlocktime = 2.2;

    function getBlocktime() {
    return from(dfd.readCSV('https://polygonscan.com/chart/blocktime?output=csv')).pipe(
    catchError((error) => {
    console.error(error);
    return from(Promise.resolve(null));
    }),
    map((df) => {
    const value = parseFloat(df['Value'].tail(1).values[0]);
    if (isNaN(value)) {
    throw new Error('Latest value is NaN');
    }
    latestBlocktime = value;
    return latestBlocktime;
    }),
    last()
    );
    }

    function main() {
    // update every 5mins
    timer(0, 5 * 60 * 1000)
    .pipe(switchMap(() => getBlocktime()))
    .subscribe({
    next: (latestFloatValue) => {
    console.log('return val:', latestFloatValue);
    console.log('global val:', latestBlocktime);
    },
    error: (error) => {
    console.error(error);
    },
    complete: () => {
    console.log('Done!');
    },
    });
    }

    main();

    // Export latestBlocktime as a global variable
    global.latestBlocktime = () => latestBlocktime;