Skip to content

Instantly share code, notes, and snippets.

@WietseWind
Last active July 4, 2022 23:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WietseWind/a246c123393e7a97f25df4e9d2270335 to your computer and use it in GitHub Desktop.
Save WietseWind/a246c123393e7a97f25df4e9d2270335 to your computer and use it in GitHub Desktop.
Fun with Generator Functions. First backfill XRPL Ledgers, then keep up with current Ledgers closing, fall back to backfilling if needed to sync gaps.
import { XrplClient } from 'xrpl-client'
const config = { backfillLedgers: 20, lastLedger: null }
const client = new XrplClient(['wss://xrplcluster.com'])
await client.ready()
config.lastLedger = client.getState().ledger.last - config.backfillLedgers
function getLedgerTransactions(ledger_index) {
return client.send({ command: 'ledger', transactions: true, expand: true, ledger_index })
}
async function backfill () {
console.log('Strategy: backfill')
return getLedgerTransactions(config.lastLedger)
}
async function stayUpToDate () {
return new Promise(resolve => {
console.log('Strategy: stay up to date')
client.once('ledger', l => resolve(getLedgerTransactions(l.ledger_index)))
})
}
// Notice the *. Yay, this is a generator.
async function* ledgerToProcess () {
/**
* This will backfill if needed, and live watch the ledger for newly closed ledgers. If live
* watch skips ledgers, the backfill will take care of it again. Ledgers will come in ordered.
*/
while (true) {
const newLedger = config.lastLedger <= client.getState().ledger.last
? await backfill()
: await stayUpToDate()
/**
* Check for a gap
*/
yield newLedger?.ledger_index > config.lastLedger + 1
? backfill()
: newLedger
config.lastLedger++
}
}
for await (const l of ledgerToProcess()) {
const index = Number(l.ledger.seqNum)
console.log(index)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment