@polkadot/types/interfaces#Exposure TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#Exposure. 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: EffectiveStake.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function EffectiveStake ({ activeEra, stashId }: Props): React.ReactElement<Props> {
  const { api } = useApi();

  const exposure = useCall<Exposure>(api.query.staking.erasStakers, [JSON.stringify(activeEra), stashId]);
  let stakeValue = new BN(0);

  if (exposure && JSON.parse(JSON.stringify(exposure)) !== null) {
    stakeValue = exposure.own.unwrap();
  }

  return (
    <td className='number all'>
      {(
        <FormatBalance value={stakeValue} />
      )}
    </td>
  );
}
Example #2
Source File: Guaranteeable.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function GuaranteeableDisplay ({ params }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();

  const { api } = useApi();
  const stakeLimit = useCall<Option<Balance>>(api.query.staking.stakeLimit, [params]);
  const activeEraInfo = useCall<ActiveEraInfo>(api.query.staking.activeEra);

  const activeEra = activeEraInfo && (JSON.parse(JSON.stringify(activeEraInfo)).index);

  const accountIdBonded = useCall<string | null>(api.query.staking.bonded, [params], transformBonded);
  const controllerActive = useCall<Balance | null>(api.query.staking.ledger, [accountIdBonded], transformLedger);
  const erasStakersStashExposure = useCall<Option<Exposure>>(api.query.staking.erasStakers, [activeEra, params]);
  const erasStakersStash = erasStakersStashExposure && (parseObj(erasStakersStashExposure).others.map((e: { who: any; }) => e.who));

  const stakersGuarantees = useCall<Guarantee[]>(api.query.staking.guarantors.multi, [erasStakersStash]);
  let totalStaked = new BN(Number(controllerActive).toString());

  if (stakersGuarantees) {
    for (const stakersGuarantee of stakersGuarantees) {
      if (parseObj(stakersGuarantee)) {
        for (const target of parseObj(stakersGuarantee)?.targets) {
          if (target.who.toString() == params?.toString()) {
            totalStaked = totalStaked?.add(new BN(Number(target.value).toString()));
          }
        }
      }
    }
  }

  return (
    <>
      <span className='highlight'>{t<string>('total stakes')} {formatBalance(totalStaked, { withUnit: true })} / {t<string>('stake limit')} { formatBalance(new BN(Number(stakeLimit).toString()))}</span>
    </>
  );
}
Example #3
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function useAddressCalls (api: ApiPromise, address: string, isMain?: boolean) {
  const params = useMemo(() => [address], [address]);
  const stakeLimit = useCall<BN>(api.query.staking.stakeLimit, params);
  const accountInfo = useCall<DeriveAccountInfo>(api.derive.accounts.info, params);
  const slashingSpans = useCall<SlashingSpans | null>(!isMain && api.query.staking.slashingSpans, params, transformSlashes);
  const activeEraInfo = useCall<ActiveEraInfo>(api.query.staking.activeEra);
  const activeEra = activeEraInfo && (JSON.parse(JSON.stringify(activeEraInfo)).index);
  const erasStakersStashExposure = useCall<Exposure>(api.query.staking.erasStakers, [activeEra, address]);
  const accountIdBonded = useCall<string | null>(api.query.staking.bonded, params, transformBonded);
  const controllerActive = useCall<Balance | null>(api.query.staking.ledger, [accountIdBonded], transformLedger);
  const erasStakersStash = erasStakersStashExposure && (parseObj(erasStakersStashExposure).others.map((e: { who: any; }) => e.who));

  const stakersGuarantees = useCall<Guarantee[]>(api.query.staking.guarantors.multi, [erasStakersStash]);
  let totalStaked = new BN(Number(controllerActive).toString());

  if (stakersGuarantees) {
    for (const stakersGuarantee of stakersGuarantees) {
      if (parseObj(stakersGuarantee)) {
        for (const target of parseObj(stakersGuarantee)?.targets) {
          if (target.who.toString() == address) {
            totalStaked = totalStaked?.add(new BN(Number(target.value).toString()));
          }
        }
      }
    }
  }

  return { accountInfo, slashingSpans, totalStaked, stakeLimit, activeEra };
}
Example #4
Source File: EffectiveGuaranteed.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function EffectiveGuaranteed ({ activeEra, stakeValue, stashId, validators }: Props): React.ReactElement<Props> {
  const { api } = useApi();

  const guaranteeTargets: [string, BN, BN][] = [];

  if (validators && JSON.parse(JSON.stringify(validators)) !== null && activeEra && JSON.parse(JSON.stringify(activeEra)) !== null) {
    let tmpTargets = JSON.parse(JSON.stringify(validators));
    let params = tmpTargets.map((e: { who: any; }) => e.who);
    let query = [];
    for (const param of params) {
      query.push([activeEra, param]);
    };
    const multiQuery = useCall<Exposure[]>(api.query.staking.erasStakers.multi, [query]);

    if (multiQuery) {
      for (let index = 0; index < tmpTargets?.length; index++) {
        let guaranteeTarget:[string, BN, BN] = [tmpTargets[index].who, new BN('0'), new BN(Number(tmpTargets[index].value).toString())];
        const exposure = multiQuery[index];
        if (exposure) {
          for (const other of exposure.others) {
            if (other.who.toString() === stashId) {
              guaranteeTarget[1] = new BN(Number(other.value).toString());
            }
          }
        }
        guaranteeTargets.push(guaranteeTarget);
      }
    }
    stakeValue = guaranteeTargets.reduce((total: BN, [, value]) => { return total.add(new BN(Number(value).toString()))}, BN_ZERO);
  }


  return (
    <td className='number all'>
      {(
        <>
          <Expander summary={
            <FormatBalance
              labelPost={` (${validators.length})`}
              value={stakeValue}
            />
          }>
            {guaranteeTargets.map(([who, effective, total]): React.ReactNode =>               
              <AddressMiniForEffectiveStake value={who} totalStake={total} effectiveStake={effective}/>
            )}
          </Expander>
        </>
      )}
    </td>
  );
}
Example #5
Source File: useInactives.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
function extractState (api: ApiPromise, stashId: string, slashes: Option<SlashingSpans>[], nominees: string[], { activeEra }: DeriveSessionIndexes, submittedIn: EraIndex, exposures: Exposure[]): Inactives {
  const max = api.consts.staking?.maxNominatorRewardedPerValidator;

  // chilled
  const nomsChilled = nominees.filter((_, index): boolean => {
    if (slashes[index].isNone) {
      return false;
    }

    const { lastNonzeroSlash } = slashes[index].unwrap();

    return !lastNonzeroSlash.isZero() && lastNonzeroSlash.gte(submittedIn);
  });

  // all nominations that are oversubscribed
  const nomsOver = exposures
    .map(({ others }) => others.sort((a, b) => b.value.unwrap().cmp(a.value.unwrap())))
    .map((others, index) =>
      !max || max.gtn(others.map(({ who }) => who.toString()).indexOf(stashId))
        ? null
        : nominees[index]
    )
    .filter((nominee): nominee is string => !!nominee && !nomsChilled.includes(nominee));

  // first a blanket find of nominations not in the active set
  let nomsInactive = exposures
    .map((exposure, index) =>
      exposure.others.some(({ who }) => who.eq(stashId))
        ? null
        : nominees[index]
    )
    .filter((nominee): nominee is string => !!nominee);

  // waiting if validator is inactive or we have not submitted long enough ago
  const nomsWaiting = exposures
    .map((exposure, index) =>
      exposure.total.unwrap().isZero() || (
        nomsInactive.includes(nominees[index]) &&
        // it could be activeEra + 1 (currentEra for last session)
        submittedIn.gte(activeEra)
      )
        ? nominees[index]
        : null
    )
    .filter((nominee): nominee is string => !!nominee)
    .filter((nominee) => !nomsChilled.includes(nominee) && !nomsOver.includes(nominee));

  // filter based on all inactives
  const nomsActive = nominees.filter((nominee) => !nomsInactive.includes(nominee) && !nomsChilled.includes(nominee) && !nomsOver.includes(nominee));

  // inactive also contains waiting, remove those
  nomsInactive = nomsInactive.filter((nominee) => !nomsWaiting.includes(nominee) && !nomsChilled.includes(nominee) && !nomsOver.includes(nominee));

  return {
    nomsActive,
    nomsChilled,
    nomsInactive,
    nomsOver,
    nomsWaiting
  };
}
Example #6
Source File: useInactives.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export default function useInactives (stashId: string, nominees?: string[]): Inactives {
  const { api } = useApi();
  const mountedRef = useIsMountedRef();
  const [state, setState] = useState<Inactives>({});
  const indexes = useCall<DeriveSessionIndexes>(api.derive.session.indexes);

  useEffect((): () => void => {
    let unsub: (() => void) | undefined;

    if (mountedRef.current && nominees && nominees.length && indexes) {
      api
        .queryMulti(
          [[api.query.staking.nominators, stashId] as any]
            .concat(
              api.query.staking.erasStakers
                ? nominees.map((id) => [api.query.staking.erasStakers, [indexes.activeEra, id]])
                : nominees.map((id) => [api.query.staking.stakers, id])
            )
            .concat(
              nominees.map((id) => [api.query.staking.slashingSpans, id])
            ),
          ([optNominators, ...exposuresAndSpans]: [Option<Nominations>, ...(Exposure | Option<SlashingSpans>)[]]): void => {
            const exposures = exposuresAndSpans.slice(0, nominees.length) as Exposure[];
            const slashes = exposuresAndSpans.slice(nominees.length) as Option<SlashingSpans>[];

            mountedRef.current && setState(
              extractState(api, stashId, slashes, nominees, indexes, optNominators.unwrapOrDefault().submittedIn, exposures)
            );
          }
        )
        .then((_unsub): void => {
          unsub = _unsub;
        }).catch(console.error);
    }

    return (): void => {
      unsub && unsub();
    };
  }, [api, indexes, mountedRef, nominees, stashId]);

  return state;
}
Example #7
Source File: useOwnEraRewards.ts    From crust-apps with Apache License 2.0 4 votes vote down vote up
export function useOwnEraRewards (maxEras?: number, ownValidators?: StakerState[]): State {
  const { api } = useApi();
  const mountedRef = useIsMountedRef();
  const stashIds = useOwnStashIds();
  const allEras = useCall<EraIndex[]>(api.derive.staking?.erasHistoric);
  const [{ filteredEras, validatorEras }, setFiltered] = useState<Filtered>({ filteredEras: [], validatorEras: [] });
  const [state, setState] = useState<State>({ isLoadingRewards: true, rewardCount: 0 });
  const stakerRewards = useCall<[[string[]], DeriveStakerReward[][]]>(!ownValidators?.length && !!filteredEras.length && stashIds && api.derive.staking?.stakerRewardsMultiEras, [stashIds, filteredEras], { withParams: true });
  const erasPoints = useCall<DeriveEraPoints[]>(!!validatorEras.length && !!filteredEras.length && api.derive.staking._erasPoints, [filteredEras, false]);
  const erasRewards = useCall<DeriveEraRewards[]>(!!validatorEras.length && !!filteredEras.length && api.derive.staking._erasRewards, [filteredEras, false]);
  const stakingOverview = useCall<DeriveStakingOverview>(api.derive.staking.overview);
  const waitingInfo = useCall<DeriveStakingWaiting>(api.derive.staking.waitingInfo);
  const allValidators = stakingOverview && waitingInfo && [...waitingInfo.waiting, ...stakingOverview.nextElected];
  const stakingAccounts = useCall<DeriveStakingAccount[]>(allValidators && api.derive.staking.accounts, [allValidators]);
  const [eraStashExposure, setEraStashExposure] = useState<EraStashExposure[]>([]);
  const [eraStakingPayouts, setEraStakingPayouts] = useState<EraStakingPayout[]>();

  useEffect(() => {
    let unsub: (() => void) | undefined;

    if (allValidators && filteredEras && mountedRef.current) {
      const query: [EraIndex, string][] = [];

      for (const v of allValidators) {
        filteredEras.forEach((era) => query.push([era, v.toString()]));
      }

      const fns: any[] = [
        [api.query.staking.erasStakers.multi as any, query]
      ];

      api.combineLatest<Exposure[]>(fns, ([exposures]): void => {
        const tmp: EraStashExposure[] = [];

        if (Array.isArray(exposures) && mountedRef.current && exposures.length && exposures.length === query.length) {
          for (const [index, a] of query.entries()) {
            tmp.push({
              era: a[0],
              stashId: a[1],
              exposure: exposures[index]
            });
          }

          setEraStashExposure(tmp);
        }
      }).then((_unsub): void => {
        unsub = _unsub;
      }).catch(console.error);
    }

    return (): void => {
      unsub && unsub();
    };
  }, [filteredEras, allValidators]);

  useEffect(() => {
    let unsub: (() => void) | undefined;

    if (filteredEras && mountedRef.current) {
      const query: number[] = [];
      filteredEras.forEach((era) => query.push(era.toNumber()));

      const fns: any[] = [
        [api.query.staking.erasStakingPayout.multi as any, query]
      ];

      api.combineLatest<BalanceOf[]>(fns, ([balanceOfs]): void => {
        const tmp: EraStakingPayout[] = [];
        const result = JSON.parse(JSON.stringify(balanceOfs))

        if (Array.isArray(result) && mountedRef.current && result.length && result.length === query.length) {
          for (const [index, a] of query.entries()) {
            tmp.push({
              era: a,
              hasReward: !!result[index]
            });
          }

          setEraStakingPayouts(tmp);
        }
      }).then((_unsub): void => {
        unsub = _unsub;
      }).catch(console.error);
    }

    return (): void => {
      unsub && unsub();
    };
  }, [filteredEras]);

  useEffect((): void => {
    setState({ allRewards: null, isLoadingRewards: true, rewardCount: 0 });
  }, [maxEras, ownValidators]);

  useEffect((): void => {
    if (allEras && maxEras) {
      const filteredEras = allEras.slice(-1 * maxEras);
      const validatorEras: ValidatorWithEras[] = [];

      if (allEras.length === 0) {
        setState({
          allRewards: {},
          isLoadingRewards: false,
          rewardCount: 0
        });
        setFiltered({ filteredEras, validatorEras });
      } else if (ownValidators?.length) {
        ownValidators.forEach(({ stakingLedger, stashId }): void => {
          if (stakingLedger) {
            const eras = filteredEras.filter((era) => !stakingLedger.claimedRewards.some((c) => era.eq(c)));

            if (eras.length) {
              validatorEras.push({ eras, stashId });
            }
          }
        });

        // When we have just claimed, we have filtered eras, but no validator eras - set accordingly
        if (filteredEras.length && !validatorEras.length) {
          setState({
            allRewards: {},
            isLoadingRewards: false,
            rewardCount: 0
          });
        }
      }

      setFiltered({ filteredEras, validatorEras });
    }
  }, [allEras, maxEras, ownValidators]);

  useEffect((): void => {
    mountedRef.current && stakerRewards && !ownValidators && stakingAccounts && eraStakingPayouts && setState(
      getRewards(stakerRewards, stakingAccounts, eraStakingPayouts)
    );
  }, [mountedRef, ownValidators, stakerRewards, stakingAccounts, eraStakingPayouts]);

  useEffect((): void => {
    mountedRef && erasPoints && erasRewards && ownValidators && eraStashExposure && eraStakingPayouts && setState(
      getValRewards(api, validatorEras, erasPoints, erasRewards, eraStashExposure, eraStakingPayouts)
    );
  }, [api, erasPoints, erasRewards, mountedRef, ownValidators, validatorEras, eraStashExposure, eraStakingPayouts]);

  return state;
}