@polkadot/types#U32 TypeScript Examples

The following examples show how to use @polkadot/types#U32. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: api.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getProposalCount = async (
  api: ApiPromise,
  hash?: Hash
): Promise<number> =>
  (
    (await (hash
      ? api.query.proposalsEngine.proposalCount.at(hash)
      : api.query.proposalsEngine.proposalCount())) as u32
  ).toNumber()
Example #2
Source File: useInfo.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
optGiltInfo = {
  defaultValue: {} as GiltInfo,
  transform: ([activeTotal, queueTotals]: [ActiveGiltsTotal, [u32, BalanceOf][]]): GiltInfo => ({
    activeIndex: activeTotal.index.isZero()
      ? null
      : activeTotal.index.sub(BN_ONE),
    activeTotal,
    queueTotals: queueTotals
      .map(([numItems, balance], index): QueueTotal => ({ balance, index: index + 1, numItems }))
      .filter(({ balance }) => !balance.isZero())
  })
}
Example #3
Source File: useBlockCounts.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default function useBlockCounts (accountId: string, sessionRewards: SessionRewards[]): u32[] {
  const { api } = useApi();
  const mountedRef = useIsMountedRef();
  const indexes = useCall<DeriveSessionIndexes>(api.derive.session?.indexes);
  const current = useCall<u32>(api.query.imOnline?.authoredBlocks, [indexes?.currentIndex, accountId]);
  const [counts, setCounts] = useState<u32[]>([]);
  const [historic, setHistoric] = useState<u32[]>([]);

  useEffect((): void => {
    if (isFunction(api.query.imOnline?.authoredBlocks) && sessionRewards && sessionRewards.length) {
      const filtered = sessionRewards.filter(({ sessionIndex }): boolean => sessionIndex.gt(BN_ZERO));

      if (filtered.length) {
        Promise
          .all(filtered.map(({ parentHash, sessionIndex }): Promise<u32> =>
            api.query.imOnline.authoredBlocks.at(parentHash, sessionIndex.sub(BN_ONE), accountId)
          ))
          .then((historic): void => {
            mountedRef.current && setHistoric(historic);
          }).catch(console.error);
      }
    }
  }, [accountId, api, mountedRef, sessionRewards]);

  useEffect((): void => {
    setCounts([...historic, current || api.createType('u32')].slice(1));
  }, [api, current, historic]);

  return counts;
}
Example #4
Source File: Summary.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function Summary ({ className = '', members, proposals }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const { api } = useApi();
  const proposalCount = useCall<u32>(api.query.technicalCommittee.proposalCount);

  return (
    <SummaryBox className={className}>
      <CardSummary label={t<string>('members')}>
        {formatNumber(members.length)}
      </CardSummary>
      <section>
        <CardSummary label={t<string>('proposals')}>
          {formatNumber(proposals?.length)}
        </CardSummary>
        <CardSummary label={t<string>('total')}>
          {formatNumber(proposalCount)}
        </CardSummary>
      </section>
    </SummaryBox>
  );
}
Example #5
Source File: parachain.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * query winners info of active auction.
 */
 async function queryAuctionWithWinners(api: ApiPromise) {
  const minContribution = api.consts.crowdloan.minContribution as BlockNumber;
  const ranges = _getLeaseRanges(api);
  const [bestNumber, auctionInfo, fundData, leasesData, initialEntries] = await Promise.all([
    api.derive.chain.bestNumber(),
    _queryAuctionInfo(api),
    api.query.crowdloan.funds.entries(),
    api.query.slots.leases.entries(),
    api.query.auctions?.winning.entries()
  ]);

  const leases = leasesData.map(([paraId]) => paraId.toHuman()[0].replace(/,/g, ""));
  const funds = fundData.map(([paraId, info]) => _updateFund(bestNumber, minContribution, {info: (info as any).unwrapOr(null), paraId: paraId.toHuman()[0].replace(/,/g, "")}, leases)).filter(i => !!i);
  const loans = _getCrowdloanBids(auctionInfo, funds, new BN(ranges[ranges.length - 1][1]));

  const winningData = _extractData(ranges, auctionInfo, initialEntries);
  return {
    auction: !!auctionInfo.leasePeriod ? {
      ...auctionInfo,
      bestNumber: bestNumber.toString(),
      leasePeriod: auctionInfo.leasePeriod.toNumber(),
      leaseEnd: auctionInfo.leasePeriod.add(api.consts.auctions.leasePeriodsPerSlot as u32).isub(BN_ONE).toNumber()
    } : {},
    funds,
    winners: _mergeCrowdLoanBids(winningData[0]?.winners || [], loans || []),
  };
}
Example #6
Source File: QueryEventBlock.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
/**
 * If the event record was emitted by an extrinsic call,
 * and can extract the extrinsic index by looking at the `phase` object.
 *
 * @param record - event record as decoded by Polkadot API
 * @returns extrinsic index, if the phase is `applyExtrinsic` or `undefined` otherwise
 */
export function getExtrinsicIndex(record: {
  phase: { isApplyExtrinsic: boolean; asApplyExtrinsic: u32 }
}): number | undefined {
  const { phase } = record
  // Try to recover extrinsic: only possible if its right phase, and extrinsics arra is non-empty, the last constraint
  // is needed to avoid events from build config code in genesis, and possibly other cases.
  return phase.isApplyExtrinsic ? phase.asApplyExtrinsic.toNumber() : undefined
}
Example #7
Source File: QueryEventBlock.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
export function getExtrinsic(eventInBlock: {
  record: {
    phase: { isApplyExtrinsic: boolean; asApplyExtrinsic: u32 }
  }
  extrinsics: Extrinsic[]
}): Extrinsic | undefined {
  const extrinsicIndex = getExtrinsicIndex(eventInBlock.record)

  return getOrUndefined(extrinsicIndex, eventInBlock.extrinsics)
}
Example #8
Source File: council.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
async function getProposals(api: ApiPromise, range: BlockRange) {
  let startProposalCount = Number(
    (
      (await api.query.proposalsEngine.proposalCount.at(
        range.startBlockHash
      )) as U32
    ).toBigInt()
  );
  let endProposalCount = Number(
    (
      (await api.query.proposalsEngine.proposalCount.at(
        range.endBlockHash
      )) as U32
    ).toBigInt()
  );

  let proposals = new Array<ProposalInfo>();
  for (let i = startProposalCount - 1; i <= endProposalCount; i++) {
    try {
      const proposal = await getProposal(api, range, i);
      if (proposal) proposals.push(proposal);
    } catch (e) {
      console.error(`Failed to fetch proposal ${i}: ${e.message}`);
    }
  }

  return proposals;
}
Example #9
Source File: substrate.ts    From subsocial-js with GNU General Public License v3.0 6 votes vote down vote up
getSubstrateApi = async (nodeUrl?: string) => {
  if (api) return api

  const rpcEndpoint = nodeUrl || 'ws://127.0.0.1:9944/';
  const provider = new WsProvider(rpcEndpoint);

  logger.info(`Connecting to Substrate node at ${rpcEndpoint}...`);
  api = new ApiPromise({ provider, typesBundle })
  await api.isReady

  const properties = await api.rpc.system.properties() as ChainProperties
  const tokenSymbol = properties.tokenSymbol.unwrapOr(undefined)?.map((x: Text) => x.toString());
  const tokenDecimals = properties.tokenDecimals.unwrapOr(undefined)?.map((x: U32) => x.toNumber());

  registry.setChainProperties(properties)

  formatBalance.setDefaults({
    decimals: tokenDecimals,
    unit: tokenSymbol
  });

  return api
}
Example #10
Source File: api.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
getCouncilRound = async (
  api: ApiPromise,
  hash: Hash
): Promise<number> =>
  ((await api.query.councilElection.round.at(hash)) as u32).toNumber()
Example #11
Source File: api.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
getCouncilSize = async (
  api: ApiPromise,
  hash: Hash
): Promise<number> =>
  ((await api.query.councilElection.councilSize.at(hash)) as u32).toNumber()
Example #12
Source File: api.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
getValidatorCount = async (
  api: ApiPromise,
  hash: Hash
): Promise<number> =>
  ((await api.query.staking.validatorCount.at(hash)) as u32).toNumber()
Example #13
Source File: phragmen_elections.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public async init(ChainInfo: SubstrateChain, Accounts: SubstrateAccounts): Promise<void> {
    this._disabled = !ChainInfo.api.query.elections;
    this._Chain = ChainInfo;
    this._Accounts = Accounts;

    const moduleName = ChainInfo.api.consts.elections
      ? 'elections'
      : ChainInfo.api.consts.phragmenElections
        ? 'phragmenElections'
        : 'electionsPhragmen';

    this._candidacyBond = this._Chain.coins(ChainInfo.api.consts[moduleName].candidacyBond as BalanceOf);
    this._votingBond = this._Chain.coins(ChainInfo.api.consts[moduleName].votingBond as BalanceOf);
    this._desiredMembers = +ChainInfo.api.consts[moduleName].desiredMembers;
    this._desiredRunnersUp = +ChainInfo.api.consts[moduleName].desiredRunnersUp;
    this._termDuration = +ChainInfo.api.consts[moduleName].termDuration;
    const members = (await ChainInfo.api.query[moduleName].members()) as Vec<any>;
    const runnersUp = (await ChainInfo.api.query[moduleName].runnersUp()) as Vec<any>;

    this._runnersUp = runnersUp.map((r) => ({
      who: r.who !== undefined ? r.who.toString() : r[0].toString(),
      // TODO: broken on KLP
      score: r.stake ? r.stake.toBn() : r[1].toBn()
    }));
    this._members = members.reduce((ms, r) => {
      const who = r.who !== undefined ? r.who : r[0];
      const bal = r.stake !== undefined ? r.stake : r[1];
      ms[who.toString()] = bal.toBn();
      return ms;
    }, {});

    const currentIndex = +(await ChainInfo.api.query[moduleName].electionRounds<u32>());
    const blockNumber = await ChainInfo.api.derive.chain.bestNumber();
    const termDuration = +ChainInfo.api.consts[moduleName].termDuration;
    const roundStartBlock = Math.floor((+blockNumber) / termDuration) * termDuration;
    const endBlock = roundStartBlock + termDuration;
    const p = {
      identifier: `${currentIndex}`,
      round: currentIndex,
      endBlock,
    };
    this._activeElection = new SubstratePhragmenElection(ChainInfo, Accounts, this, p, moduleName);
    this._initialized = true;
  }
Example #14
Source File: parachain.ts    From sdk with Apache License 2.0 5 votes vote down vote up
function _isU32 (leasePeriodsPerSlot: unknown): leasePeriodsPerSlot is u32 {
  return !!leasePeriodsPerSlot;
}
Example #15
Source File: council.ts    From community-repo with GNU General Public License v3.0 4 votes vote down vote up
async function main() {
  // Initialise the provider to connect to the local node
  const provider = new WsProvider('ws://127.0.0.1:9944');

  //If you want to play around on our staging network, go ahead and connect to this staging network instead.
  //const provider = new WsProvider('wss://testnet-rpc-2-singapore.joystream.org');
  
  // Create the API and wait until ready
  const api = await ApiPromise.create({ provider, types })
  // made this example with historical data, so you can check different councils/stages
  const blocks :number[] = [259200, 259201]

  // discounting this voter
  const joystreamVoter = "5CJzTaCp5fuqG7NdJQ6oUCwdmFHKichew8w4RZ3zFHM8qSe6"

  const councils: CouncilData[] = []
  for (let i=0; i<blocks.length; i++) {
    const councilMembers: CouncilMemberData[] = []
    const blockHash = await api.rpc.chain.getBlockHash(blocks[i]) as Hash
    const electionStatus = await api.query.councilElection.stage.at(blockHash) as Option<ElectionStage>
    const electionRound = await api.query.councilElection.round.at(blockHash) as u32
    console.log(`
      at block: ${blocks[i]},
      the election stage was: ${electionStatus.value.toString()},
      of election round: ${electionRound.toNumber()},
    `)
    if (electionStatus.value instanceof ElectionStage) {
      const electionStage = electionStatus.unwrap()
      if (electionStage.value instanceof Announcing) {
        console.log("In 'Announcing' stage - ends at block", electionStage.value.toNumber())
      } else if (electionStage.value instanceof Voting) {
        console.log("In 'Voting' stage - ends at block", electionStage.value.toNumber())
      } else if (electionStage.value instanceof Revealing) {
        console.log("In 'Revealing' stage - ends at block", electionStage.value.toNumber())
      } else {
      }
    }
    const activeCouncil = await api.query.council.activeCouncil.at(blockHash) as Seats
    if (!activeCouncil.isEmpty) {
      const elected: Participant[] = []
      for (let member of activeCouncil) {
        let otherStake = 0
        let jsgStake = 0
        const councilMemberId = await getParticipantAt(api, member.member, blockHash)
        const voters: VoterData[] = []
        elected.push(councilMemberId)
        for (let backer of member.backers) {
          const voterId = await getParticipantAt(api, backer.member, blockHash)
          const voter: VoterData = {
            voterId,
            voterStake: backer.stake.toNumber(),
            stakeRatioExJSGvotes: 0,
            kpiRewardRatio: 0,
          }
          otherStake += backer.stake.toNumber()
          if (backer.member.toString() === joystreamVoter) {
            jsgStake += backer.stake.toNumber()
          }
          voters.push(voter)
        }
        const ownStake = member.stake.toNumber()
        const totalStakeExJSGvotes = member.stake.toNumber() + otherStake - jsgStake
        const totalStake = member.stake.toNumber() + otherStake
        const councilMember: CouncilMemberData = {
          councilMemberId,
          totalStake,
          totalStakeExJSGvotes,
          ownStake,
          otherStake,
          otherStakeExJSGvotes: otherStake - jsgStake,
          stakeRatioExJSGvotes: ownStake/totalStakeExJSGvotes,
          voters,
        }
        councilMembers.push(councilMember)
      }
      let totalStakes = 0
      let totalStakesExJSGvotes = 0
      let ownStakes = 0
      let otherStakes = 0
      let otherStakesExJSGvotes = 0
      
      for (let councilMember of councilMembers) {
        totalStakes += councilMember.totalStake
        totalStakesExJSGvotes += councilMember.totalStakeExJSGvotes
        ownStakes += councilMember.ownStake
        otherStakes += councilMember.otherStake
        otherStakesExJSGvotes += councilMember.otherStakeExJSGvotes
      }
      for (let councilMember of councilMembers) {
        councilMember.kpiRewardRatio = councilMember.ownStake/totalStakesExJSGvotes
        for (let voter of councilMember.voters) {
          if (voter.voterId.accountId != joystreamVoter) {
            voter.stakeRatioExJSGvotes = voter.voterStake/councilMember.totalStakeExJSGvotes
            voter.kpiRewardRatio = voter.voterStake/totalStakesExJSGvotes
          }
        }
      }
      const termEnd = (await api.query.council.termEndsAt.at(blockHash) as BlockNumber).toNumber()
      const announcing = (await api.query.councilElection.announcingPeriod.at(blockHash) as BlockNumber).toNumber()
      const voting = (await api.query.councilElection.votingPeriod.at(blockHash) as BlockNumber).toNumber()
      const revealing = (await api.query.councilElection.votingPeriod.at(blockHash) as BlockNumber).toNumber()
      const term = (await api.query.councilElection.newTermDuration.at(blockHash) as BlockNumber).toNumber()
 
      // this will not always be correct...
      const electedAtBlock = termEnd-term
      const newCouncilStartsAt = termEnd+announcing+voting+revealing
      const electedHash = await api.rpc.chain.getBlockHash(electedAtBlock) as Hash
      const getRewardInterval = await api.query.council.payoutInterval.at(electedHash) as Option<BlockNumber>

      const councilMint = await api.query.council.councilMint.at(electedHash) as MintId
      const mintAtStart = await api.query.minting.mints.at(electedHash,councilMint) as Mint
      const mintCapacityAtStart = mintAtStart.capacity.toNumber()
      
      let rewardInterval = 3600
      if (!(getRewardInterval.value instanceof Null)) {
        rewardInterval = getRewardInterval.unwrap().toNumber()
      }

      const rewardamountPerPayout = (await api.query.council.amountPerPayout.at(electedHash) as BalanceOf).toNumber()
      const expectedIndividualRewards = rewardamountPerPayout*term/rewardInterval

      const council: CouncilData = {
        electionCycle: electionRound.toNumber(),
        electedAtBlock,
        mintCapacityAtStart,
        rewardamountPerPayout,
        rewardInterval,
        termEnd: termEnd,
        expectedIndividualRewards,
        newCouncilStartsAt,
        totalStakes,
        totalStakesExJSGvotes,
        ownStakes,
        otherStakes,
        otherStakesExJSGvotes,
        elected,
        electionData: councilMembers,
      }
      const bestHeight = (await api.derive.chain.bestNumber()).toNumber()
      if (bestHeight>newCouncilStartsAt) {
        const endHash = await api.rpc.chain.getBlockHash(newCouncilStartsAt) as Hash
        const mintAtEnd = await api.query.minting.mints.at(endHash,councilMint) as Mint
        council.mintCapacityAtEnd = mintAtEnd.capacity.toNumber()
        council.councilSpending = mintAtEnd.total_minted.toNumber() - mintAtStart.total_minted.toNumber()
      }
      councils.push(council)
    }
  }
  console.log("councils",JSON.stringify(councils, null, 4))
  api.disconnect()
}
Example #16
Source File: council.ts    From community-repo with GNU General Public License v3.0 4 votes vote down vote up
export async function generateReportData(
  api: ApiPromise,
  blockRange: BlockRange
) {
  const averageBlockProductionTime = await computeAverageBlockProductionTime(
    api,
    blockRange
  );

  const proposals = await getProposals(api, blockRange);
  const electionRound = (await api.query.councilElection.round.at(
    blockRange.startBlockHash
  )) as u32;

  const roundInfo = await getCouncilMembersInfo(api, blockRange, proposals);
  const { members, membersOwnStake, backersTotalStake } = roundInfo;
  const { startMinted, endMinted } = roundInfo;

  let councilTable =
    "| Username             | Member ID | Prop. Votes Cast | CM Own Stake | CM Voter Stake |\n" +
    "|----------------------|-----------|------------------|--------------|----------------|\n";

  for (const member of members) {
    const { username, memberId, votesInProposals, ownStake, backersStake } =
      member;
    councilTable += `| @${username} | ${memberId} | ${votesInProposals} | ${ownStake} | ${backersStake} |\n`;
  }
  councilTable += `| | | Subtotal: | ${membersOwnStake} | ${backersTotalStake} |\n`;
  const totalStake = membersOwnStake + backersTotalStake;
  councilTable += `| | | Total: | ${totalStake} |  |\n`;

  const councilSecretary = getCouncilSecretary(proposals);
  const councilSecretaryDeputy = getCouncilSecretaryDeputy(proposals);

  let proposalsBreakdownText = "";
  for (const proposal of proposals) {
    const { id, name, type, status, failedReason, paymentAmount } = proposal;
    const { creatorUsername, votersUsernames, blocksToFinalized } = proposal;

    let proposalStatusText = "";
    switch (status) {
      case ProposalStatus.Active:
        proposalStatusText = "Passed to next council";
        break;
      case ProposalStatus.Executed:
        proposalStatusText = "Approved & Executed";
        break;
      case ProposalStatus.ExecutionFailed:
        const reason =
          ProposalFailedReason[failedReason as ProposalFailedReason];
        proposalStatusText = `Execution failed (${reason})`;
        break;
      case ProposalStatus.PendingExecution:
        proposalStatusText = "Execution Pending";
        break;
      case ProposalStatus.Rejected:
        proposalStatusText = "Rejected";
        break;
      case ProposalStatus.Cancelled:
        proposalStatusText = "Canceled";
        break;
      case ProposalStatus.Expired:
        proposalStatusText = "Expired";
        break;
      case ProposalStatus.Slashed:
        proposalStatusText = "Slashed";
        break;
    }

    proposalsBreakdownText += `#### Proposal ${id} - ${name}\n`;
    proposalsBreakdownText += `- Proposal Link: ${PROPOSAL_URL}${id}\n`;
    proposalsBreakdownText += `- Proposal Type: ${ProposalType[type]}\n`;

    if (paymentAmount)
      proposalsBreakdownText += `\t- Amount: ${paymentAmount}\n`;

    if (proposal.paymentDestinationMemberUsername)
      proposalsBreakdownText += `\t- Destination member: ${proposal.paymentDestinationMemberUsername}\n`;

    proposalsBreakdownText += `- Status: ${proposalStatusText}\n`;
    if (blocksToFinalized > 0 && status != ProposalStatus.Cancelled) {
      const time = averageBlockProductionTime;
      const days = convertBlocksToHours(blocksToFinalized, time);
      proposalsBreakdownText += `\t- Time to finalize: ${blocksToFinalized} blocks (${days}h)\n`;
    }
    proposalsBreakdownText += `- Created by: @${creatorUsername}\n`;
    let participantsText = votersUsernames.map((vote) => `@${vote}`).join(", ");
    proposalsBreakdownText += `- Participants: ${participantsText}\n\n`;
  }
  proposalsBreakdownText = proposalsBreakdownText.substring(
    0,
    proposalsBreakdownText.length - 2
  ); //Remove last \n\n

  let reportData = new ReportData();
  reportData.averageBlockProductionTime = averageBlockProductionTime.toFixed(2);
  reportData.electionRound = Number(electionRound.toBigInt());
  reportData.councilTerm = reportData.electionRound - ELECTION_OFFSET;
  reportData.startBlockHeight = blockRange.startBlockHeight;
  reportData.endBlockHeight = blockRange.endBlockHeight;
  reportData.startMinted = startMinted;
  reportData.endMinted = endMinted;

  reportData.totalNewMinted = endMinted - startMinted;
  reportData.percNewMinted = convertToPercentage(startMinted, endMinted);

  reportData.councilTable = councilTable;
  reportData.councilSecretary =
    councilSecretary == "" ? "?" : "@" + councilSecretary;
  reportData.councilDeputySecretary =
    councilSecretaryDeputy == "" ? "?" : "@" + councilSecretaryDeputy;

  reportData.proposalsCreated = proposals.length;
  reportData.textProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.Text
  ).length;
  reportData.spendingProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.Spending
  ).length;
  reportData.setWorkingGroupLeaderRewardProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.SetWorkingGroupLeaderReward
  ).length;
  reportData.setWorkingGroupMintCapacityProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.SetWorkingGroupMintCapacity
  ).length;
  reportData.beginReviewWorkingGroupLeaderApplicationProposals =
    proposals.filter(
      (proposal) =>
        proposal.type == ProposalType.BeginReviewWorkingGroupLeaderApplication
    ).length;
  reportData.terminateWorkingGroupLeaderRoleProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.TerminateWorkingGroupLeaderRole
  ).length;
  reportData.fillWorkingGroupLeaderOpeningProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.FillWorkingGroupLeaderOpening
  ).length;
  reportData.setValidatorCountProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.SetValidatorCount
  ).length;
  reportData.addWorkingGroupLeaderOpeningProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.AddWorkingGroupLeaderOpening
  ).length;
  reportData.setElectionParametersProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.SetElectionParameters
  ).length;
  reportData.runtimeUpgradeProposals = proposals.filter(
    (proposal) => proposal.type == ProposalType.RuntimeUpgrade
  ).length;

  reportData.approvedExecutedProposals = proposals.filter(
    (proposal) => proposal.status == ProposalStatus.Executed
  ).length;
  reportData.canceledProposals = proposals.filter(
    (proposal) => proposal.status == ProposalStatus.Cancelled
  ).length;
  reportData.rejectedProposals = proposals.filter(
    (proposal) => proposal.status == ProposalStatus.Rejected
  ).length;
  reportData.slashedProposals = proposals.filter(
    (proposal) => proposal.status == ProposalStatus.Slashed
  ).length;
  reportData.expiredProposals = proposals.filter(
    (proposal) => proposal.status == ProposalStatus.Expired
  ).length;
  reportData.activeProposals = proposals.filter(
    (proposal) => proposal.status == ProposalStatus.Active
  ).length;

  let executedNonCancelledProposals = proposals.filter(
    ({ status, blocksToFinalized }) =>
      blocksToFinalized > 0 && status != ProposalStatus.Cancelled
  );
  let totalFinalizeTime = executedNonCancelledProposals.reduce(
    (accumulator, proposal) => accumulator + proposal.blocksToFinalized,
    0
  );
  let averageFinalizeTime =
    totalFinalizeTime / executedNonCancelledProposals.length;

  let failedProposals = proposals.filter(
    (proposal) => proposal.status == ProposalStatus.ExecutionFailed
  );

  reportData.proposalsFailedForNotEnoughCapacity = failedProposals.filter(
    ({ failedReason }) => failedReason == ProposalFailedReason.NotEnoughCapacity
  ).length;
  reportData.proposalsFailedForExecutionFailed = failedProposals.filter(
    ({ failedReason }) => failedReason == ProposalFailedReason.ExecutionFailed
  ).length;

  reportData.totalProposalsFinalizeTime = convertBlocksToHours(
    totalFinalizeTime,
    averageBlockProductionTime
  );
  reportData.averageTimeForProposalsToFinalize = convertBlocksToHours(
    averageFinalizeTime,
    averageBlockProductionTime
  );
  reportData.proposalBreakdown = proposalsBreakdownText;
  return reportData;
}