@polkadot/util#bnToBn TypeScript Examples

The following examples show how to use @polkadot/util#bnToBn. 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: Elapsed.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function getDisplayValue(now = 0, value: BN | Date | number = 0): React.ReactNode {
  const tsValue =
    (value && (value as Date).getTime ? (value as Date).getTime() : bnToBn(value as number).toNumber()) || 0;

  if (!now || !tsValue) {
    return formatValue(0, 's', true);
  }

  const elapsed = Math.max(Math.abs(now - tsValue), 0) / 1000;

  return elapsed < 60
    ? formatValue(elapsed, 's', elapsed < 15)
    : elapsed < 3600
    ? formatValue(elapsed / 60, 'min')
    : formatValue(elapsed / 3600, 'hr');
}
Example #2
Source File: Progress.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function Progress ({ className = '', isDisabled, total, value }: Props): React.ReactElement<Props> | null {
  const _total = bnToBn(total || 0);
  const angle = _total.gtn(0)
    ? (bnToBn(value || 0).muln(36000).div(_total).toNumber() / 100)
    : 0;

  if (angle < 0) {
    return null;
  }

  const drawAngle = angle % 360;

  return (
    <div className={`ui--Progress${isDisabled ? ' isDisabled' : ''} ${className}`}>
      <div className='background highlight--bg' />
      <Clip
        angle={
          drawAngle <= 180
            ? drawAngle.toFixed(1)
            : '180'
        }
        type='first'
      />
      <Clip
        angle={
          drawAngle <= 180
            ? '0'
            : (drawAngle - 180).toFixed(1)
        }
        type='second'
      />
      <div className='inner'>
        <div>{Math.floor(angle * 100 / 360)}%</div>
      </div>
    </div>
  );
}
Example #3
Source File: useWeightFee.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export function useWeightFee(weight: BN | number, apiOverride?: ApiPromise | null): BN {
  const { api } = useApi();

  return useMemo(
    () =>
      isUndefined(apiOverride) || apiOverride
        ? (((apiOverride || api).consts.transactionPayment?.weightToFee as unknown as any[]) || []).reduce(
            (acc, { coeffFrac, coeffInteger, degree, negative }: WeightToFeeCoefficient): BN => {
              const w = bnToBn(weight).pow(degree);
              const frac = coeffFrac.mul(w).div(BN_BILLION);
              const integer = coeffInteger.mul(w);

              if (negative.isTrue) {
                acc.isub(frac);
                acc.isub(integer);
              } else {
                acc.iadd(frac);
                acc.iadd(integer);
              }

              return acc;
            },
            new BN(0)
          )
        : BN_ZERO,
    [api, apiOverride, weight]
  );
}
Example #4
Source File: VoteThreshold.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function VoteThresholdParam ({ className = '', defaultValue: { value }, isDisabled, isError, label, onChange, registry, withLabel }: Props): React.ReactElement<Props> {
  const _onChange = useCallback(
    (value: number) =>
      onChange && onChange({
        isValid: true,
        value
      }),
    [onChange]
  );

  const defaultValue = value instanceof ClassOf(registry, 'VoteThreshold')
    ? value.toNumber()
    : bnToBn(value as number).toNumber();

  return (
    <Bare className={className}>
      <Dropdown
        className='full'
        defaultValue={defaultValue}
        isDisabled={isDisabled}
        isError={isError}
        label={label}
        onChange={_onChange}
        options={options}
        withLabel={withLabel}
      />
    </Bare>
  );
}
Example #5
Source File: Elapsed.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function getDisplayValue (now = 0, value: BN | Date | number = 0): React.ReactNode {
  const tsValue = (
    value && (value as Date).getTime
      ? (value as Date).getTime()
      : bnToBn(value as number).toNumber()
  ) || 0;
  let display = formatValue(0, 's', true);

  if (now && tsValue) {
    const elapsed = Math.max(Math.abs(now - tsValue), 0) / 1000;

    if (elapsed < 15) {
      display = formatValue(elapsed, 's', true);
    } else if (elapsed < 60) {
      display = formatValue(elapsed);
    } else if (elapsed < 3600) {
      display = formatValue(elapsed, 'min');
    } else {
      display = formatValue(elapsed / 3600, 'hr');
    }
  }

  return display;
}
Example #6
Source File: useBlockTime.ts    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
useBlockTime = (
  blocks: number | BN = BN_ONE,
  apiOverride?: ApiPromise | null
): Result => {
  const { api } = useApi();

  return useMemo((): Result => {
    const a = apiOverride || api;
    const blockTime = blockTimeMs(a);
    const value = blockTime.mul(bnToBn(blocks)).toNumber();
    const time = extractTime(Math.abs(value));
    const { days, hours, minutes, seconds } = time;
    const timeStr = [
      days ? (days > 1 ? `${days} days` : '1 day') : null,
      hours ? (hours > 1 ? `${hours} hours` : '1 hr') : null,
      minutes ? (minutes > 1 ? `${minutes} mins` : '1 min') : null,
      seconds ? (seconds > 1 ? `${seconds} s` : '1 s') : null,
    ]
      .filter((s): s is string => !!s)
      .slice(0, 2)
      .join(' ');

    return [blockTime.toNumber(), `${value < 0 ? '+' : ''}${timeStr}`, time];
  }, [api, apiOverride, blocks]);
}
Example #7
Source File: Doughnut.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function ChartDoughnut ({ className = '', size = 100, values }: DoughnutProps): React.ReactElement<DoughnutProps> {
  const options: Options = {
    colorHover: [],
    colorNormal: [],
    data: [],
    labels: []
  };

  values.forEach(({ colors: [normalColor = '#00f', hoverColor], label, value }): void => {
    options.colorNormal.push(normalColor);
    options.colorHover.push(hoverColor || normalColor);
    options.data.push(bnToBn(value).toNumber());
    options.labels.push(label);
  });

  return (
    <Base className={className}>
      <Doughnut
        data={{
          datasets: [{
            backgroundColor: options.colorNormal,
            data: options.data,
            hoverBackgroundColor: options.colorHover
          }],
          labels: options.labels
        }}
        height={size}
        width={size}
      />
    </Base>
  );
}
Example #8
Source File: Doughnut.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line no-magic-numbers
function ChartDoughnut({ className = '', size = 100, values }: DoughnutProps): React.ReactElement<DoughnutProps> {
  const options: Options = {
    colorHover: [],
    colorNormal: [],
    data: [],
    labels: [],
  };

  values.forEach(({ colors: [normalColor = '#00f', hoverColor], label, value }): void => {
    options.colorNormal.push(normalColor);
    options.colorHover.push(hoverColor || normalColor);
    options.data.push(bnToBn(value).toNumber());
    options.labels.push(label);
  });

  return (
    <Base className={className}>
      <Doughnut
        type=""
        data={{
          datasets: [
            {
              backgroundColor: options.colorNormal,
              data: options.data,
              hoverBackgroundColor: options.colorHover,
            },
          ],
          labels: options.labels,
        }}
        height={size}
        width={size}
      />
    </Base>
  );
}
Example #9
Source File: Progress.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function Progress({ className = '', isDisabled, total, value }: Props): React.ReactElement<Props> | null {
  const _total = bnToBn(total || 0);
  const angle = _total.gtn(0)
    ? bnToBn(value || 0)
        .muln(36000)
        .div(_total)
        .toNumber() / 100
    : 0;

  if (angle < 0) {
    return null;
  }

  const drawAngle = angle % 360;

  return (
    <div className={`ui--Progress${isDisabled ? ' isDisabled' : ''} ${className}`}>
      <div className="background highlight--bg" />
      <Clip angle={drawAngle <= 180 ? drawAngle.toFixed(1) : '180'} type="first" />
      <Clip angle={drawAngle <= 180 ? '0' : (drawAngle - 180).toFixed(1)} type="second" />
      <div className="inner">
        <div>{Math.floor((angle * 100) / 360)}%</div>
      </div>
    </div>
  );
}
Example #10
Source File: useNonZeroBn.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
export function useNonZeroBn(initialValue: BN | number = BN_ZERO): ValidFormField<BN> {
  const value = useMemo(() => bnToBn(initialValue), [initialValue]);

  return useFormField(value, isValid);
}
Example #11
Source File: VoteThreshold.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function VoteThresholdParam({
  className = '',
  defaultValue: { value },
  isDisabled,
  isError,
  label,
  onChange,
  registry,
  withLabel,
}: Props): React.ReactElement<Props> {
  const _onChange = useCallback(
    (val: number) =>
      onChange &&
      onChange({
        isValid: true,
        value: val,
      }),
    [onChange]
  );

  const defaultValue =
    value instanceof registry.createClass<VoteThreshold>('VoteThreshold')
      ? value.toNumber()
      : bnToBn(value as number).toNumber();

  return (
    <Bare className={className}>
      <Dropdown
        className="full"
        defaultValue={defaultValue}
        isDisabled={isDisabled}
        isError={isError}
        label={label}
        onChange={_onChange}
        options={options}
        withLabel={withLabel}
      />
    </Bare>
  );
}
Example #12
Source File: Amount.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function Amount({
  className = '',
  defaultValue: { value },
  isDisabled,
  isError,
  label,
  onChange,
  onEnter,
  registry,
  type,
  withLabel,
}: Props): React.ReactElement<Props> {
  const defaultValue = useMemo(
    () =>
      isDisabled
        ? value instanceof registry.createClass('AccountIndex')
          ? value.toString()
          : formatNumber(value as number)
        : bnToBn((value as number) || 0).toString(),
    [isDisabled, registry, value]
  );

  const bitLength = useMemo((): number => {
    try {
      return registry.createType(type.type as 'u32').bitLength();
    } catch (error) {
      // eslint-disable-next-line no-magic-numbers
      return 32;
    }
  }, [registry, type]);

  const _onChange = useCallback(
    (val?: BN) =>
      onChange &&
      onChange({
        isValid: !isUndefined(val),
        value: val,
      }),
    [onChange]
  );

  return (
    <Bare className={className}>
      {isDisabled ? (
        <Input
          className="full"
          defaultValue={defaultValue}
          isDisabled
          label={label}
          withEllipsis
          withLabel={withLabel}
        />
      ) : (
        <InputNumber
          bitLength={bitLength}
          className="full"
          defaultValue={defaultValue}
          isError={isError}
          isZeroable
          label={label}
          onChange={_onChange}
          onEnter={onEnter}
          withLabel={withLabel}
        />
      )}
    </Bare>
  );
}
Example #13
Source File: useParaEndpoints.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function extractParaEndpoints(allEndpoints: LinkOption[], paraId: BN | number): LinkOption[] {
  const numId = bnToBn(paraId).toNumber();

  return allEndpoints.filter(({ paraId }: any) => paraId === numId);
}
Example #14
Source File: useNonZeroBn.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export function useNonZeroBn(initialValue: BN | number = BN_ZERO): FormField<BN> {
  const value = useMemo(() => bnToBn(initialValue), [initialValue]);

  return useFormField(value, isValid);
}
Example #15
Source File: HorizBar.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function calculateOptions(
  aspectRatio: number,
  values: HorizBarValue[],
  jsonValues: string,
  max: number,
  showLabels: boolean
): State {
  const chartData = values.reduce(
    (data, { colors: [normalColor = '#00f', hoverColor], label, value }): Config => {
      const dataset = data.datasets[0];

      dataset.backgroundColor.push(alphaColor(normalColor));
      dataset.hoverBackgroundColor.push(alphaColor(hoverColor || normalColor));
      dataset.data.push(isNumber(value) ? value : bnToBn(value).toNumber());
      data.labels.push(label);

      return data;
    },
    {
      datasets: [
        {
          backgroundColor: [] as string[],
          data: [] as number[],
          hoverBackgroundColor: [] as string[],
        },
      ],
      labels: [] as string[],
    }
  );

  return {
    chartData,
    chartOptions: {
      // width/height by default this is "1", i.e. a square box
      aspectRatio,
      // no need for the legend, expect the labels contain everything
      legend: {
        display: false,
      },
      scales: {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        xAxes: [
          {
            ticks: showLabels ? { beginAtZero: true, max } : { display: false },
          },
        ],
      },
      tooltips: {
        callbacks: {
          label: (item: TooltipItem): string => values[item.index].tooltip || values[item.index].label,
        },
      },
    },
    jsonValues,
  };
}
Example #16
Source File: Amount.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function Amount ({ className = '', defaultValue: { value }, isDisabled, isError, label, onChange, onEnter, registry, type, withLabel }: Props): React.ReactElement<Props> {
  const defaultValue = useMemo(
    () => isDisabled
      ? value instanceof ClassOf(registry, 'AccountIndex')
        ? value.toString()
        : formatNumber(value as number)
      : bnToBn((value as number) || 0).toString(),
    [isDisabled, registry, value]
  );

  const bitLength = useMemo(
    (): number => {
      try {
        return registry.createType(type.type as 'u32').bitLength();
      } catch (error) {
        return 32;
      }
    },
    [registry, type]
  );

  const _onChange = useCallback(
    (value?: BN) => onChange && onChange({
      isValid: !isUndefined(value),
      value
    }),
    [onChange]
  );

  return (
    <Bare className={className}>
      {isDisabled
        ? (
          <Input
            className='full'
            defaultValue={defaultValue}
            isDisabled
            label={label}
            withEllipsis
            withLabel={withLabel}
          />
        )
        : (
          <InputNumber
            bitLength={bitLength}
            className='full'
            defaultValue={defaultValue}
            isError={isError}
            isZeroable
            label={label}
            onChange={_onChange}
            onEnter={onEnter}
            withLabel={withLabel}
          />
        )
      }
    </Bare>
  );
}
Example #17
Source File: useParaEndpoints.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
function extractResults (genesisHash: string, paraId: BN | number): LinkOption[] {
  const numId = bnToBn(paraId).toNumber();

  return createWsEndpoints((key: string, value: string | undefined) => value || key).filter(({ genesisHashRelay, paraId }) =>
    paraId === numId && genesisHashRelay === genesisHash
  );
}
Example #18
Source File: useNonZeroBn.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function useNonZeroBn (initialValue: BN | number = BN_ZERO): FormField<BN> {
  const value = useMemo(() => bnToBn(initialValue), [initialValue]);

  return useFormField(value, isValid);
}
Example #19
Source File: HorizBar.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function calculateOptions (aspectRatio: number, values: HorizBarValue[], jsonValues: string, max: number, showLabels: boolean): State {
  const chartData = values.reduce((data, { colors: [normalColor = '#00f', hoverColor], label, value }): Config => {
    const dataset = data.datasets[0];

    dataset.backgroundColor.push(alphaColor(normalColor));
    dataset.hoverBackgroundColor.push(alphaColor(hoverColor || normalColor));
    dataset.data.push(isNumber(value) ? value : bnToBn(value).toNumber());
    data.labels.push(label);

    return data;
  }, {
    datasets: [{
      backgroundColor: [] as string[],
      data: [] as number[],
      hoverBackgroundColor: [] as string[]
    }],
    labels: [] as string[]
  });

  return {
    chartData,
    chartOptions: {
      // width/height by default this is "1", i.e. a square box
      aspectRatio,
      // no need for the legend, expect the labels contain everything
      legend: {
        display: false
      },
      scales: {
        xAxes: [{
          ticks: showLabels
            ? { beginAtZero: true, max }
            : { display: false }
        }]
      },
      tooltips: {
        callbacks: {
          label: (item: TooltipItem): string =>
            values[item.index].tooltip || values[item.index].label
        }
      }
    },
    jsonValues
  };
}