StatisticsCollector.ts 37 KB

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