Browse Source

update media, rewards

Joystream Stats 3 years ago
parent
commit
8a9d5b06f3
5 changed files with 46 additions and 49 deletions
  1. 4 1
      api.ts
  2. 1 1
      index.ts
  3. 3 3
      media.ts
  4. 30 44
      rewards.ts
  5. 8 0
      types.ts

+ 4 - 1
api.ts

@@ -99,7 +99,10 @@ export const getEraStake = async (
   (await api.query.staking.erasTotalStake.at(hash, era)).toNumber();
 
 // council
-export const getCouncil = (api: ApiPromise, hash: Hash): Promise<Seats> =>
+export const getCouncil = (api: ApiPromise): Promise<Seats> =>
+  api.query.council.activeCouncil();
+
+export const getCouncilAt = (api: ApiPromise, hash: Hash): Promise<Seats> =>
   api.query.council.activeCouncil.at(hash);
 
 export const getCouncils = async (

+ 1 - 1
index.ts

@@ -3,7 +3,7 @@ import { Mint, MintId } from "@joystream/types/mint";
 import { Moment } from "@polkadot/types/interfaces";
 
 export const getPercent = (value1: number, value2: number): number => {
-  if (value1 == 0) return value2 > 0 ? 100 : 0;
+  if (value1 === 0) return value2 > 0 ? 100 : 0;
   return Number(((value2 * 100) / value1 - 100).toFixed(2));
 };
 

+ 3 - 3
media.ts

@@ -11,12 +11,12 @@ const VIDEO_CLASS_iD = 10;
 
 const getEntities = async (
   api: ApiPromise,
-  blockHash: Hash
+  hash: Hash
 ): Promise<Map<number, Entity>> => {
-  let nrEntities: number = await getNextEntity(api, blockHash);
+  let nrEntities: number = await getNextEntity(api, hash);
   let entities = new Map<number, Entity>();
   for (let i = 0; i < nrEntities; ++i) {
-    const entity: Entity = await getEntity(api, blockHash, i);
+    const entity: Entity = await getEntity(api, hash, i);
     entities.set(i, entity);
   }
   return entities;

+ 30 - 44
rewards.ts

@@ -45,9 +45,7 @@ export const filterMethods = {
   finalizedSpendingProposals: ({ section, method }: CacheEvent) =>
     section === "proposalsEngine" && method === "ProposalStatusUpdated",
   sudoSetBalance: ({ section, method }: CacheEvent) =>
-    section === "balances" && method === "BalanceSet",
-  proposalStatusUpdated: ({ section, method }: CacheEvent) =>
-    section === "proposalsEngine" && method === "ProposalStatusUpdated",
+    section == "balances" && method == "BalanceSet",
 };
 
 export const getWorkerRewards = async (
@@ -66,21 +64,19 @@ export const getWorkerRewards = async (
     const member: Membership = await getMember(api, memberId, hash);
     const handle = member ? String(member.handle) : account.toString();
     const status = worker.is_active ? `active` : `inactive`;
-    let stake: Stake;
-    let reward: RewardRelationship;
 
+    // fetch reward and stake
+    const w: WorkerReward = { id, status, handle, account, memberId };
     if (worker.role_stake_profile.isSome) {
       const roleStakeProfile = worker.role_stake_profile.unwrap();
-      stake = await getStake(api, roleStakeProfile.stake_id, hash);
+      w.stake = await getStake(api, roleStakeProfile.stake_id);
     }
 
     if (worker.reward_relationship.isSome) {
-      // TODO changing salaries are not reflected
-      const rewardId: RewardRelationshipId =
-        worker.reward_relationship.unwrap();
-      reward = await getWorkerReward(api, hash, rewardId);
+      const id: RewardRelationshipId = worker.reward_relationship.unwrap();
+      w.reward = await getWorkerReward(api, hash, id);
     }
-    workers.push({ id, stake, reward, status, handle, account, memberId });
+    workers.push(w);
   }
   return workers;
 };
@@ -92,6 +88,7 @@ export const getWorkerRow = (
   const mtjoy = (mtjoy: number): string => (mtjoy / 1000000).toFixed(1);
 
   const { id, memberId, account, handle, status, reward } = worker;
+  if (!reward) return ``;
   const earnedEnd = Number(reward.total_reward_received.toBigInt());
   if (!earnedEnd) return ``;
   const totalEarned = mtjoy(earnedEnd);
@@ -121,42 +118,32 @@ export const getFinalizedSpendingProposals = async (
   api: ApiPromise,
   blocks: [number, CacheEvent[]][]
 ): Promise<SpendingProposal[]> => {
-  const selectedEvents: CacheEvent[] = [];
-  blocks.map(([key, proposalEvents]) =>
-    proposalEvents.map((proposalEvent) => selectedEvents.push(proposalEvent))
-  );
-
   let spendingProposals: SpendingProposal[] = [];
-  for (const proposalEvent of selectedEvents) {
-    let statusUpdateData = proposalEvent.data[1] as any;
-    const finalizedAt = statusUpdateData.finalized.finalizedAt;
-    if (!(statusUpdateData.finalized && finalizedAt)) continue;
-
-    const proposalId = proposalEvent.data[0] as ProposalId;
-    const proposalInfo: ProposalOf = await getProposalInfo(api, proposalId);
-    if (!proposalInfo) continue;
-    try {
+  await blocks.forEach(([key, proposals]) =>
+    proposals.forEach(async (proposalEvent) => {
+      let statusUpdateData = proposalEvent.data[1] as any;
+      const finalizedAt = statusUpdateData.finalized.finalizedAt;
+      if (!(statusUpdateData.finalized && finalizedAt)) return;
+
+      const proposalId = proposalEvent.data[0] as ProposalId;
+      const id = +proposalId;
+      const proposalInfo: ProposalOf = await getProposalInfo(api, proposalId);
       const finalizedData = proposalInfo.status.asFinalized;
       const details: ProposalDetailsOf = await getProposalDetails(
         api,
         proposalId
       );
-      if (finalizedData.proposalStatus.isApproved && details.isSpending) {
-        let approvedData = finalizedData.proposalStatus.asApproved;
-        if (!approvedData.isExecuted) continue;
-        if (
-          !spendingProposals.some((proposal) => proposal.id === +proposalId)
-        ) {
-          const title = proposalInfo.title.toString();
-          const amount = +details.asSpending[0];
-          spendingProposals.push({ id: +proposalId, title, amount });
-        }
+      if (!finalizedData.proposalStatus.isApproved || !details.isSpending)
+        return;
+      let approvedData = finalizedData.proposalStatus.asApproved;
+      if (!approvedData.isExecuted) return;
+      if (!spendingProposals.some((proposal) => proposal.id === id)) {
+        const title = proposalInfo.title.toString();
+        const amount = +details.asSpending[0];
+        spendingProposals.push({ id, title, amount });
       }
-    } catch (e) {
-      console.error(`Failed to fetch proposal info: ${e.message}`);
-      continue;
-    }
-  }
+    })
+  );
   return spendingProposals;
 };
 
@@ -179,17 +166,16 @@ export const getActiveValidators = async (
 ): Promise<AccountId[]> => {
   const block = await getBlock(api, hash);
   let currentBlockNr = block.block.header.number.toNumber();
-  let activeValidators: AccountId[];
-  do {
+  let activeValidators: AccountId[] = [];
+  while (!activeValidators.length) {
     const hash: Hash = await getBlockHash(api, currentBlockNr);
     const validators: AccountId[] = await getValidators(api, hash);
     if (validators.length) {
       let max = await getValidatorCount(api, hash);
       activeValidators = validators.slice(0, max);
     }
-
     if (searchPreviousBlocks) --currentBlockNr;
     else ++currentBlockNr;
-  } while (!activeValidators);
+  }
   return activeValidators;
 };

+ 8 - 0
types.ts

@@ -130,3 +130,11 @@ export interface Exchange {
   status: string;
   xmrAddress: string;
 }
+
+export class Media {
+  constructor(public id: number, public title: string) {}
+}
+
+export class Channel {
+  constructor(public id: number, public title: string) {}
+}