StatisticsCollector.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. import {ApiPromise, WsProvider} from "@polkadot/api";
  2. import {types} from '@joystream/types'
  3. import {
  4. AccountId,
  5. Balance,
  6. BalanceOf,
  7. BlockNumber,
  8. EraIndex,
  9. EventRecord,
  10. Hash,
  11. Moment
  12. } from "@polkadot/types/interfaces";
  13. import {
  14. CacheEvent,
  15. Exchange,
  16. Media,
  17. MintStatistics,
  18. Statistics,
  19. ValidatorReward, WorkersInfo, Channel, SpendingProposals, Bounty
  20. } from "./types";
  21. import {Option, u32, Vec} from "@polkadot/types";
  22. import {ElectionStake, SealedVote, Seats} from "@joystream/types/council";
  23. import {Mint, MintId} from "@joystream/types/mint";
  24. import {ContentId, DataObject} from "@joystream/types/media";
  25. import Linkage from "@polkadot/types/codec/Linkage";
  26. import {PostId, ThreadId} from "@joystream/types/common";
  27. import {CategoryId} from "@joystream/types/forum";
  28. import {MemberId, Membership} from "@joystream/types/members";
  29. import {RewardRelationship, RewardRelationshipId} from "@joystream/types/recurring-rewards";
  30. import workingGroup from "@joystream/types/src/working-group/index";
  31. import {Stake} from "@joystream/types/stake";
  32. import {ChannelId} from "@joystream/types/content-working-group";
  33. import {WorkerId} from "@joystream/types/working-group";
  34. import {Entity, EntityId, PropertyType} from "@joystream/types/content-directory";
  35. import {ProposalDetails, ProposalId, WorkerOf} from "@joystream/types/augment-codec/all";
  36. import {SpendingParams} from "@joystream/types/proposals";
  37. import * as constants from "constants";
  38. const fsSync = require('fs');
  39. const fs = fsSync.promises;
  40. const parse = require('csv-parse/lib/sync');
  41. const BURN_ADDRESS = '5D5PhZQNJzcJXVBxwJxZcsutjKPqUPydrvpu6HeiBfMaeKQu';
  42. const COUNCIL_ROUND_OFFSET = 0;
  43. const PROVIDER_URL = "ws://localhost:9944";
  44. const CACHE_FOLDER = "cache";
  45. const WORKER_ID_OFFSET = 0;
  46. const VIDEO_CLASS_iD = 10;
  47. const CHANNEL_CLASS_iD = 1;
  48. export class StatisticsCollector {
  49. private api?: ApiPromise;
  50. private blocksEventsCache: Map<number, CacheEvent[]>;
  51. private statistics: Statistics;
  52. constructor() {
  53. this.blocksEventsCache = new Map<number, CacheEvent[]>();
  54. this.statistics = new Statistics();
  55. }
  56. async getStatistics(startBlock: number, endBlock: number): Promise<Statistics> {
  57. this.api = await StatisticsCollector.connectApi();
  58. let startHash = (await this.api.rpc.chain.getBlockHash(startBlock)) as Hash;
  59. let endHash = (await this.api.rpc.chain.getBlockHash(endBlock)) as Hash;
  60. this.statistics.startBlock = startBlock;
  61. this.statistics.endBlock = endBlock;
  62. this.statistics.newBlocks = endBlock - startBlock;
  63. this.statistics.percNewBlocks = StatisticsCollector.convertToPercentage(startBlock, endBlock);
  64. await this.buildBlocksEventCache(startBlock, endBlock);
  65. await this.fillBasicInfo(startHash, endHash);
  66. await this.fillTokenGenerationInfo(startBlock, endBlock, startHash, endHash);
  67. await this.fillMintsInfo(startHash, endHash);
  68. await this.fillCouncilInfo(startHash, endHash);
  69. await this.fillCouncilElectionInfo(startBlock);
  70. await this.fillValidatorInfo(startHash, endHash);
  71. await this.fillStorageProviderInfo(startBlock, endBlock, startHash, endHash);
  72. await this.fillCuratorInfo(startHash, endHash);
  73. await this.fillMembershipInfo(startHash, endHash);
  74. await this.fillMediaUploadInfo(startHash, endHash);
  75. await this.fillForumInfo(startHash, endHash);
  76. await this.api.disconnect();
  77. return this.statistics;
  78. }
  79. async getApprovedBounties() {
  80. let bountiesFilePath = __dirname + '/../bounties.csv';
  81. try {
  82. await fs.access(bountiesFilePath, constants.R_OK);
  83. } catch {
  84. throw new Error('Bounties CSV file not found');
  85. }
  86. const fileContent = await fs.readFile(bountiesFilePath);
  87. const rawBounties = parse(fileContent);
  88. rawBounties.shift();
  89. let bounties = rawBounties.map((rawBounty: any) => {
  90. return new Bounty(rawBounty[0], rawBounty[1], rawBounty[2], rawBounty[3], rawBounty[4]);
  91. });
  92. return bounties.filter((bounty: Bounty) => bounty.status == "Approved");
  93. }
  94. async getSpendingProposals() : Promise<Array<SpendingProposals>>{
  95. let spendingProposals = new Array<SpendingProposals>();
  96. for (let [key, blockEvents] of this.blocksEventsCache) {
  97. let validatorRewards = blockEvents.filter((event) => {
  98. return event.section == "staking" && event.method == "Reward";
  99. });
  100. for (let validatorReward of validatorRewards) {
  101. this.statistics.newValidatorRewards += Number(validatorReward.data[1]);
  102. }
  103. let transfers = blockEvents.filter((event) => {
  104. return event.section == "balances" && event.method == "Transfer";
  105. });
  106. for (let transfer of transfers) {
  107. let receiver = transfer.data[1] as AccountId;
  108. let amount = transfer.data[2] as Balance;
  109. if (receiver.toString() == BURN_ADDRESS) {
  110. this.statistics.newTokensBurn = Number(amount);
  111. }
  112. }
  113. let proposalEvents = blockEvents.filter((event) => {
  114. return event.section == "proposalsEngine" && event.method == "ProposalStatusUpdated";
  115. });
  116. for (let proposalEvent of proposalEvents) {
  117. let statusUpdateData = proposalEvent.data[1] as any;
  118. if (!(statusUpdateData.finalized && statusUpdateData.finalized.finalizedAt)) {
  119. continue;
  120. }
  121. let proposalId = proposalEvent.data[0] as ProposalId;
  122. let proposalDetail = await this.api.query.proposalsCodex.proposalDetailsByProposalId(proposalId) as ProposalDetails;
  123. if (!proposalDetail.isOfType("Spending")) {
  124. continue;
  125. }
  126. let spendingParams = Array.from(proposalDetail.asType("Spending") as SpendingParams);
  127. spendingProposals.push(new SpendingProposals(Number(proposalId), Number(spendingParams[0])));
  128. }
  129. }
  130. return spendingProposals;
  131. }
  132. async fillBasicInfo(startHash: Hash, endHash: Hash) {
  133. let startDate = (await this.api.query.timestamp.now.at(startHash)) as Moment;
  134. let endDate = (await this.api.query.timestamp.now.at(endHash)) as Moment;
  135. this.statistics.dateStart = new Date(startDate.toNumber()).toLocaleDateString("en-US");
  136. this.statistics.dateEnd = new Date(endDate.toNumber()).toLocaleDateString("en-US");
  137. }
  138. async fillTokenGenerationInfo(startBlock: number, endBlock: number, startHash: Hash, endHash: Hash) {
  139. this.statistics.startIssuance = (await this.api.query.balances.totalIssuance.at(startHash) as Balance).toNumber();
  140. this.statistics.endIssuance = (await this.api.query.balances.totalIssuance.at(endHash) as Balance).toNumber();
  141. this.statistics.newIssuance = this.statistics.endIssuance - this.statistics.startIssuance;
  142. this.statistics.percNewIssuance = StatisticsCollector.convertToPercentage(this.statistics.startIssuance, this.statistics.endIssuance);
  143. let bounties = await this.getApprovedBounties();
  144. let spendingProposals = await this.getSpendingProposals();
  145. this.statistics.bountiesTotalPaid = 0;
  146. for (let bounty of bounties){
  147. let bountySpendingProposal = spendingProposals.find((spendingProposal) => spendingProposal.id == bounty.proposalId);
  148. if (bountySpendingProposal){
  149. this.statistics.bountiesTotalPaid += bountySpendingProposal.spentAmount;
  150. }
  151. }
  152. this.statistics.spendingProposalsTotal = spendingProposals.reduce((n, spendingProposal) => n + spendingProposal.spentAmount, 0);
  153. let roundNrBlocks = endBlock - startBlock;
  154. this.statistics.newCouncilRewards = await this.computeCouncilReward(roundNrBlocks, endHash);
  155. this.statistics.newCouncilRewards = Number(this.statistics.newCouncilRewards.toFixed(2));
  156. this.statistics.newCuratorRewards = await this.computeCuratorsReward(roundNrBlocks, startHash, endHash);
  157. this.statistics.newCuratorRewards = Number(this.statistics.newCuratorRewards.toFixed(2));
  158. }
  159. async computeCouncilReward(roundNrBlocks: number, endHash: Hash): Promise<number> {
  160. const payoutInterval = Number((await this.api.query.council.payoutInterval.at(endHash) as Option<BlockNumber>).unwrapOr(0));
  161. const amountPerPayout = (await this.api.query.council.amountPerPayout.at(endHash) as BalanceOf).toNumber();
  162. const announcing_period = (await this.api.query.councilElection.announcingPeriod.at(endHash)) as BlockNumber;
  163. const voting_period = (await this.api.query.councilElection.votingPeriod.at(endHash)) as BlockNumber;
  164. const revealing_period = (await this.api.query.councilElection.revealingPeriod.at(endHash)) as BlockNumber;
  165. const new_term_duration = (await this.api.query.councilElection.newTermDuration.at(endHash)) as BlockNumber;
  166. const termDuration = new_term_duration.toNumber();
  167. const votingPeriod = voting_period.toNumber();
  168. const revealingPeriod = revealing_period.toNumber();
  169. const announcingPeriod = announcing_period.toNumber();
  170. const nrCouncilMembers = (await this.api.query.council.activeCouncil.at(endHash) as Seats).length
  171. const totalCouncilRewardsPerBlock = (amountPerPayout && payoutInterval)
  172. ? (amountPerPayout * nrCouncilMembers) / payoutInterval
  173. : 0;
  174. const councilTermDurationRatio = termDuration / (termDuration + votingPeriod + revealingPeriod + announcingPeriod);
  175. const avgCouncilRewardPerBlock = councilTermDurationRatio * totalCouncilRewardsPerBlock;
  176. return avgCouncilRewardPerBlock * roundNrBlocks;
  177. }
  178. async computeStorageProviderReward(roundNrBlocks: number, startHash: Hash, endHash: Hash): Promise<WorkersInfo> {
  179. let nextWorkerId = (await this.api.query.storageWorkingGroup.nextWorkerId.at(startHash) as WorkerId).toNumber();
  180. let info = new WorkersInfo();
  181. for (let i = 0; i < nextWorkerId; ++i) {
  182. let worker = await this.api.query.storageWorkingGroup.workerById(i) as WorkerOf;
  183. if (worker.role_stake_profile.isSome) {
  184. let roleStakeProfile = worker.role_stake_profile.unwrap();
  185. let stake = await this.api.query.stake.stakes(roleStakeProfile.stake_id) as Stake;
  186. info.startStake += stake.value.toNumber();
  187. }
  188. }
  189. nextWorkerId = (await this.api.query.storageWorkingGroup.nextWorkerId.at(endHash) as WorkerId).toNumber();
  190. let rewardRelationshipIds = Array<RewardRelationshipId>();
  191. for (let i = 0; i < nextWorkerId; ++i) {
  192. let worker = await this.api.query.storageWorkingGroup.workerById(i) as WorkerOf;
  193. if (worker.reward_relationship.isSome) {
  194. rewardRelationshipIds.push(worker.reward_relationship.unwrap());
  195. }
  196. if (worker.role_stake_profile.isSome) {
  197. let roleStakeProfile = worker.role_stake_profile.unwrap();
  198. let stake = await this.api.query.stake.stakes(roleStakeProfile.stake_id) as Stake;
  199. info.endStake += stake.value.toNumber();
  200. }
  201. }
  202. info.rewards = await this.computeReward(roundNrBlocks, rewardRelationshipIds, endHash);
  203. info.endNrOfWorkers = nextWorkerId - WORKER_ID_OFFSET;
  204. return info;
  205. }
  206. async computeCuratorsReward(roundNrBlocks: number, startHash: Hash, endHash: Hash) {
  207. let nextCuratorId = (await this.api.query.contentDirectoryWorkingGroup.nextWorkerId.at(endHash) as WorkerId).toNumber();
  208. let rewardRelationshipIds = Array<RewardRelationshipId>();
  209. for (let i = 0; i < nextCuratorId; ++i) {
  210. let worker = await this.api.query.contentDirectoryWorkingGroup.workerById(i) as WorkerOf;
  211. if (worker.reward_relationship.isSome) {
  212. rewardRelationshipIds.push(worker.reward_relationship.unwrap());
  213. }
  214. }
  215. return this.computeReward(roundNrBlocks, rewardRelationshipIds, endHash);
  216. }
  217. async computeReward(roundNrBlocks: number, rewardRelationshipIds: RewardRelationshipId[], hash: Hash) {
  218. let recurringRewards = await Promise.all(rewardRelationshipIds.map(async (rewardRelationshipId) => {
  219. return await this.api.query.recurringRewards.rewardRelationships.at(hash, rewardRelationshipId) as RewardRelationship;
  220. }));
  221. let rewardPerBlock = 0;
  222. for (let recurringReward of recurringRewards) {
  223. const amount = recurringReward.amount_per_payout.toNumber();
  224. const payoutInterval = recurringReward.payout_interval.unwrapOr(null);
  225. if (amount && payoutInterval) {
  226. rewardPerBlock += amount / payoutInterval;
  227. }
  228. }
  229. return rewardPerBlock * roundNrBlocks;
  230. }
  231. async fillMintsInfo(startHash: Hash, endHash: Hash) {
  232. let startNrMints = parseInt((await this.api.query.minting.mintsCreated.at(startHash)).toString());
  233. let endNrMints = parseInt((await this.api.query.minting.mintsCreated.at(endHash)).toString());
  234. this.statistics.newMints = endNrMints - startNrMints;
  235. // statistics.startMinted = 0;
  236. // statistics.endMinted = 0;
  237. for (let i = 0; i < startNrMints; ++i) {
  238. let startMint = (await this.api.query.minting.mints.at(startHash, i)) as Mint;
  239. // if (!startMint) {
  240. // continue;
  241. // }
  242. let endMint = (await this.api.query.minting.mints.at(endHash, i)) as Mint;
  243. // let = endMintResult[0];
  244. // if (!endMint) {
  245. // continue;
  246. // }
  247. let startMintTotal = parseInt(startMint.getField("total_minted").toString());
  248. let endMintTotal = parseInt(endMint.getField("total_minted").toString());
  249. // statistics.startMinted += startMintTotal;
  250. this.statistics.totalMinted += endMintTotal - startMintTotal;
  251. this.statistics.totalMintCapacityIncrease += parseInt(endMint.getField("capacity").toString()) - parseInt(startMint.getField("capacity").toString());
  252. }
  253. for (let i = startNrMints; i < endNrMints; ++i) {
  254. let endMint = await this.api.query.minting.mints.at(endHash, i) as Mint;
  255. if (!endMint) {
  256. return;
  257. }
  258. this.statistics.totalMinted = parseInt(endMint.getField("total_minted").toString());
  259. }
  260. let councilMint = (await this.api.query.council.councilMint.at(endHash)) as MintId;
  261. let councilMintStatistics = await this.computeMintInfo(councilMint, startHash, endHash);
  262. this.statistics.startCouncilMinted = councilMintStatistics.startMinted;
  263. this.statistics.endCouncilMinted = councilMintStatistics.endMinted;
  264. this.statistics.newCouncilMinted = councilMintStatistics.diffMinted;
  265. this.statistics.percNewCouncilMinted = councilMintStatistics.percMinted;
  266. 6
  267. let curatorMint = (await this.api.query.contentDirectoryWorkingGroup.mint.at(endHash)) as MintId;
  268. let curatorMintStatistics = await this.computeMintInfo(curatorMint, startHash, endHash);
  269. this.statistics.startCuratorMinted = curatorMintStatistics.startMinted;
  270. this.statistics.endCuratorMinted = curatorMintStatistics.endMinted;
  271. this.statistics.newCuratorMinted = curatorMintStatistics.diffMinted;
  272. this.statistics.percCuratorMinted = curatorMintStatistics.percMinted;
  273. let storageProviderMint = (await this.api.query.storageWorkingGroup.mint.at(endHash)) as MintId;
  274. let storageProviderMintStatistics = await this.computeMintInfo(storageProviderMint, startHash, endHash);
  275. this.statistics.startStorageMinted = storageProviderMintStatistics.startMinted;
  276. this.statistics.endStorageMinted = storageProviderMintStatistics.endMinted;
  277. this.statistics.newStorageMinted = storageProviderMintStatistics.diffMinted;
  278. this.statistics.percStorageMinted = storageProviderMintStatistics.percMinted;
  279. }
  280. async computeMintInfo(mintId: MintId, startHash: Hash, endHash: Hash): Promise<MintStatistics> {
  281. // if (mintId.toString() == "0") {
  282. // return new MintStatistics(0, 0, 0);
  283. // }
  284. let startMint = await this.api.query.minting.mints.at(startHash, mintId) as Mint;
  285. // let startMint = startMintResult[0] as unknown as Mint;
  286. // if (!startMint) {
  287. // return new MintStatistics(0, 0, 0);
  288. // }
  289. let endMint = await this.api.query.minting.mints.at(endHash, mintId) as Mint;
  290. // let endMint = endMintResult[0] as unknown as Mint;
  291. // if (!endMint) {
  292. // return new MintStatistics(0, 0, 0);
  293. // }
  294. let mintStatistics = new MintStatistics();
  295. mintStatistics.startMinted = parseInt(startMint.getField('total_minted').toString());
  296. mintStatistics.endMinted = parseInt(endMint.getField('total_minted').toString());
  297. mintStatistics.diffMinted = mintStatistics.endMinted - mintStatistics.startMinted;
  298. mintStatistics.percMinted = StatisticsCollector.convertToPercentage(mintStatistics.startMinted, mintStatistics.endMinted);
  299. return mintStatistics;
  300. }
  301. async fillCouncilInfo(startHash: Hash, endHash: Hash) {
  302. this.statistics.councilRound = (await this.api.query.councilElection.round.at(startHash) as u32).toNumber();
  303. this.statistics.councilMembers = (await this.api.query.councilElection.councilSize.at(startHash) as u32).toNumber();
  304. let startNrProposals = await this.api.query.proposalsEngine.proposalCount.at(startHash) as u32;
  305. let endNrProposals = await this.api.query.proposalsEngine.proposalCount.at(endHash) as u32;
  306. this.statistics.newProposals = endNrProposals.toNumber() - startNrProposals.toNumber();
  307. let approvedProposals = new Set();
  308. for (let [key, blockEvents] of this.blocksEventsCache) {
  309. for (let event of blockEvents) {
  310. if (event.section == "proposalsEngine" && event.method == "ProposalStatusUpdated") {
  311. let statusUpdateData = event.data[1] as any;
  312. let finalizeData = statusUpdateData.finalized as any
  313. if (finalizeData && finalizeData.proposalStatus.approved) {
  314. approvedProposals.add(Number(event.data[0]));
  315. }
  316. }
  317. }
  318. }
  319. this.statistics.newApprovedProposals = approvedProposals.size;
  320. }
  321. async fillCouncilElectionInfo(startBlock: number) {
  322. let startBlockHash = await this.api.rpc.chain.getBlockHash(startBlock);
  323. let events = await this.api.query.system.events.at(startBlockHash) as Vec<EventRecord>;
  324. let isStartBlockFirstCouncilBlock = events.some((event) => {
  325. return event.event.section == "councilElection" && event.event.method == "CouncilElected";
  326. });
  327. if (!isStartBlockFirstCouncilBlock) {
  328. console.warn('Note: The given start block is not the first block of the council round so council election information will be empty');
  329. return;
  330. }
  331. let previousCouncilRoundLastBlock = startBlock - 1;
  332. let previousCouncilRoundLastBlockHash = await this.api.rpc.chain.getBlockHash(previousCouncilRoundLastBlock);
  333. let applicants = await this.api.query.councilElection.applicants.at(previousCouncilRoundLastBlockHash) as Vec<AccountId>;
  334. this.statistics.electionApplicants = applicants.length;
  335. for (let applicant of applicants) {
  336. let applicantStakes = await this.api.query.councilElection.applicantStakes.at(previousCouncilRoundLastBlockHash, applicant) as unknown as ElectionStake;
  337. this.statistics.electionApplicantsStakes += applicantStakes.new.toNumber();
  338. }
  339. // let seats = await this.api.query.council.activeCouncil.at(startBlockHash) as Seats;
  340. //TODO: Find a more accurate way of getting the votes
  341. const votes = await this.api.query.councilElection.commitments.at(previousCouncilRoundLastBlockHash) as Vec<Hash>;
  342. this.statistics.electionVotes = votes.length;
  343. }
  344. async fillValidatorInfo(startHash: Hash, endHash: Hash) {
  345. let startTimestamp = await this.api.query.timestamp.now.at(startHash) as unknown as Moment;
  346. let endTimestamp = await this.api.query.timestamp.now.at(endHash) as unknown as Moment;
  347. let avgBlockProduction = (((endTimestamp.toNumber() - startTimestamp.toNumber())
  348. / 1000) / this.statistics.newBlocks);
  349. this.statistics.avgBlockProduction = Number(avgBlockProduction.toFixed(2));
  350. let maxStartValidators = (await this.api.query.staking.validatorCount.at(startHash) as u32).toNumber();
  351. let startValidators = await this.findActiveValidators(startHash, false);
  352. this.statistics.startValidators = startValidators.length + " / " + maxStartValidators;
  353. let maxEndValidators = (await this.api.query.staking.validatorCount.at(endHash) as u32).toNumber();
  354. let endValidators = await this.findActiveValidators(endHash, true);
  355. this.statistics.endValidators = endValidators.length + " / " + maxEndValidators;
  356. this.statistics.percValidators = StatisticsCollector.convertToPercentage(startValidators.length, endValidators.length);
  357. const startEra = await this.api.query.staking.currentEra.at(startHash) as Option<EraIndex>;
  358. this.statistics.startValidatorsStake = (await this.api.query.staking.erasTotalStake.at(startHash, startEra.unwrap())).toNumber();
  359. const endEra = await this.api.query.staking.currentEra.at(endHash) as Option<EraIndex>;
  360. this.statistics.endValidatorsStake = (await this.api.query.staking.erasTotalStake.at(endHash, endEra.unwrap())).toNumber();
  361. this.statistics.percNewValidatorsStake = StatisticsCollector.convertToPercentage(this.statistics.startValidatorsStake, this.statistics.endValidatorsStake);
  362. }
  363. async findActiveValidators(hash: Hash, searchPreviousBlocks: boolean): Promise<AccountId[]> {
  364. const block = await this.api.rpc.chain.getBlock(hash);
  365. let currentBlockNr = block.block.header.number.toNumber();
  366. let activeValidators;
  367. do {
  368. let currentHash = (await this.api.rpc.chain.getBlockHash(currentBlockNr)) as Hash;
  369. let allValidators = await this.api.query.staking.snapshotValidators.at(currentHash) as Option<Vec<AccountId>>;
  370. if (!allValidators.isEmpty) {
  371. let max = (await this.api.query.staking.validatorCount.at(currentHash)).toNumber();
  372. activeValidators = Array.from(allValidators.unwrap()).slice(0, max);
  373. }
  374. if (searchPreviousBlocks) {
  375. --currentBlockNr;
  376. } else {
  377. ++currentBlockNr;
  378. }
  379. } while (activeValidators == undefined);
  380. return activeValidators;
  381. }
  382. async fillStorageProviderInfo(startBlock: number, endBlock: number, startHash: Hash, endHash: Hash) {
  383. let roundNrBlocks = endBlock - startBlock;
  384. let storageProvidersRewards = await this.computeStorageProviderReward(roundNrBlocks, startHash, endHash);
  385. this.statistics.newStorageProviderReward = storageProvidersRewards.rewards;
  386. this.statistics.newStorageProviderReward = Number(this.statistics.newStorageProviderReward.toFixed(2));
  387. this.statistics.startStorageProvidersStake = storageProvidersRewards.startStake;
  388. this.statistics.endStorageProvidersStake = storageProvidersRewards.endStake;
  389. this.statistics.percNewStorageProviderStake = StatisticsCollector.convertToPercentage(this.statistics.startStorageProvidersStake, this.statistics.endStorageProvidersStake);
  390. this.statistics.startStorageProviders = await this.api.query.storageWorkingGroup.activeWorkerCount.at(startHash);
  391. this.statistics.endStorageProviders = await this.api.query.storageWorkingGroup.activeWorkerCount.at(endHash);
  392. this.statistics.percNewStorageProviders = StatisticsCollector.convertToPercentage(this.statistics.startStorageProviders, this.statistics.endStorageProviders);
  393. let lastStorageProviderId = Number(await this.api.query.storageWorkingGroup.nextWorkerId.at(endHash)) - 1;
  394. this.statistics.storageProviders = "";
  395. for (let i = lastStorageProviderId, storageProviderCount = 0; storageProviderCount < this.statistics.endStorageProviders; --i, ++storageProviderCount){
  396. let storageProvider = await this.api.query.storageWorkingGroup.workerById.at(endHash, i) as WorkerOf;
  397. let membership = await this.api.query.members.membershipById.at(endHash, storageProvider.member_id) as Membership;
  398. this.statistics.storageProviders += "@" + membership.handle + " | (" + membership.root_account +") \n";
  399. }
  400. }
  401. async fillCuratorInfo(startHash: Hash, endHash: Hash) {
  402. this.statistics.startCurators = Number(await this.api.query.contentDirectoryWorkingGroup.activeWorkerCount.at(startHash));
  403. this.statistics.endCurators = Number(await this.api.query.contentDirectoryWorkingGroup.activeWorkerCount.at(endHash));
  404. this.statistics.percNewCurators = StatisticsCollector.convertToPercentage(this.statistics.startCurators, this.statistics.endCurators);
  405. let lastCuratorId = Number(await this.api.query.contentDirectoryWorkingGroup.nextWorkerId.at(endHash)) - 1;
  406. this.statistics.curators = "";
  407. for (let i = lastCuratorId, curatorCount = 0; curatorCount < this.statistics.endCurators; --i, ++curatorCount){
  408. let curator = await this.api.query.contentDirectoryWorkingGroup.workerById.at(endHash, i) as WorkerOf;
  409. let curatorMembership = await this.api.query.members.membershipById.at(endHash, curator.member_id) as Membership;
  410. this.statistics.curators += "@" + curatorMembership.handle + " | (" + curatorMembership.root_account +") \n";
  411. }
  412. }
  413. async fillMembershipInfo(startHash: Hash, endHash: Hash) {
  414. this.statistics.startMembers = (await this.api.query.members.nextMemberId.at(startHash) as MemberId).toNumber();
  415. this.statistics.endMembers = (await this.api.query.members.nextMemberId.at(endHash) as MemberId).toNumber();
  416. this.statistics.newMembers = this.statistics.endMembers - this.statistics.startMembers;
  417. this.statistics.percNewMembers = StatisticsCollector.convertToPercentage(this.statistics.startMembers, this.statistics.endMembers);
  418. }
  419. async fillMediaUploadInfo(startHash: Hash, endHash: Hash) {
  420. let startEntites = await this.getEntities(startHash);
  421. let endEntities = await this.getEntities(endHash);
  422. let startVideos = await this.parseVideos(startEntites);
  423. let endVideos = await this.parseVideos(endEntities);
  424. this.statistics.startMedia = startVideos.length;
  425. this.statistics.endMedia = endVideos.length;
  426. this.statistics.percNewMedia = StatisticsCollector.convertToPercentage(this.statistics.startMedia, this.statistics.endMedia);
  427. let startChannels = await this.parseChannels(startEntites);
  428. let endChannels = await this.parseChannels(endEntities);
  429. this.statistics.startChannels = startChannels.length;
  430. this.statistics.endChannels = endChannels.length;
  431. this.statistics.percNewChannels = StatisticsCollector.convertToPercentage(this.statistics.startChannels, this.statistics.endChannels);
  432. let startDataObjects = await this.api.query.dataDirectory.knownContentIds.at(startHash) as Vec<ContentId>;
  433. this.statistics.startUsedSpace = Number((await this.computeUsedSpaceInMbs(startDataObjects)).toFixed(2));
  434. let endDataObjects = await this.api.query.dataDirectory.knownContentIds.at(endHash) as Vec<ContentId>;
  435. this.statistics.endUsedSpace = Number((await this.computeUsedSpaceInMbs(endDataObjects)).toFixed(2));
  436. this.statistics.percNewUsedSpace = StatisticsCollector.convertToPercentage(this.statistics.startUsedSpace, this.statistics.endUsedSpace);
  437. }
  438. async fillForumInfo(startHash: Hash, endHash: Hash) {
  439. let startPostId = await this.api.query.forum.nextPostId.at(startHash) as PostId;
  440. let endPostId = await this.api.query.forum.nextPostId.at(endHash) as PostId;
  441. this.statistics.startPosts = startPostId.toNumber();
  442. this.statistics.endPosts = endPostId.toNumber();
  443. this.statistics.newPosts = this.statistics.endPosts - this.statistics.startPosts;
  444. this.statistics.percNewPosts = StatisticsCollector.convertToPercentage(this.statistics.startPosts, this.statistics.endPosts);
  445. let startThreadId = ((await this.api.query.forum.nextThreadId.at(startHash)) as unknown) as ThreadId;
  446. let endThreadId = ((await this.api.query.forum.nextThreadId.at(endHash)) as unknown) as ThreadId;
  447. this.statistics.startThreads = startThreadId.toNumber();
  448. this.statistics.endThreads = endThreadId.toNumber();
  449. this.statistics.newThreads = this.statistics.endThreads - this.statistics.startThreads;
  450. this.statistics.percNewThreads = StatisticsCollector.convertToPercentage(this.statistics.startThreads, this.statistics.endThreads);
  451. let startCategoryId = (await this.api.query.forum.nextCategoryId.at(startHash)) as CategoryId;
  452. let endCategoryId = (await this.api.query.forum.nextCategoryId.at(endHash)) as CategoryId;
  453. this.statistics.startCategories = startCategoryId.toNumber();
  454. this.statistics.endCategories = endCategoryId.toNumber();
  455. this.statistics.newCategories = this.statistics.endCategories - this.statistics.startCategories;
  456. this.statistics.perNewCategories = StatisticsCollector.convertToPercentage(this.statistics.startCategories, this.statistics.endCategories);
  457. }
  458. static convertToPercentage(previousValue: number, newValue: number): number {
  459. if (previousValue == 0) {
  460. return newValue > 0 ? Infinity : 0;
  461. }
  462. return Number((newValue * 100 / previousValue - 100).toFixed(2));
  463. }
  464. async computeUsedSpaceInMbs(contentIds: Vec<ContentId>) {
  465. let space = 0;
  466. for (let contentId of contentIds) {
  467. let dataObject = (await this.api.query.dataDirectory.dataObjectByContentId(contentId)) as Option<DataObject>;
  468. space += dataObject.unwrap().size_in_bytes.toNumber();
  469. }
  470. return space / 1024 / 1024;
  471. }
  472. async parseVideos(entities: Map<number, Entity>) {
  473. let videos: Media[] = [];
  474. for (let [key, entity] of entities) {
  475. if (entity.class_id.toNumber() != VIDEO_CLASS_iD || entity.values.isEmpty) {
  476. continue;
  477. }
  478. let values = Array.from(entity.getField('values').entries());
  479. if (values.length < 2 || values[2].length < 1) {
  480. continue;
  481. }
  482. let title = values[2][1].getValue().toString();
  483. videos.push(new Media(key, title));
  484. }
  485. return videos;
  486. }
  487. async parseChannels(entities: Map<number, Entity>) {
  488. let channels: Channel[] = [];
  489. for (let [key, entity] of entities) {
  490. if (entity.class_id.toNumber() != CHANNEL_CLASS_iD || entity.values.isEmpty) {
  491. continue;
  492. }
  493. let values = Array.from(entity.getField('values').entries());
  494. let title = values[0][1].getValue().toString();
  495. channels.push(new Channel(key, title));
  496. }
  497. return channels;
  498. }
  499. async getEntities(blockHash: Hash) {
  500. let nrEntities = ((await this.api.query.contentDirectory.nextEntityId.at(blockHash)) as EntityId).toNumber();
  501. let entities = new Map<number, Entity>();
  502. for (let i = 0; i < nrEntities; ++i) {
  503. let entity = await this.api.query.contentDirectory.entityById.at(blockHash, i) as Entity;
  504. entities.set(i, entity);
  505. }
  506. return entities;
  507. }
  508. async buildBlocksEventCache(startBlock: number, endBlock: number) {
  509. let cacheFile = CACHE_FOLDER + '/' + startBlock + '-' + endBlock + '.json';
  510. let exists = await fs.access(cacheFile, fsSync.constants.R_OK).then(() => true)
  511. .catch(() => false);
  512. // let exists = false;
  513. if (!exists) {
  514. console.log('Building events cache...');
  515. for (let i = startBlock; i < endBlock; ++i) {
  516. process.stdout.write('\rCaching block: ' + i + ' until ' + endBlock);
  517. const blockHash: Hash = await this.api.rpc.chain.getBlockHash(i);
  518. let eventRecord = await this.api.query.system.events.at(blockHash) as Vec<EventRecord>;
  519. let cacheEvents = new Array<CacheEvent>();
  520. for (let event of eventRecord) {
  521. cacheEvents.push(new CacheEvent(event.event.section, event.event.method, event.event.data));
  522. }
  523. this.blocksEventsCache.set(i, cacheEvents);
  524. }
  525. console.log('\nFinish events cache...');
  526. await fs.writeFile(cacheFile, JSON.stringify(Array.from(this.blocksEventsCache.entries()), null, 2));
  527. } else {
  528. console.log('Cache file found, loading it...');
  529. let fileData = await fs.readFile(cacheFile);
  530. this.blocksEventsCache = new Map(JSON.parse(fileData));
  531. console.log('Cache file loaded...');
  532. }
  533. }
  534. static async connectApi(): Promise<ApiPromise> {
  535. // const provider = new WsProvider('wss://testnet.joystream.org:9944');
  536. const provider = new WsProvider(PROVIDER_URL);
  537. // Create the API and wait until ready
  538. return await ApiPromise.create({provider, types});
  539. }
  540. }