@polkadot/types/interfaces#BlockNumber TypeScript Examples

The following examples show how to use @polkadot/types/interfaces#BlockNumber. 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: vaults.ts    From interbtc-api with Apache License 2.0 6 votes vote down vote up
async parseVault(vault: VaultRegistryVault, network: Network): Promise<VaultExt<BitcoinUnit>> {
        const collateralCurrency = currencyIdToMonetaryCurrency<CollateralUnit>(vault.id.currencies.collateral);
        const replaceCollateral = newMonetaryAmount(vault.replaceCollateral.toString(), collateralCurrency);
        const liquidatedCollateral = newMonetaryAmount(vault.liquidatedCollateral.toString(), collateralCurrency);
        const backingCollateral = await this.computeBackingCollateral(vault.id);
        return new VaultExt<BitcoinUnit>(
            this.api,
            this.oracleAPI,
            this.systemAPI,
            parseWallet(vault.wallet, network),
            backingCollateral,
            vault.id,
            this.parseVaultStatus(vault.status),
            vault.bannedUntil.isSome ? (vault.bannedUntil.value as BlockNumber).toNumber() : undefined,
            newMonetaryAmount(vault.toBeIssuedTokens.toString(), this.wrappedCurrency),
            newMonetaryAmount(vault.issuedTokens.toString(), this.wrappedCurrency),
            newMonetaryAmount(vault.toBeRedeemedTokens.toString(), this.wrappedCurrency),
            newMonetaryAmount(vault.toBeReplacedTokens.toString(), this.wrappedCurrency),
            replaceCollateral,
            liquidatedCollateral
        );
    }
Example #2
Source File: AddressStatusSmall.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function AddressStatusSmall ({ children, className = '', defaultName, frozenBn, onClickName, overrideName, toggle, value, withSidebar = true }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const { api } = useApi();
  const bestNumberFinalized = useCall<BlockNumber>(api.derive.chain.bestNumberFinalized);

  return (
    <div className={`ui--AddressSmall ${className}`}>
      {(frozenBn && frozenBn > Number(bestNumberFinalized))
        ? (
          <Badge color='orange'
            hover={t<string>('You can not set guarantee fee until block {{bn}}', {
              replace: {
                bn: frozenBn
              }
            })}
            icon='ice-cream'
          />
        )
        : null}
      <IdentityIcon value={value as Uint8Array} />
      <AccountName
        className={withSidebar ? 'withSidebar' : ''}
        defaultName={defaultName}
        onClick={onClickName}
        override={overrideName}
        toggle={toggle}
        value={value}
        withSidebar={withSidebar}
      >
        {children}
      </AccountName>
    </div>
  );
}
Example #3
Source File: parachain.ts    From sdk with Apache License 2.0 6 votes vote down vote up
/**
 * query parachain module overview.
 */
async function queryParasOverview(api: ApiPromise) {
  const [paras, bestNumber] = await Promise.all([api.query.paras.parachains(), api.derive.chain.bestNumber()]);

  const length = api.consts.slots.leasePeriod as BlockNumber;
  const startNumber = bestNumber.sub((api.consts.slots.leaseOffset as BlockNumber) || BN_ZERO);

  return {
    parasCount: (paras as any).length,
    currentLease: startNumber.div(length).toNumber(),
    leaseLength: length.toNumber(),
    leaseProgress: startNumber.mod(length).toNumber(),
  };
}
Example #4
Source File: useBlocksInfo.ts    From parity-bridges-ui with GNU General Public License v3.0 6 votes vote down vote up
useBlocksInfo = ({ isApiReady, api, chain }: SubscriptionInput) => {
  const [bestBlock, setBestBlock] = useMountedState('');
  const [bestBlockFinalized, setBestBlockFinalized] = useMountedState('');
  const isReady = !!(isApiReady && chain);

  const getBestNumber = useCallback(
    () =>
      api.derive.chain.bestNumber((res) => {
        setBestBlock((res as BlockNumber).toString());
      }),
    [api.derive.chain, setBestBlock]
  );

  const getBestBlockFinalized = useCallback(
    () =>
      api.derive.chain.bestNumberFinalized((res) => {
        setBestBlockFinalized((res as BlockNumber).toString());
      }),
    [api.derive.chain, setBestBlockFinalized]
  );

  useApiSubscription(getBestNumber, isReady);
  useApiSubscription(getBestBlockFinalized, isReady);

  return { bestBlock, bestBlockFinalized };
}
Example #5
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
optionsMulti = {
  defaultValue: {
    auctionInfo: null,
    numAuctions: null
  },
  transform: ([numAuctions, optInfo]: [AuctionIndex, Option<ITuple<[LeasePeriodOf, BlockNumber]>>]) => ({
    auctionInfo: optInfo.unwrapOr(null),
    numAuctions
  })
}
Example #6
Source File: treasury.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
public async init(ChainInfo: SubstrateChain, Accounts: SubstrateAccounts): Promise<void> {
    this._disabled = !ChainInfo.api.query.treasury;
    if (this._initializing || this._initialized || this.disabled) return;
    this._initializing = true;
    this._Chain = ChainInfo;
    this._Accounts = Accounts;

    // load server proposals
    const entities = this.app.chain.chainEntities.store.getByType(SubstrateTypes.EntityKind.TreasuryProposal);
    entities.forEach((e) => this._entityConstructor(e));

    // save parameters
    this._bondPct = +(ChainInfo.api.consts.treasury.proposalBond as Permill) / 1_000_000;
    this._bondMinimum = this._Chain.coins(ChainInfo.api.consts.treasury.proposalBondMinimum as BalanceOf);
    this._spendPeriod = +(ChainInfo.api.consts.treasury.spendPeriod as BlockNumber);
    this._burnPct = +(ChainInfo.api.consts.treasury.burn as Permill) / 1_000_000;

    const TREASURY_ACCOUNT = u8aToHex(stringToU8a('modlpy/trsry'.padEnd(32, '\0')));
    const pot = await ChainInfo.api.derive.balances.account(TREASURY_ACCOUNT);
    this._pot = this._Chain.coins(pot.freeBalance);

    // register new chain-event handlers
    this.app.chain.chainEntities.registerEntityHandler(
      SubstrateTypes.EntityKind.TreasuryProposal, (entity, event) => {
        this.updateProposal(entity, event);
      }
    );

    // fetch proposals from chain
    await this.app.chain.chainEntities.fetchEntities(
      this.app.chain.id,
      chainToEventNetwork(this.app.chain.meta),
      () => this._Chain.fetcher.fetchTreasuryProposals(this.app.chain.block.height),
    );

    this._initialized = true;
    this._initializing = false;
  }
Example #7
Source File: useLeasePeriod.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default function useLeasePeriod (): LeasePeriod | null {
  const { api } = useApi();
  const bestNumber = useBestNumber();

  return useMemo((): LeasePeriod | null => {
    if (api.consts.slots?.leasePeriod && bestNumber) {
      const length = api.consts.slots.leasePeriod as BlockNumber;

      return {
        currentPeriod: bestNumber.div(length),
        length,
        remainder: bestNumber.mod(length)
      };
    }

    return null;
  }, [api, bestNumber]);
}
Example #8
Source File: explorer.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
constructor(event: DotEvent, blockNumber?: Compact<BlockNumber>) {
    const { section, method, meta, hash } = event;
    const { docs } = meta;

    super(event);
    this._id = `${hash}-${generateRandomId()}`;
    this._caption = `${section}.${method}`;
    this._description = String(docs.toHuman());
    this._blockNumber = blockNumber ? String(blockNumber.toHuman()) : undefined;
  }
Example #9
Source File: AddressInfo.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function renderBalances (props: Props, lookup: Record<string, string>, bestNumber: BlockNumber | undefined, t: TFunction): React.ReactNode[] {
  const { address, balancesAll, democracyLocks, stakingInfo, withBalance = true, withBalanceToggle = false } = props;
  const balanceDisplay = withBalance === true
    ? DEFAULT_BALANCES
    : withBalance || false;

  if (!bestNumber || !balanceDisplay) {
    return [null];
  }

  const [ownBonded, otherBonded] = calcBonded(stakingInfo, balanceDisplay.bonded);
  const isAllLocked = !!balancesAll && balancesAll.lockedBreakdown.some(({ amount }): boolean => amount.isMax());
  const baseOpts = { address, balanceDisplay, bestNumber, democracyLocks, isAllLocked, otherBonded, ownBonded, withBalanceToggle };
  const items = [createBalanceItems(0, lookup, t, { ...baseOpts, balancesAll, stakingInfo })];

  withBalanceToggle && balancesAll?.additional.length && balancesAll.additional.forEach((balancesAll, index): void => {
    items.push(createBalanceItems(index + 1, lookup, t, { ...baseOpts, balancesAll }));
  });

  return items;
}
Example #10
Source File: Blocks.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Get block number
   * @param hash
   * @returns Compact<BlockNumber>
   */
  async getBlockNumber(hash: `0x${string}` | Uint8Array): Promise<Compact<BlockNumber>> {
    const block = await this.get(hash);
    return block.block.header.number;
  }
Example #11
Source File: useVotingStatus.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
function getStatus (api: ApiPromise, bestNumber: BlockNumber, votes: Votes, numMembers: number, section: 'council' | 'technicalCommittee'): State {
  if (!votes.end) {
    return {
      hasFailed: false,
      hasPassed: false,
      isCloseable: false,
      isVoteable: true,
      remainingBlocks: null
    };
  }

  const isEnd = bestNumber.gte(votes.end);
  const hasPassed = votes.threshold.lten(votes.ayes.length);
  const hasFailed = votes.threshold.gtn(Math.abs(numMembers - votes.nays.length));

  return {
    hasFailed,
    hasPassed,
    isCloseable: isFunction(api.tx[section].close)
      ? api.tx[section].close.meta.args.length === 4 // current-generation
        ? isEnd || hasPassed || hasFailed
        : isEnd
      : false,
    isVoteable: !isEnd,
    remainingBlocks: isEnd
      ? null
      : votes.end.sub(bestNumber)
  };
}
Example #12
Source File: api.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getCouncilElectionDurations = async (
  api: ApiPromise,
  hash: Hash
): Promise<number[]> => {
  const periods = [
    "announcingPeriod",
    "votingPeriod",
    "revealingPeriod",
    "newTermDuration",
  ];
  let durations = await Promise.all(
    periods.map((period: string) => getCouncilElectionPeriod(api, hash, period))
  ).then((d) => d.map((block: BlockNumber) => block.toNumber()));
  durations.push(durations[0] + durations[1] + durations[2] + durations[3]);
  return durations;
}
Example #13
Source File: BestNumber.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function BestNumber({ children, className = '', isFinalized, label, withPound }: Props): React.ReactElement<Props> {
  const { api, isApiReady } = useApi();
  const bestNumber = useCall<BlockNumber>(
    isApiReady && (isFinalized ? api.derive.chain.bestNumberFinalized : api.derive.chain.bestNumber)
  );

  return (
    <div className={className}>
      {label || ''}
      {withPound && '#'}
      {bestNumber ? <Digits value={formatNumber(bestNumber)} /> : '-'}
      {children}
    </div>
  );
}
Example #14
Source File: tokenomics.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
async computeCouncilReward(
    roundNrBlocks: number,
    endHash: Hash
  ): Promise<number> {
    const payoutInterval = Number(
      (
        (await getCouncilPayoutInterval(
          this.api,
          endHash
        )) as Option<BlockNumber>
      ).unwrapOr(0)
    );
    const amountPerPayout = (
      (await getCouncilPayout(this.api, endHash)) as BalanceOf
    ).toNumber();

    const [
      announcingPeriod,
      votingPeriod,
      revealingPeriod,
      termDuration,
    ]: number[] = await getCouncilElectionDurations(this.api, endHash);

    const nrCouncilMembers = ((await getCouncil(this.api, endHash)) as Seats)
      .length;
    const totalCouncilRewardsPerBlock =
      amountPerPayout && payoutInterval
        ? (amountPerPayout * nrCouncilMembers) / payoutInterval
        : 0;

    const councilTermDurationRatio =
      termDuration /
      (termDuration + votingPeriod + revealingPeriod + announcingPeriod);
    const avgCouncilRewardPerBlock =
      councilTermDurationRatio * totalCouncilRewardsPerBlock;

    return avgCouncilRewardPerBlock * roundNrBlocks;
  }
Example #15
Source File: SubstrateService.ts    From squid with GNU General Public License v3.0 6 votes vote down vote up
// async subscribeFinalizedHeads(v: Callback<Header>): UnsubscribePromise {
  //   const api = await getApiPromise()
  //   api.rpc.chain.subscribeFinalizedHeads()
  //   return (await getApiPromise()).rpc.chain.subscribeFinalizedHeads(v)
  // }

  async getBlockHash(
    blockNumber?: BlockNumber | Uint8Array | number | string
  ): Promise<Hash> {
    debug(`Fetching block hash. BlockNumber: ${JSON.stringify(blockNumber)}`)
    return this.apiCall(
      (api) => api.rpc.chain.getBlockHash(blockNumber),
      `get block hash by height ${JSON.stringify(blockNumber)}`
    )
  }
Example #16
Source File: api.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getCouncilElectionStatus = async (
  api: ApiPromise,
  hash: Hash
): Promise<ElectionInfo> => {
  const durations = await getCouncilElectionDurations(api, hash);
  const round = await getCouncilRound(api, hash);
  const stage: ElectionStage = await getCouncilElectionStage(api, hash);
  const stageEndsAt: number = Number(stage.value as BlockNumber);
  const termEndsAt: number = await getCouncilTermEnd(api, hash);
  return { round, stageEndsAt, termEndsAt, stage, durations };
}
Example #17
Source File: BestFinalized.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function BestFinalized({ children, className = '', label }: Props): React.ReactElement<Props> {
  const { api } = useApi();
  const bestNumberFinalized = useCall<BlockNumber>(api.derive.chain.bestNumberFinalized);

  return (
    <div className={className}>
      {label || ''}
      {bestNumberFinalized ? <Digits value={formatNumber(bestNumberFinalized)} /> : '-'}
      {children}
    </div>
  );
}
Example #18
Source File: defaults.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
defaultBountyApi: BountyApi = {
  acceptCurator: jest.fn(),
  approveBounty: jest.fn(),
  awardBounty: jest.fn().mockReturnValue('mockAwardExtrinsic'),
  bestNumber: new BN(1) as BlockNumber,
  bounties: [] as DeriveBounties,
  bountyCuratorDeposit: balanceOf(500000),
  bountyDepositBase: new BN(1),
  bountyUpdatePeriod: defaultBountyUpdatePeriod,
  bountyValueMinimum: new BN(1),
  claimBounty: jest.fn(),
  closeBounty: jest.fn().mockReturnValue({ length: 4 }),
  dataDepositPerByte: new BN(1),
  extendBountyExpiry: jest.fn().mockReturnValue('mockExtendExtrinsic'),
  maximumReasonLength: 100,
  proposeBounty: jest.fn(),
  proposeCurator: jest.fn(),
  unassignCurator: jest.fn().mockReturnValue('mockUnassignExtrinsic')
}
Example #19
Source File: useVotingStatus.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line complexity
function getStatus(
  api: ApiPromise,
  bestNumber: BlockNumber,
  votes: Votes,
  numMembers: number,
  section: 'council' | 'membership' | 'technicalCommittee'
): State {
  if (!votes.end) {
    return {
      hasFailed: false,
      hasPassed: false,
      isCloseable: false,
      isVoteable: true,
      remainingBlocks: null,
    };
  }

  const isEnd = bestNumber.gte(votes.end);
  const hasPassed = votes.threshold.lten(votes.ayes.length);
  const hasFailed = votes.threshold.gtn(Math.abs(numMembers - votes.nays.length));

  return {
    hasFailed,
    hasPassed,
    isCloseable: isFunction(api.tx[section].close)
      ? api.tx[section].close.meta.args.length === 4 // current-generation
        ? isEnd || hasPassed || hasFailed
        : isEnd
      : false,
    isVoteable: !isEnd,
    remainingBlocks: isEnd ? null : votes.end.sub(bestNumber),
  };
}
Example #20
Source File: api.ts    From community-repo with GNU General Public License v3.0 6 votes vote down vote up
getBlockHash = (
  api: ApiPromise,
  block: BlockNumber | number
): Promise<Hash> => {
  try {
    return api.rpc.chain.getBlockHash(block);
  } catch (e) {
    return api.rpc.chain.getFinalizedHead();
  }
}
Example #21
Source File: democracy_proposals.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
// Loads all proposals and referendums currently present in the democracy module
  public async init(ChainInfo: SubstrateChain, Accounts: SubstrateAccounts): Promise<void> {
    this._disabled = !ChainInfo.api.query.democracy;
    if (this._initializing || this._initialized || this.disabled) return;
    this._initializing = true;
    this._Chain = ChainInfo;
    this._Accounts = Accounts;

    // load server proposals
    const entities = this.app.chain.chainEntities.store.getByType(SubstrateTypes.EntityKind.DemocracyProposal);
    entities.forEach((e) => this._entityConstructor(e));

    // save parameters
    this._minimumDeposit = this._Chain.coins(ChainInfo.api.consts.democracy.minimumDeposit as Balance);
    this._launchPeriod = +(ChainInfo.api.consts.democracy.launchPeriod as BlockNumber);
    this._cooloffPeriod = +(ChainInfo.api.consts.democracy.cooloffPeriod as BlockNumber);

    // register new chain-event handlers
    this.app.chain.chainEntities.registerEntityHandler(
      SubstrateTypes.EntityKind.DemocracyProposal, (entity, event) => {
        this.updateProposal(entity, event);
      }
    );
    this.app.chain.chainEntities.registerEntityHandler(
      SubstrateTypes.EntityKind.DemocracyPreimage, (entity, event) => {
        if (event.data.kind === SubstrateTypes.EventKind.PreimageNoted) {
          const proposal = this.getByHash(entity.typeId);
          if (proposal) proposal.update(event);
        }
      }
    );

    // fetch proposals from chain
    const events = await this.app.chain.chainEntities.fetchEntities(
      this.app.chain.id,
      chainToEventNetwork(this.app.chain.meta),
      () => this._Chain.fetcher.fetchDemocracyProposals(this.app.chain.block.height)
    );

    const hashes = events.map((e) => e.data.proposalHash);
    await this.app.chain.chainEntities.fetchEntities(
      this.app.chain.id,
      chainToEventNetwork(this.app.chain.meta),
      () => this._Chain.fetcher.fetchDemocracyPreimages(hashes)
    );

    const lastTabledWasExternal = await ChainInfo.api.query.democracy.lastTabledWasExternal();
    const nextExternal = await ChainInfo.api.query.democracy.nextExternal();
    this._lastTabledWasExternal = lastTabledWasExternal.valueOf();
    this._nextExternal = nextExternal.unwrapOr(null);
    this._initialized = true;
    this._initializing = false;
  }
Example #22
Source File: subscriber.ts    From polkadot-watcher-csv-exporter with Apache License 2.0 5 votes vote down vote up
private _writeEraCSV = async (eraIndex: EraIndex, sessionIndex: SessionIndex, blockNumber: Compact<BlockNumber>): Promise<void> => {
      const network = this.chain.toString().toLowerCase()
      const request = {api:this.api,network,apiChunkSize:this.apiChunkSize,exportDir:this.exportDir,eraIndex,sessionIndex,blockNumber}
      const chainData = await gatherChainData(request, this.logger)
      await writeSessionCSV(request, chainData, this.logger)
      await writeEraCSV(request, chainData, this.logger)
    }
Example #23
Source File: bountyTreasury.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.consts.bounties && !ChainInfo.api.consts.treasury;
    if (this._initializing || this._initialized || this.disabled) return;
    this._initializing = true;
    this._Chain = ChainInfo;
    this._Accounts = Accounts;

    // load server proposals
    const entities = this.app.chain.chainEntities.store.getByType(SubstrateTypes.EntityKind.TreasuryBounty);
    entities.forEach((e) => this._entityConstructor(e));

    // save parameters
    const bountyModule = ChainInfo.api.consts.bounties || ChainInfo.api.consts.treasury;
    this._bountyCuratorDeposit = this._Chain.coins(bountyModule.bountyCuratorDeposit as Permill);
    this._bountyDepositBase = this._Chain.coins(bountyModule.bountyDepositBase as BalanceOf);
    this._bountyDepositPayoutDelay = bountyModule.bountyDepositPayoutDelay as BlockNumber;
    this._bountyValueMinimum = this._Chain.coins(bountyModule.bountyValueMinimum as BalanceOf);

    // kick off subscriptions
    // const TREASURY_ACCOUNT = u8aToHex(stringToU8a('modlpy/trsry'.padEnd(32, '\0')));

    // register new chain-event handlers
    this.app.chain.chainEntities.registerEntityHandler(
      SubstrateTypes.EntityKind.TreasuryBounty, (entity, event) => {
        this.updateProposal(entity, event);
      }
    );

    // fetch proposals from chain
    await this.app.chain.chainEntities.fetchEntities(
      this.app.chain.id,
      chainToEventNetwork(this.app.chain.meta),
      () => this._Chain.fetcher.fetchBounties(this.app.chain.block.height),
    );

    // fetch extra metadata
    // TODO: this should be picked up by the chain-events system
    const extra = await ChainInfo.api.derive.bounties.bounties();
    extra.forEach((b) => {
      const index = b.index.toNumber();
      const bounty = this.store.getByIdentifier(index);
      if (!bounty) {
        console.log('Unexpected missing bounty, on chain but not returned by chain-events');
        return;
      }
      const data = {
        title: b.description,
        // state
        isActive: b.bounty.status.isActive,
        isApproved: b.bounty.status.isApproved,
        isCuratorProposed: b.bounty.status.isCuratorProposed,
        isFunded: b.bounty.status.isFunded,
        isPendingPayout: b.bounty.status.isPendingPayout,
        isProposed: b.bounty.status.isProposed,
        // metadata
        fee: b.bounty.fee,
        curatorDeposit: b.bounty.curatorDeposit,
        bond: b.bounty.bond,
        curator: b.bounty.status.isCuratorProposed ? b.bounty.status.asCuratorProposed?.curator
          : b.bounty.status.isActive ? b.bounty.status.asActive.curator
            : b.bounty.status.isPendingPayout ? b.bounty.status.asPendingPayout.curator : null,
        updateDue: b.bounty.status.isActive ? b.bounty.status.asActive.updateDue : null,
        beneficiary: b.bounty.status.isPendingPayout ? b.bounty.status.asPendingPayout.beneficiary : null,
        unlockAt: b.bounty.status.isPendingPayout ? b.bounty.status.asPendingPayout.unlockAt : null,
      };
      bounty.setStatus(data);
    });

    this._initialized = true;
    this._initializing = false;
  }
Example #24
Source File: AddressInfo.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function renderBalances(
  props: Props,
  lookup: Record<string, string>,
  bestNumber: BlockNumber | undefined,
  t: TFunction
): React.ReactNode[] {
  const {
    address,
    balancesAll,
    democracyLocks,
    stakingInfo,
    votingOf,
    withBalance = true,
    withBalanceToggle = false,
  } = props;
  const balanceDisplay = withBalance === true ? DEFAULT_BALANCES : withBalance || false;

  if (!bestNumber || !balanceDisplay) {
    return [null];
  }

  const [ownBonded, otherBonded] = calcBonded(stakingInfo, balanceDisplay.bonded);
  const isAllLocked = !!balancesAll && balancesAll.lockedBreakdown.some(({ amount }): boolean => amount?.isMax());
  const baseOpts = {
    address,
    balanceDisplay,
    bestNumber,
    democracyLocks,
    isAllLocked,
    otherBonded,
    ownBonded,
    votingOf,
    withBalanceToggle,
  };
  const items = [createBalanceItems(0, lookup, t, { ...baseOpts, balancesAll, stakingInfo })];

  withBalanceToggle &&
    balancesAll?.additional.length &&
    balancesAll.additional.forEach((balancesAll, index): void => {
      items.push(createBalanceItems(index + 1, lookup, t, { ...baseOpts, balancesAll }));
    });

  return items;
}
Example #25
Source File: FundContribute.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function FundContribute ({ cap, className, paraId, raised }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const { api } = useApi();
  const { hasAccounts } = useAccounts();
  const [isOpen, toggleOpen] = useToggle();
  const [accountId, setAccountId] = useState<string | null>(null);
  const [amount, setAmount] = useState<BN | undefined>();

  // TODO verifier signature

  const remaining = cap.sub(raised);
  const isAmountBelow = !amount || amount.lt(api.consts.crowdloan.minContribution as BalanceOf);
  const isAmountOver = !!(amount && amount.gt(remaining));
  const isAmountError = isAmountBelow || isAmountOver;

  return (
    <>
      <Button
        icon='plus'
        isDisabled={!hasAccounts}
        label={t<string>('Contribute')}
        onClick={toggleOpen}
      />
      {isOpen && (
        <Modal
          className={className}
          header={t<string>('Contribute to fund')}
          size='large'
        >
          <Modal.Content>
            <Modal.Columns hint={t<string>('This account will contribute to the crowdloan.')}>
              <InputAddress
                label={t<string>('contribute from')}
                onChange={setAccountId}
                type='account'
                value={accountId}
              />
            </Modal.Columns>
            <Modal.Columns hint={t<string>('The amount to contribute. Should be less than the remaining value and more than the minimum contribution amount.')}>
              <InputBalance
                autoFocus
                defaultValue={api.consts.crowdloan.minContribution as BalanceOf}
                isError={isAmountError}
                isZeroable={false}
                label={t<string>('contribution')}
                onChange={setAmount}
              />
              {isAmountBelow && (
                <MarkWarning content={t<string>('The amount is less than the minimum allowed contribution of {{value}}', { replace: { value: formatBalance(api.consts.crowdloan.minContribution as BlockNumber) } })} />
              )}
              {isAmountOver && (
                <MarkWarning content={t<string>('The amount is more than the remaining contribution needed {{value}}', { replace: { value: formatBalance(remaining) } })} />
              )}
            </Modal.Columns>
          </Modal.Content>
          <Modal.Actions onCancel={toggleOpen}>
            <TxButton
              accountId={accountId}
              icon='plus'
              isDisabled={isAmountError}
              label={t<string>('Contribute')}
              onStart={toggleOpen}
              params={[paraId, amount, null]}
              tx={api.tx.crowdloan.contribute}
            />
          </Modal.Actions>
        </Modal>
      )}
    </>
  );
}
Example #26
Source File: useBestNumber.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export function useBestNumber(): BlockNumber | undefined {
  const { api } = useApi();

  return useCall<BlockNumber>(api.derive.chain.bestNumber);
}
Example #27
Source File: Bid.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function Bid ({ auctionInfo, className, id, ownedIds }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const { api } = useApi();
  const { hasAccounts } = useAccounts();
  const bestNumber = useBestNumber();
  const [{ accountId, paraId }, setOwnerInfo] = useState<OwnerInfo>({ accountId: null, paraId: 0 });
  const [amount, setAmount] = useState<BN | undefined>(BN_ZERO);
  const [range, setRange] = useState(0);
  const [isOpen, toggleOpen] = useToggle();

  const rangeOpts = useMemo(
    (): Option[] => {
      const [leasePeriod] = auctionInfo || [null, null];

      return leasePeriod
        ? RANGES.map(([first, last], value): Option => ({
          text: `${formatNumber(leasePeriod.addn(first))} - ${formatNumber(leasePeriod.addn(last))}`,
          value
        }))
        : [];
    },
    [auctionInfo]
  );

  const [leasePeriod, endBlock] = auctionInfo || [null, null];

  return (
    <>
      <Button
        icon='plus'
        isDisabled={!ownedIds.length || !hasAccounts || !id || !leasePeriod || !endBlock || bestNumber?.gte(endBlock.add(api.consts.auctions.endingPeriod as BlockNumber))}
        label={t<string>('Bid')}
        onClick={toggleOpen}
      />
      {isOpen && (
        <Modal
          className={className}
          header={t<string>('Place bid')}
          size='large'
        >
          <Modal.Content>
            <InputOwner
              onChange={setOwnerInfo}
              ownedIds={ownedIds}
            />
            <Modal.Columns hint={t<string>('The amount to to bid for this parachain slot')}>
              <InputBalance
                isZeroable={false}
                label={t<string>('bid amount')}
                onChange={setAmount}
              />
            </Modal.Columns>
            <Modal.Columns hint={t<string>('The first and last slots for this bid. The last slot should be after the first and a maximum of 3 slots more than the first')}>
              <Dropdown
                label={t<string>('bid slot range (start slot, end slot)')}
                onChange={setRange}
                options={rangeOpts}
                value={range}
              />
            </Modal.Columns>
          </Modal.Content>
          <Modal.Actions onCancel={toggleOpen}>
            <TxButton
              accountId={accountId}
              icon='plus'
              isDisabled={!paraId || !amount?.gt(BN_ZERO) || !leasePeriod}
              label={t<string>('Bid')}
              onStart={toggleOpen}
              params={[paraId, id, leasePeriod?.addn(RANGES[range][0]), leasePeriod?.addn(RANGES[range][1]), amount]}
              tx={api.tx.auctions.bid}
            />
          </Modal.Actions>
        </Modal>
      )}
    </>
  );
}
Example #28
Source File: announcements.ts    From community-repo with GNU General Public License v3.0 5 votes vote down vote up
council = async (
  api: Api,
  council: Council,
  currentBlock: number,
  sendMessage: Send,
  channel: any
): Promise<Council> => {
  const round: number = await api.query.councilElection.round();
  const stage: any = await api.query.councilElection.stage();
  const stageObj = JSON.parse(JSON.stringify(stage));
  let stageString = stageObj ? Object.keys(stageObj)[0] : "";
  let msg: string[] = ["", ""];

  if (!stage || stage.toJSON() === null) {
    stageString = "elected";
    const councilEnd: BlockNumber = await api.query.council.termEndsAt();
    const termDuration: BlockNumber = await api.query.councilElection.newTermDuration();
    const block = councilEnd.toNumber() - termDuration.toNumber();
    if (currentBlock - block < 2000) {
      const remainingBlocks = councilEnd.toNumber() - currentBlock;
      const m = moment().add(remainingBlocks * 6, "s");
      const endDate = formatTime(m, "DD/MM/YYYY");

      const handles: string[] = await Promise.all(
        (await api.query.council.activeCouncil()).map(
          async (seat: { member: string }) =>
            await memberHandleByAccount(api, seat.member)
        )
      );
      const members = handles.join(", ");

      msg[0] = `Council election ended: ${members} have been elected for <a href="${domain}/#/council/members">council ${round}</a>. Congratulations!\nNext election starts on ${endDate}.`;
      msg[1] = `Council election ended: ${members} have been elected for council ${round}. Congratulations!\nNext election starts on ${endDate}.\n${domain}/#/council/members`;
    }
  } else {
    const remainingBlocks = stage.toJSON()[stageString] - currentBlock;
    const m = moment().add(remainingBlocks * 6, "second");
    const endDate = formatTime(m, "DD-MM-YYYY HH:mm (UTC)");

    const link = `${domain}/#/council/`;
    if (stageString === "Announcing") {
      msg[0] = `Council election started. You can <b><a href="${link}applicants">announce your application</a></b> until ${endDate}`;
      msg[1] = `Council election started. You can **announce your application** until ${endDate} ${link}applicants`;
    } else if (stageString === "Voting") {
      msg[0] = `Council election: <b><a href="${link}applicants">Vote</a></b> until ${endDate}`;
      msg[1] = `Council election: **Vote* until ${endDate} ${link}applicants`;
    } else if (stageString === "Revealing") {
      msg[0] = `Council election: <b><a href="${link}votes">Reveal your votes</a></b> until ${endDate}`;
      msg[1] = `Council election: **Reveal your votes** until ${endDate} ${link}votes`;
    }
  }

  if (
    council.last !== "" &&
    round !== council.round &&
    stageString !== council.last
  )
    sendMessage({ tg: msg[0], discord: msg[1] }, channel);
  return { round, last: stageString };
}
Example #29
Source File: Blocks.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Get blockHash by number
   * @param number number of block
   * @returns blockHash
   */
  async getBlockHash(number: AnyNumber | BlockNumber): Promise<BlockHash> {
    return await this.api.rpc.chain.getBlockHash(number);
  }