useAvailableSlashes.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2017-2020 @polkadot/app-council authors & contributors
  2. // This software may be modified and distributed under the terms
  3. // of the Apache-2.0 license. See the LICENSE file for details.
  4. import { DeriveSessionIndexes } from '@polkadot/api-derive/types';
  5. import { EraIndex, UnappliedSlash } from '@polkadot/types/interfaces';
  6. import BN from 'bn.js';
  7. import { useEffect, useState } from 'react';
  8. import { useApi, useCall, useIsMountedRef } from '@polkadot/react-hooks';
  9. import { Option, Vec } from '@polkadot/types';
  10. type Unsub = () => void;
  11. export default function useAvailableSlashes (): [BN, UnappliedSlash[]][] {
  12. const { api } = useApi();
  13. const indexes = useCall<DeriveSessionIndexes>(api.derive.session?.indexes, []);
  14. const earliestSlash = useCall<Option<EraIndex>>(api.query.staking?.earliestUnappliedSlash, []);
  15. const mountedRef = useIsMountedRef();
  16. const [slashes, setSlashes] = useState<[BN, UnappliedSlash[]][]>([]);
  17. useEffect((): Unsub => {
  18. let unsub: Unsub | undefined;
  19. if (mountedRef.current && indexes && earliestSlash && earliestSlash.isSome) {
  20. const from = earliestSlash.unwrap();
  21. const range: BN[] = [];
  22. let start = new BN(from);
  23. while (start.lt(indexes.activeEra)) {
  24. range.push(start);
  25. start = start.addn(1);
  26. }
  27. if (range.length) {
  28. (async (): Promise<void> => {
  29. unsub = await api.query.staking.unappliedSlashes.multi<Vec<UnappliedSlash>>(range, (values): void => {
  30. mountedRef.current && setSlashes(
  31. values
  32. .map((value, index): [BN, UnappliedSlash[]] => [from.addn(index), value])
  33. .filter(([, slashes]): boolean => slashes.length !== 0)
  34. );
  35. });
  36. })().catch(console.error);
  37. }
  38. }
  39. return (): void => {
  40. unsub && unsub();
  41. };
  42. }, [api, earliestSlash, indexes, mountedRef]);
  43. return slashes;
  44. }