@polkadot/util#BN_THOUSAND TypeScript Examples

The following examples show how to use @polkadot/util#BN_THOUSAND. 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: util.ts    From crust-apps with Apache License 2.0 7 votes vote down vote up
export function balanceToNumber (amount: BN | ToBN = BN_ZERO, divisor: BN): number {
  const value = isBn(amount)
    ? amount
    : isFunction(amount.toBn)
      ? amount.toBn()
      : BN_ZERO;

  return value.mul(BN_THOUSAND).div(divisor).toNumber() / 1000;
}
Example #2
Source File: InputValidateAmount.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function formatExistential (value: BN): string {
  let fmt = (value.mul(BN_THOUSAND).div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals))).toNumber() / 1000).toFixed(3);

  while (fmt.length !== 1 && ['.', '0'].includes(fmt[fmt.length - 1])) {
    const isLast = fmt.endsWith('.');

    fmt = fmt.substr(0, fmt.length - 1);

    if (isLast) {
      break;
    }
  }

  return fmt;
}
Example #3
Source File: ConvictionDropdown.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function createOptions (api: ApiPromise, t: TFunction, blockTime: number): { text: string; value: number }[] {
  return [
    { text: t<string>('0.1x voting balance, no lockup period'), value: 0 },
    ...CONVICTIONS.map(([value, lock, bnLock]): { text: string; value: number } => ({
      text: t<string>('{{value}}x voting balance, locked for {{lock}}x enactment ({{period}} days)', {
        replace: {
          lock,
          period: (bnLock.mul(api.consts.democracy.enactmentPeriod.muln(blockTime).div(BN_THOUSAND)).toNumber() / SEC_DAY).toFixed(2),
          value
        }
      }),
      value
    }))
  ];
}
Example #4
Source File: InputCandyBalance.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function reformat (value: string | BN, isDisabled?: boolean): string {
  if (isBn(value)) {
    let fmt = (value.mul(BN_THOUSAND).div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals))).toNumber() / 1000).toFixed(3);

    while (fmt.length !== 1 && ['.', '0'].includes(fmt[fmt.length - 1])) {
      const isLast = fmt.endsWith('.');

      fmt = fmt.substr(0, fmt.length - 1);

      if (isLast) {
        break;
      }
    }

    return fmt;
  }

  return formatBalance(value, { forceUnit: '-', withSi: false }).replace(',', isDisabled ? ',' : '');
}
Example #5
Source File: InputCsmBalance.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function reformat (value: string | BN, isDisabled?: boolean): string {
  if (isBn(value)) {
    let fmt = (value.mul(BN_THOUSAND).div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals))).toNumber() / 1000).toFixed(3);

    while (fmt.length !== 1 && ['.', '0'].includes(fmt[fmt.length - 1])) {
      const isLast = fmt.endsWith('.');

      fmt = fmt.substr(0, fmt.length - 1);

      if (isLast) {
        break;
      }
    }

    return fmt;
  }

  return formatBalance(value, { forceUnit: '-', withSi: false }).replace(',', isDisabled ? ',' : '');
}
Example #6
Source File: ConvictionDropdown.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function createOptions(api: ApiPromise, t: TFunction, blockTime: number): { text: string; value: number }[] {
  return [
    { text: t<string>('0.1x voting balance, no lockup period'), value: 0 },
    ...CONVICTIONS.map(([value, lock, bnLock]): { text: string; value: number } => ({
      text: t<string>('{{value}}x voting balance, locked for {{lock}}x enactment ({{period}} days)', {
        replace: {
          lock,
          period: (
            bnLock
              .mul((api.consts.democracy.enactmentPeriod as unknown as BN).muln(blockTime).div(BN_THOUSAND))
              .toNumber() / SEC_DAY
          ).toFixed(2),
          value,
        },
      }),
      value,
    })),
  ];
}
Example #7
Source File: blockTime.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
THRESHOLD = BN_THOUSAND.div(BN_TWO)
Example #8
Source File: InstantiateContext.tsx    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
initialData: InstantiateData = {
  constructorIndex: 0,
  value: BN_THOUSAND,
  name: '',
  weight: BN_THOUSAND,
}
Example #9
Source File: Propose.tsx    From crust-apps with Apache License 2.0 4 votes vote down vote up
function Propose ({ className, onClose }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const { api } = useApi();
  const [accountId, setAccountId] = useState<string | null>(null);
  const [name, setName] = useState('');
  const [paraId, setParaId] = useState<BN | undefined>();
  const [balance, setBalance] = useState(() => BN_THOUSAND.mul(BN_TEN.pow(new BN(api.registry.chainDecimals[0]))));
  const [validators, setValidators] = useState<string[]>(['']);
  const [{ isWasmValid, wasm }, setWasm] = useState<CodeState>({ isWasmValid: false, wasm: null });
  const [genesisState, setGenesisState] = useState<Uint8Array | null>(null);

  const _setGenesisState = useCallback(
    (data: Uint8Array) => setGenesisState(compactAddLength(data)),
    []
  );

  const _setWasm = useCallback(
    (wasm: Uint8Array, isWasmValid: boolean) => setWasm({ isWasmValid, wasm }),
    []
  );

  const _setAddress = useCallback(
    (index: number, address: string) =>
      setValidators((v) => v.map((v, i) => i === index ? address : v)),
    []
  );

  const _addValidator = useCallback(
    () => setValidators((v) => [...v, '']),
    []
  );

  const _delValidator = useCallback(
    () => setValidators((v) => [...v.slice(0, v.length - 1)]),
    []
  );

  const isNameValid = name.length >= 3;
  const isValDuplicate = validators.some((a, ai) => validators.some((b, bi) => ai !== bi && a === b));

  return (
    <Modal
      className={className}
      header={t<string>('Propose parachain')}
      size='large'
    >
      <Modal.Content>
        <Modal.Columns hint={t<string>('This account will be associated with the parachain and pay the deposit.')}>
          <InputAddress
            label={t<string>('propose from')}
            onChange={setAccountId}
            type='account'
            value={accountId}
          />
        </Modal.Columns>
        <Modal.Columns hint={t<string>('The name for this parachain, the id and the allocated/requested balance.')}>
          <Input
            autoFocus
            isError={!isNameValid}
            label={t<string>('parachain name')}
            onChange={setName}
          />
          <InputNumber
            isZeroable={false}
            label={t<string>('requested id')}
            onChange={setParaId}
          />
          <InputBalance
            defaultValue={balance}
            label={t<string>('initial balance')}
            onChange={setBalance}
          />
        </Modal.Columns>
        <Modal.Columns hint={t<string>('The WASM validation function as well as the genesis state for this parachain.')}>
          <InputWasm
            help={t<string>('The compiled runtime WASM for the parachain you wish to register.')}
            isError={!isWasmValid}
            label={t<string>('validation code')}
            onChange={_setWasm}
            placeholder={wasm && !isWasmValid && t<string>('The code is not recognized as being in valid WASM format')}
          />
          <InputFile
            help={t<string>('The genesis state for the parachain.')}
            isError={!genesisState}
            label={t<string>('genesis state')}
            onChange={_setGenesisState}
          />
        </Modal.Columns>
        <Modal.Columns hint={t<string>('The validators for this parachain. At least one is required and where multiple is supplied, they need to be unique.')}>
          {validators.map((address, index) => (
            <Validator
              address={address}
              index={index}
              key={index}
              setAddress={_setAddress}
              t={t}
            />
          ))}
          {!validators.length && (
            <MarkWarning content={t<string>('You need to supply at last one running validator for your parachain alongside this request.')} />
          )}
          {isValDuplicate && (
            <MarkWarning content={t<string>('You have duplicated validator entries, ensure each is unique.')} />
          )}
          <Button.Group>
            <Button
              icon='plus'
              label={t<string>('Add validator')}
              onClick={_addValidator}
            />
            <Button
              icon='minus'
              isDisabled={validators.length === 0}
              label={t<string>('Remove validator')}
              onClick={_delValidator}
            />
          </Button.Group>
        </Modal.Columns>
      </Modal.Content>
      <Modal.Actions onCancel={onClose}>
        <TxButton
          accountId={accountId}
          icon='plus'
          isDisabled={!isWasmValid || !genesisState || !isNameValid || !validators.length || !paraId?.gt(BN_ZERO)}
          onStart={onClose}
          params={[paraId, name, wasm, genesisState, validators, balance]}
          tx={api.tx.proposeParachain?.proposeParachain}
        />
      </Modal.Actions>
    </Modal>
  );
}