fetchWorkingGroupsData.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import createApi from './api'
  2. import { BlockHash } from '@polkadot/types/interfaces'
  3. import { ApiPromise } from '@polkadot/api'
  4. import { WorkerJson, WorkingGroupJson, WorkingGroupsJson } from '../types'
  5. import fs from 'fs'
  6. import path from 'path'
  7. export enum WorkingGroups {
  8. Storage = 'storageWorkingGroup',
  9. Gateway = 'gatewayWorkingGroup',
  10. }
  11. // export flow
  12. async function main() {
  13. // prepare api connection
  14. const api = await createApi()
  15. const blockNumner = parseInt(process.env.AT_BLOCK_NUMBER || '')
  16. const hash = process.env.AT_BLOCK_NUMBER ? await api.rpc.chain.getBlockHash(blockNumner) : undefined
  17. const now = new Date()
  18. // get results for all relevant groups
  19. const workingGroups: WorkingGroupsJson = {
  20. STORAGE: await getWorkingGroupData(api, WorkingGroups.Storage, hash, now),
  21. GATEWAY: await getWorkingGroupData(api, WorkingGroups.Gateway, hash, now),
  22. }
  23. // output results
  24. fs.writeFileSync(path.resolve(__dirname, '../data/workingGroups.json'), JSON.stringify(workingGroups, undefined, 4))
  25. console.log(`${workingGroups.GATEWAY?.workers.length || 0} GATEWAY workers exported & saved!`)
  26. console.log(`${workingGroups.STORAGE?.workers.length || 0} STORAGE workers exported & saved!`)
  27. // disconnect api
  28. api.disconnect()
  29. }
  30. // retrieves all active workers in working group
  31. async function getWorkingGroupData(
  32. api: ApiPromise,
  33. group: WorkingGroups,
  34. hash: BlockHash | undefined,
  35. now: Date
  36. ): Promise<WorkingGroupJson> {
  37. // get working group entries
  38. const entries = await (hash ? api.query[group].workerById.entriesAt(hash) : api.query[group].workerById.entries())
  39. const workers: WorkerJson[] = []
  40. entries.forEach(([storageKey]) => {
  41. // prepare workerId
  42. const workerId = storageKey.args[0]
  43. // add record
  44. workers.push({
  45. workerId: workerId.toString(),
  46. // set time of running this script as createdAt
  47. createdAt: now.getTime(),
  48. })
  49. })
  50. return { workers }
  51. }
  52. main()
  53. .then(() => process.exit())
  54. .catch(console.error)