@polkadot/types/interfaces#EraRewardPoints TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#EraRewardPoints. 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: dataGatherer.ts    From polkadot-watcher-csv-exporter with Apache License 2.0 6 votes vote down vote up
_getMyValidatorStaking = async (api: ApiPromise, apiChunkSize: number, nominatorsStakings: DeriveStakingAccount[], eraPoints: EraRewardPoints, eraExposures: DeriveEraExposure, logger: Logger): Promise<MyDeriveStakingAccount[]> =>{
  const validatorsAddresses = await api.query.session.validators();
  logger.debug(`the validator addresses size is ${validatorsAddresses.length}`)

  //A too big nominators set could make crush the API => Chunk splitting
  const size = apiChunkSize
  const validatorsAddressesChucked = []
  for (let i = 0; i < validatorsAddresses.length; i += size) {
    const chunk = validatorsAddresses.slice(i, i + size)
    validatorsAddressesChucked.push(chunk)
  } 

  const validatorsStakings: DeriveStakingAccount[] = []
  for (const chunk of validatorsAddressesChucked) {
    logger.debug(`the handled chunk size is ${chunk.length}`)
    validatorsStakings.push(...await api.derive.staking.accounts(chunk))
  }

  return await _buildMyValidatorStaking(api,validatorsStakings,nominatorsStakings,eraPoints,eraExposures)
}
Example #2
Source File: dataGatherer.ts    From polkadot-watcher-csv-exporter with Apache License 2.0 6 votes vote down vote up
_getMyWaitingValidatorStaking = async (api: ApiPromise, apiChunkSize: number, nominatorsStakings: DeriveStakingAccount[], eraPoints: EraRewardPoints, eraExposures: DeriveEraExposure, logger: Logger): Promise<MyDeriveStakingAccount[]> => {
  const validatorsAddresses = await _getWaitingValidatorsAccountId(api)
  logger.debug(`the waiting validator addresses size is ${validatorsAddresses.length}`)

  //A too big nominators set could make crush the API => Chunk splitting
  const size = apiChunkSize
  const validatorsAddressesChucked = []
  for (let i = 0; i < validatorsAddresses.length; i += size) {
    const chunk = validatorsAddresses.slice(i, i + size)
    validatorsAddressesChucked.push(chunk)
  } 

  const validatorsStakings: DeriveStakingAccount[] = []
  for (const chunk of validatorsAddressesChucked) {
    logger.debug(`the handled chunk size is ${chunk.length}`)
    validatorsStakings.push(...await api.derive.staking.accounts(chunk))
  }

  return await _buildMyValidatorStaking(api,validatorsStakings,nominatorsStakings,eraPoints,eraExposures)
}
Example #3
Source File: dataGatherer.ts    From polkadot-watcher-csv-exporter with Apache License 2.0 6 votes vote down vote up
_buildMyValidatorStaking = async (api: ApiPromise, validatorsStakings: DeriveStakingAccount[], nominatorsStakings: DeriveStakingAccount[], eraPoints: EraRewardPoints, eraExposures: DeriveEraExposure): Promise<MyDeriveStakingAccount[]> =>{
  const myValidatorStaking = Promise.all ( validatorsStakings.map( async validatorStaking => {

    const validatorAddress = validatorStaking.accountId
    const infoPromise = api.derive.accounts.info(validatorAddress);

    const validatorEraPoints = eraPoints.toJSON()['individual'][validatorAddress.toHuman()] ? eraPoints.toJSON()['individual'][validatorAddress.toHuman()] : 0

    const exposure = eraExposures.validators[validatorAddress.toHuman()] ? eraExposures.validators[validatorAddress.toHuman()] : {total:0,own:0,others:[]}

    const voters: Voter[] = []
    for (const staking of nominatorsStakings) {
      if (staking.nominators.includes(validatorAddress)) {
        voters.push({address: staking.accountId.toString(), value: staking.stakingLedger.total })
      }
    }

    const {identity} = await infoPromise
    return {
      ...validatorStaking,
      displayName: getDisplayName(identity),
      voters: voters,
      exposure: exposure,
      eraPoints: validatorEraPoints,
    } as MyDeriveStakingAccount

  }))
  return myValidatorStaking
}
Example #4
Source File: BlockAuthors.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function BlockAuthorsBase ({ children }: Props): React.ReactElement<Props> {
  const { api, isApiReady } = useApi();
  const queryPoints = useCall<EraRewardPoints>(isApiReady && api.derive.staking?.currentPoints);
  const [state, setState] = useState<Authors>({ byAuthor, eraPoints, lastBlockAuthors: [], lastHeaders: [] });
  const [validators, setValidators] = useState<string[]>([]);

  useEffect((): void => {
    // No unsub, global context - destroyed on app close
    api.isReady.then((): void => {
      let lastHeaders: HeaderExtended[] = [];
      let lastBlockAuthors: string[] = [];
      let lastBlockNumber = '';

      // subscribe to all validators
      api.query.session && api.query.session.validators((validatorIds): void => {
        setValidators(validatorIds.map((validatorId) => validatorId.toString()));
      }).catch(console.error);

      // subscribe to new headers
      api.derive.chain.subscribeNewHeads((lastHeader): void => {
        if (lastHeader?.number) {
          const blockNumber = lastHeader.number.unwrap();
          const thisBlockAuthor = lastHeader.author?.toString();
          const thisBlockNumber = formatNumber(blockNumber);

          if (thisBlockAuthor) {
            byAuthor[thisBlockAuthor] = thisBlockNumber;

            if (thisBlockNumber !== lastBlockNumber) {
              lastBlockNumber = thisBlockNumber;
              lastBlockAuthors = [thisBlockAuthor];
            } else {
              lastBlockAuthors.push(thisBlockAuthor);
            }
          }

          lastHeaders = lastHeaders
            .filter((old, index) => index < MAX_HEADERS && old.number.unwrap().lt(blockNumber))
            .reduce((next, header): HeaderExtended[] => {
              next.push(header);

              return next;
            }, [lastHeader])
            .sort((a, b) => b.number.unwrap().cmp(a.number.unwrap()));

          setState({ byAuthor, eraPoints, lastBlockAuthors: lastBlockAuthors.slice(), lastBlockNumber, lastHeader, lastHeaders });
        }
      }).catch(console.error);
    }).catch(console.error);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect((): void => {
    if (queryPoints) {
      const entries = [...queryPoints.individual.entries()]
        .map(([accountId, points]) => [accountId.toString(), formatNumber(points)]);
      const current = Object.keys(eraPoints);

      // we have an update, clear all previous
      if (current.length !== entries.length) {
        current.forEach((accountId): void => {
          delete eraPoints[accountId];
        });
      }

      entries.forEach(([accountId, points]): void => {
        eraPoints[accountId] = points;
      });
    }
  }, [queryPoints]);

  return (
    <ValidatorsContext.Provider value={validators}>
      <BlockAuthorsContext.Provider value={state}>
        {children}
      </BlockAuthorsContext.Provider>
    </ValidatorsContext.Provider>
  );
}
Example #5
Source File: BlockAuthors.tsx    From subscan-multisig-react with Apache License 2.0 4 votes vote down vote up
function BlockAuthorsBase({ children }: Props): React.ReactElement<Props> {
  const { api, isApiReady } = useApi();
  const queryPoints = useCall<EraRewardPoints>(isApiReady && api.derive.staking?.currentPoints);
  const [state, setState] = useState<Authors>({ byAuthor, eraPoints, lastBlockAuthors: [], lastHeaders: [] });
  const [validators, setValidators] = useState<string[]>([]);

  useEffect((): void => {
    // No unsub, global context - destroyed on app close
    api?.isReady
      .then((): void => {
        let lastHeaders: HeaderExtendedWithMapping[] = [];
        let lastBlockAuthors: string[] = [];
        let lastBlockNumber = '';
        const isAuthorMapping = isFunction(api.query.authorMapping?.mapping);

        // subscribe to all validators
        api.query.session &&
          api.query.session
            .validators((validatorIds: any): void => {
              setValidators(validatorIds.map((validatorId: any) => validatorId.toString()));
            })
            .catch(console.error);

        // subscribe to new headers
        api.derive.chain
          .subscribeNewHeads(async (lastHeader: HeaderExtendedWithMapping): Promise<void> => {
            if (lastHeader?.number) {
              const blockNumber = lastHeader.number.unwrap();
              let thisBlockAuthor = '';

              if (lastHeader.author) {
                thisBlockAuthor = lastHeader.author.toString();
              } else if (
                isAuthorMapping &&
                lastHeader.digest.logs &&
                lastHeader.digest.logs[0] &&
                lastHeader.digest.logs[0].isConsensus &&
                lastHeader.digest.logs[0].asConsensus[1]
              ) {
                // Some blockchains such as Moonbeam need to fetch the author accountId from a mapping
                thisBlockAuthor = (
                  await api.query.authorMapping.mapping(lastHeader.digest.logs[0].asConsensus[1])
                ).toString();
                lastHeader.authorFromMapping = thisBlockAuthor;
              }

              const thisBlockNumber = formatNumber(blockNumber);

              if (thisBlockAuthor) {
                byAuthor[thisBlockAuthor] = thisBlockNumber;

                if (thisBlockNumber !== lastBlockNumber) {
                  lastBlockNumber = thisBlockNumber;
                  lastBlockAuthors = [thisBlockAuthor];
                } else {
                  lastBlockAuthors.push(thisBlockAuthor);
                }
              }

              lastHeaders = lastHeaders
                .filter((old, index) => index < MAX_HEADERS && old.number.unwrap().lt(blockNumber))
                .reduce(
                  (next, header): HeaderExtendedWithMapping[] => {
                    next.push(header);

                    return next;
                  },
                  [lastHeader]
                )
                .sort((a, b) => b.number.unwrap().cmp(a.number.unwrap()));

              setState({
                byAuthor,
                eraPoints,
                lastBlockAuthors: lastBlockAuthors.slice(),
                lastBlockNumber,
                lastHeader,
                lastHeaders,
              });
            }
          })
          .catch(console.error);
      })
      .catch(console.error);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect((): void => {
    if (queryPoints) {
      const entries = [...queryPoints.individual.entries()].map(([accountId, points]) => [
        accountId.toString(),
        formatNumber(points),
      ]);
      const current = Object.keys(eraPoints);

      // we have an update, clear all previous
      if (current.length !== entries.length) {
        current.forEach((accountId): void => {
          delete eraPoints[accountId];
        });
      }

      entries.forEach(([accountId, points]): void => {
        eraPoints[accountId] = points;
      });
    }
  }, [queryPoints]);

  return (
    <ValidatorsContext.Provider value={validators}>
      <BlockAuthorsContext.Provider value={state}>{children}</BlockAuthorsContext.Provider>
    </ValidatorsContext.Provider>
  );
}