rewards.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import { ApiPromise } from "@polkadot/api";
  2. // types
  3. import { Bounty, CacheEvent, WorkerReward, SpendingProposal } from "./types";
  4. import { AccountId, Balance } from "@polkadot/types/interfaces";
  5. import { Hash } from "@polkadot/types/interfaces";
  6. import { Membership } from "@joystream/types/members";
  7. import { Mint, MintId } from "@joystream/types/mint";
  8. import {
  9. Proposal,
  10. ProposalId,
  11. SpendingParams,
  12. } from "@joystream/types/proposals";
  13. import { ProposalDetails, ProposalOf } from "@joystream/types/augment/types";
  14. import { Stake } from "@joystream/types/stake";
  15. import {
  16. RewardRelationship,
  17. RewardRelationshipId,
  18. } from "@joystream/types/recurring-rewards";
  19. // lib
  20. import { getPercent, getTotalMinted } from "./";
  21. import {
  22. getBlock,
  23. getBlockHash,
  24. getMint,
  25. getNextWorker,
  26. getMember,
  27. getWorker,
  28. getWorkerReward,
  29. getProposalInfo,
  30. getProposalDetails,
  31. getStake,
  32. getValidators,
  33. getValidatorCount,
  34. } from "./api";
  35. import { WorkerOf } from "@joystream/types/augment-codec/all";
  36. import { ProposalDetailsOf } from "@joystream/types/augment/types";
  37. export const filterMethods = {
  38. getBurnedTokens: ({ section, method }: CacheEvent) =>
  39. section === "balances" && method === "Transfer",
  40. newValidatorsRewards: ({ section, method }: CacheEvent) =>
  41. section === "staking" && method === "Reward",
  42. finalizedSpendingProposals: ({ section, method }: CacheEvent) =>
  43. section === "proposalsEngine" && method === "ProposalStatusUpdated",
  44. sudoSetBalance: ({ section, method }: CacheEvent) =>
  45. section == "balances" && method == "BalanceSet",
  46. };
  47. export const getWorkerRewards = async (
  48. api: ApiPromise,
  49. group: string,
  50. hash: Hash
  51. ): Promise<WorkerReward[]> => {
  52. let workers = Array<WorkerReward>();
  53. const nextWorkerId = await getNextWorker(api, group, hash);
  54. for (let id = 0; id < nextWorkerId; ++id) {
  55. const worker: WorkerOf = await getWorker(api, group, hash, id);
  56. const account = worker.role_account_id as AccountId;
  57. const memberId = worker.member_id;
  58. const member: Membership = await getMember(api, memberId, hash);
  59. const handle = member ? String(member.handle) : account.toString();
  60. const status = worker.is_active ? `active` : `inactive`;
  61. // fetch reward and stake
  62. const w: WorkerReward = { id, status, handle, account, memberId };
  63. if (worker.role_stake_profile.isSome) {
  64. const roleStakeProfile = worker.role_stake_profile.unwrap();
  65. w.stake = await getStake(api, roleStakeProfile.stake_id);
  66. }
  67. if (worker.reward_relationship.isSome) {
  68. const id: RewardRelationshipId = worker.reward_relationship.unwrap();
  69. w.reward = await getWorkerReward(api, hash, id);
  70. }
  71. workers.push(w);
  72. }
  73. return workers;
  74. };
  75. export const getWorkerRow = (
  76. worker: WorkerReward,
  77. earnedStart: number
  78. ): string => {
  79. const mtjoy = (mtjoy: number): string => (mtjoy / 1000000).toFixed(1);
  80. const { id, memberId, account, handle, status, reward } = worker;
  81. if (!reward) return ``;
  82. const earnedEnd = Number(reward.total_reward_received.toBigInt());
  83. if (!earnedEnd) return ``;
  84. const totalEarned = mtjoy(earnedEnd);
  85. const earnedTerm = mtjoy(earnedEnd - earnedStart);
  86. const amount = Number(reward.amount_per_payout.toBigInt());
  87. const rewardPerBlock = (amount / Number(reward.payout_interval)).toFixed();
  88. const url = `https://pioneer.joystreamstats.live/#/members/${handle}`; // TODO
  89. return `| ${id} | [@${handle}](${url}) | ${status} | ${rewardPerBlock} | ${earnedTerm} | ${totalEarned} |\n`;
  90. };
  91. export const getBurnedTokens = (
  92. burnAddress: string,
  93. blocks: [number, CacheEvent[]][]
  94. ): number => {
  95. let tokensBurned = 0;
  96. blocks.forEach(([key, transfers]) =>
  97. transfers.forEach((transfer) => {
  98. let receiver = transfer.data[1] as AccountId;
  99. let amount = transfer.data[2] as Balance;
  100. if (receiver.toString() === burnAddress) tokensBurned += Number(amount);
  101. })
  102. );
  103. return tokensBurned;
  104. };
  105. export const getFinalizedSpendingProposals = async (
  106. api: ApiPromise,
  107. blocks: [number, CacheEvent[]][]
  108. ): Promise<SpendingProposal[]> => {
  109. let spendingProposals: SpendingProposal[] = [];
  110. await blocks.forEach(([key, proposals]) =>
  111. proposals.forEach(async (proposalEvent) => {
  112. let statusUpdateData = proposalEvent.data[1] as any;
  113. const finalizedAt = statusUpdateData.finalized.finalizedAt;
  114. if (!(statusUpdateData.finalized && finalizedAt)) return;
  115. const proposalId = proposalEvent.data[0] as ProposalId;
  116. const id = +proposalId;
  117. const proposalInfo: ProposalOf = await getProposalInfo(api, proposalId);
  118. const finalizedData = proposalInfo.status.asFinalized;
  119. const details: ProposalDetailsOf = await getProposalDetails(
  120. api,
  121. proposalId
  122. );
  123. if (!finalizedData.proposalStatus.isApproved || !details.isSpending)
  124. return;
  125. let approvedData = finalizedData.proposalStatus.asApproved;
  126. if (!approvedData.isExecuted) return;
  127. if (!spendingProposals.some((proposal) => proposal.id === id)) {
  128. const title = proposalInfo.title.toString();
  129. const amount = +details.asSpending[0];
  130. spendingProposals.push({ id, title, amount });
  131. }
  132. })
  133. );
  134. return spendingProposals;
  135. };
  136. export const getValidatorsRewards = (
  137. blocks: [number, CacheEvent[]][]
  138. ): number => {
  139. let newValidatorRewards = 0;
  140. blocks.forEach(([key, validatorRewards]) =>
  141. validatorRewards.forEach(
  142. (reward: CacheEvent) => (newValidatorRewards += Number(reward.data[1]))
  143. )
  144. );
  145. return newValidatorRewards;
  146. };
  147. export const getActiveValidators = async (
  148. api: ApiPromise,
  149. hash: Hash,
  150. searchPreviousBlocks: boolean = false
  151. ): Promise<AccountId[]> => {
  152. const block = await getBlock(api, hash);
  153. let currentBlockNr = block.block.header.number.toNumber();
  154. let activeValidators: AccountId[] = [];
  155. while (!activeValidators.length) {
  156. const hash: Hash = await getBlockHash(api, currentBlockNr);
  157. const validators: AccountId[] = await getValidators(api, hash);
  158. if (validators.length) {
  159. let max = await getValidatorCount(api, hash);
  160. activeValidators = validators.slice(0, max);
  161. }
  162. if (searchPreviousBlocks) --currentBlockNr;
  163. else ++currentBlockNr;
  164. }
  165. return activeValidators;
  166. };