@polkadot/util#isBn TypeScript Examples

The following examples show how to use @polkadot/util#isBn. 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: InputBalance.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)) {
    // format for 4 decimals (align with util)
    const valStr = value
      .mul(BN_TEN_THOUSAND)
      .div(BN_TEN.pow(new BN(formatBalance.getDefaults().decimals)))
      .toString()
      .padStart(5, '0'); // 4 after decimal, 1 before, min 5

    // dive using string format (the value may be too large for 2^53-1)
    let fmt = `${valStr.substr(0, valStr.length - 4)}.${valStr.slice(-4)}`;

    // remove all trailing 0's until the decimal
    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 #3
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 #4
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 #5
Source File: findComponent.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default function findComponent (registry: Registry, def: TypeDef, overrides: ComponentMap = {}): React.ComponentType<Props> {
  const findOne = (type: string): React.ComponentType<Props> | null =>
    overrides[type] || components[type];
  const type = fromDef(def);
  let Component = findOne(type);

  if (!Component) {
    let error: string | null = null;

    try {
      const instance = registry.createType(type as 'u32');
      const raw = getTypeDef(instance.toRawType());

      Component = findOne(raw.type);

      if (Component) {
        return Component;
      } else if (isBn(instance)) {
        return Amount;
      } else if ([TypeDefInfo.Enum, TypeDefInfo.Struct, TypeDefInfo.Tuple].includes(raw.info)) {
        return findComponent(registry, raw, overrides);
      } else if (raw.info === TypeDefInfo.VecFixed && (raw.sub as TypeDef).type !== 'u8') {
        return findComponent(registry, raw, overrides);
      }
    } catch (e) {
      error = (e as Error).message;
    }

    // we only want to want once, not spam
    if (!warnList.includes(type)) {
      warnList.push(type);
      error && console.error(`params: findComponent: ${error}`);
      console.info(`params: findComponent: No pre-defined component for type ${type} from ${JSON.stringify(def)}, using defaults`);
    }
  }

  return Component || Unknown;
}
Example #6
Source File: QueryResult.tsx    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
QueryResult = ({ result: { time, data, message, error }, date }: Props) => {
  const { api } = useApi();

  const value =
    message.returnType && encodeTypeDef(api.registry, message.returnType) === 'u128' && isBn(data)
      ? fromSats(api, data).toString()
      : data?.toString();

  return (
    <div
      key={`${time}`}
      className={
        'text-xs dark:text-gray-400 text-gray-600 break-all p-4 border-b border-gray-200 dark:border-gray-700'
      }
      data-cy={message.method}
    >
      <div className="mb-2">{date}</div>
      <div>
        <div className="mb-2">
          <MessageSignature message={message} />
        </div>
        <div className="dark:bg-elevation-1 bg-gray-200 p-2 rounded-sm text-mono return-value">
          {value}
          <CopyButton className="float-right" value={value || ''} />
        </div>
      </div>
      {error && (
        <ReactMarkdown
          // eslint-disable-next-line react/no-children-prop
          children={error.docs.join('\r\n')}
          remarkPlugins={[remarkGfm]}
          className="markdown mt-4"
        />
      )}
    </div>
  );
}
Example #7
Source File: Line.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function calculateOptions(
  colors: (string | undefined)[] = [],
  legends: string[],
  labels: string[],
  values: (number | BN)[][]
): State {
  const chartData = values.reduce(
    (chartData, values, index): Config => {
      const color = colors[index] || alphaColor(COLORS[index]);
      const data = values.map((value): number => (isBn(value) ? value.toNumber() : value));

      chartData.datasets.push({
        backgroundColor: color,
        borderColor: color,
        data,
        fill: false,
        hoverBackgroundColor: color,
        label: legends[index],
      });

      return chartData;
    },
    { datasets: [] as Dataset[], labels }
  );

  return {
    chartData,
    // eslint-disable-next-line
    // @ts-ignore
    chartOptions,
  };
}
Example #8
Source File: InputNumber.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function getValues(
  api: ApiPromise,
  value: BN | string = BN_ZERO,
  si: SiDef | null,
  bitLength: BitLength,
  isZeroable: boolean,
  maxValue?: BN,
  decimals?: number
): [string, BN, boolean] {
  return isBn(value)
    ? getValuesFromBn(value, si, isZeroable, decimals)
    : getValuesFromString(api, value, si, bitLength, isZeroable, maxValue, decimals);
}
Example #9
Source File: InputCandyNumber.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function getValues (api: ApiPromise, value: BN | string = BN_ZERO, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [string, BN, boolean] {
  return isBn(value)
    ? getValuesFromBn(value, si)
    : getValuesFromString(api, value, si, bitLength, isZeroable, maxValue);
}
Example #10
Source File: InputCsmNumber.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function getValues (api: ApiPromise, value: BN | string = BN_ZERO, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [string, BN, boolean] {
  return isBn(value)
    ? getValuesFromBn(value, si)
    : getValuesFromString(api, value, si, bitLength, isZeroable, maxValue);
}
Example #11
Source File: InputNumber.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function getValues (api: ApiPromise, value: BN | string = BN_ZERO, si: SiDef | null, bitLength: BitLength, isZeroable: boolean, maxValue?: BN): [string, BN, boolean] {
  return isBn(value)
    ? getValuesFromBn(value, si, isZeroable)
    : getValuesFromString(api, value, si, bitLength, isZeroable, maxValue);
}
Example #12
Source File: useBalance.ts    From contracts-ui with GNU General Public License v3.0 5 votes vote down vote up
export function useBalance(
  initialValue: BN | string | number = 0,
  { bitLength = DEFAULT_BITLENGTH, isZeroable = true, maxValue }: ValidateOptions = {}
): UseBalance {
  const { api } = useApi();

  const validate = useCallback(
    (value: BN | null | undefined): Validation => {
      let message: React.ReactNode;
      let isError = false;

      if (!value) {
        isError = true;
        return {
          isError,
        };
      }

      if (value?.lt(BN_ZERO)) {
        isError = true;
        message = 'Value cannot be negative';
      }

      if (value?.gt(getGlobalMaxValue(bitLength))) {
        isError = true;
        message = 'Value exceeds global maximum';
      }

      if (!isZeroable && value?.isZero()) {
        isError = true;
        message = 'Value cannot be zero';
      }

      if (value && value?.bitLength() > (bitLength || DEFAULT_BITLENGTH)) {
        isError = true;
        message = "Value's bitlength is too high";
      }

      if (maxValue && maxValue.gtn(0) && value?.gt(maxValue)) {
        isError = true;
        message = `Value cannot exceed ${formatBalance(maxValue?.toString())}`;
      }

      return {
        isError,
        isValid: !isError,
        message,
      };
    },
    [bitLength, isZeroable, maxValue]
  );

  const balance = useFormField<BN>(
    isBn(initialValue) ? toSats(api, initialValue) : toBalance(api, initialValue),
    validate
  );

  return balance;
}
Example #13
Source File: findComponent.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
// eslint-disable-next-line complexity
export default function findComponent(
  registry: Registry,
  def: TypeDef,
  overrides: ComponentMap = {}
): React.ComponentType<Props> {
  const findOne = (type: string): React.ComponentType<Props> | null => overrides[type] || components[type];
  const type = fromDef(def);
  let Component = findOne(type);

  if (!Component) {
    let error: string | null = null;

    try {
      const instance = registry.createType(type as 'u32');
      const raw = getTypeDef(instance.toRawType());

      Component = findOne(raw.type);

      if (Component) {
        return Component;
      } else if (isBn(instance)) {
        return Amount;
      } else if ([TypeDefInfo.Enum, TypeDefInfo.Struct, TypeDefInfo.Tuple].includes(raw.info)) {
        return findComponent(registry, raw, overrides);
      } else if (raw.info === TypeDefInfo.VecFixed && (raw.sub as TypeDef).type !== 'u8') {
        return findComponent(registry, raw, overrides);
      }
    } catch (e) {
      error = (e as Error).message;
    }

    // we only want to want once, not spam
    if (!warnList.includes(type)) {
      warnList.push(type);
      // eslint-disable-next-line
      error && console.error(`params: findComponent: ${error}`);
      console.info(
        `params: findComponent: No pre-defined component for type ${type} from ${JSON.stringify(def)}, using defaults`
      );
    }
  }

  return Component || Unknown;
}
Example #14
Source File: Vote.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
// eslint-disable-next-line complexity
function Vote({
  className = '',
  defaultValue: { value },
  isDisabled,
  isError,
  onChange,
  withLabel,
}: Props): React.ReactElement<Props> {
  const { t } = useTranslation();

  const optAyeRef = useRef([
    { text: t<string>('Nay'), value: 0 },
    { text: t<string>('Aye'), value: -1 },
  ]);

  const optConvRef = useRef([
    { text: t<string>('None'), value: 0 },
    { text: t<string>('Locked1x'), value: 1 },
    { text: t<string>('Locked2x'), value: 2 },
    { text: t<string>('Locked3x'), value: 3 },
    { text: t<string>('Locked4x'), value: 4 },
    { text: t<string>('Locked5x'), value: 5 },
    { text: t<string>('Locked6x'), value: 6 },
  ]);

  const defaultValue = isBn(value)
    ? value.toNumber()
    : value instanceof GenericVote
    ? value.isAye
      ? -1
      : 0
    : (value as number);
  const defaultConv = value instanceof GenericVote ? value.conviction.index : 0;

  return (
    <Bare className={className}>
      <Dropdown
        className="full"
        defaultValue={defaultValue}
        isDisabled={isDisabled}
        isError={isError}
        label={t<string>('aye: bool')}
        onChange={doChange(onChange)}
        options={optAyeRef.current}
        withLabel={withLabel}
      />
      {isDisabled && (
        <Dropdown
          className="full"
          defaultValue={defaultConv}
          isDisabled={isDisabled}
          isError={isError}
          label={t<string>('conviction: Conviction')}
          options={optConvRef.current}
          withLabel={withLabel}
        />
      )}
    </Bare>
  );
}
Example #15
Source File: initValue.ts    From subscan-multisig-react with Apache License 2.0 4 votes vote down vote up
// eslint-disable-next-line complexity
export default function getInitValue(registry: Registry, def: TypeDef): unknown {
  if (def.info === TypeDefInfo.Vec) {
    return [getInitValue(registry, def.sub as TypeDef)];
  } else if (def.info === TypeDefInfo.Tuple) {
    return Array.isArray(def.sub) ? def.sub.map((item) => getInitValue(registry, item)) : [];
  } else if (def.info === TypeDefInfo.Struct) {
    return Array.isArray(def.sub)
      ? def.sub.reduce((result: Record<string, unknown>, cur): Record<string, unknown> => {
          result[cur.name as string] = getInitValue(registry, cur);

          return result;
        }, {})
      : {};
  } else if (def.info === TypeDefInfo.Enum) {
    return Array.isArray(def.sub) ? { [def.sub[0].name as string]: getInitValue(registry, def.sub[0]) } : {};
  }

  const type = [TypeDefInfo.Compact, TypeDefInfo.Option].includes(def.info) ? (def.sub as TypeDef).type : def.type;

  switch (type) {
    case 'AccountIndex':
    case 'Balance':
    case 'BalanceOf':
    case 'BlockNumber':
    case 'Compact':
    case 'Gas':
    case 'Index':
    case 'Nonce':
    case 'ParaId':
    case 'PropIndex':
    case 'ProposalIndex':
    case 'ReferendumIndex':
    case 'i8':
    case 'i16':
    case 'i32':
    case 'i64':
    case 'i128':
    case 'u8':
    case 'u16':
    case 'u32':
    case 'u64':
    case 'u128':
    case 'VoteIndex':
      return BN_ZERO;

    case 'bool':
      return false;

    case 'Bytes':
      return undefined;

    case 'String':
    case 'Text':
      return '';

    case 'Moment':
      return BN_ZERO;

    case 'Vote':
      return -1;

    case 'VoteThreshold':
      return 0;

    case 'BlockHash':
    case 'CodeHash':
    case 'Hash':
    case 'H256':
      return registry.createType('H256');

    case 'H512':
      return registry.createType('H512');

    case 'H160':
      return registry.createType('H160');

    case 'Raw':
    case 'Keys':
      return '';

    case 'AccountId':
    case 'AccountIdOf':
    case 'Address':
    case 'Call':
    case 'CandidateReceipt':
    case 'Digest':
    case 'Header':
    case 'KeyValue':
    case 'LookupSource':
    case 'MisbehaviorReport':
    case 'Proposal':
    case 'Signature':
    case 'SessionKey':
    case 'StorageKey':
    case 'ValidatorId':
      return undefined;

    case 'Extrinsic':
      return registry.createType('Raw');

    case 'Null':
      return null;

    default: {
      let error: string | null = null;

      try {
        const instance = registry.createType(type as 'u32');
        const raw = getTypeDef(instance.toRawType());

        if (isBn(instance)) {
          return BN_ZERO;
        } else if ([TypeDefInfo.Struct].includes(raw.info)) {
          return undefined;
        } else if ([TypeDefInfo.Enum, TypeDefInfo.Tuple].includes(raw.info)) {
          return getInitValue(registry, raw);
        }
      } catch (e) {
        error = (e as Error).message;
      }

      // we only want to want once, not spam
      if (!warnList.includes(type)) {
        warnList.push(type);
        // eslint-disable-next-line
        error && console.error(`params: initValue: ${error}`);
        console.info(
          `params: initValue: No default value for type ${type} from ${JSON.stringify(def)}, using defaults`
        );
      }

      return '0x';
    }
  }
}
Example #16
Source File: initValue.ts    From contracts-ui with GNU General Public License v3.0 4 votes vote down vote up
export function getInitValue(registry: Registry, keyring: Keyring, def: TypeDef): unknown {
  if (def.info === TypeDefInfo.Si) {
    const lookupTypeDef = registry.lookup.getTypeDef(def.lookupIndex as number);

    return getInitValue(registry, keyring, lookupTypeDef);
  } else if (def.info === TypeDefInfo.Option) {
    return null;
  } else if (def.info === TypeDefInfo.Vec) {
    return [getInitValue(registry, keyring, def.sub as TypeDef)];
  } else if (def.info === TypeDefInfo.Tuple) {
    return Array.isArray(def.sub) ? def.sub.map(def => getInitValue(registry, keyring, def)) : [];
  } else if (def.info === TypeDefInfo.Struct) {
    return Array.isArray(def.sub)
      ? def.sub.reduce((result: Record<string, unknown>, def): Record<string, unknown> => {
          result[def.name as string] = getInitValue(registry, keyring, def);

          return result;
        }, {})
      : {};
  } else if (def.info === TypeDefInfo.Enum) {
    return Array.isArray(def.sub)
      ? { [def.sub[0].name as string]: getInitValue(registry, keyring, def.sub[0]) }
      : {};
  }

  const type = [TypeDefInfo.Compact, TypeDefInfo.Option].includes(def.info)
    ? (def.sub as TypeDef).type
    : def.type;

  switch (type) {
    case 'AccountIndex':
    case 'Balance':
    case 'BalanceOf':
    case 'BlockNumber':
    case 'Compact':
    case 'Gas':
    case 'Index':
    case 'Nonce':
    case 'ParaId':
    case 'PropIndex':
    case 'ProposalIndex':
    case 'ReferendumIndex':
    case 'i8':
    case 'i16':
    case 'i32':
    case 'i64':
    case 'i128':
    case 'u8':
    case 'u16':
    case 'u32':
    case 'u64':
    case 'u128':
    case 'VoteIndex':
      return BN_ZERO;

    case 'bool':
      return false;

    case 'Bytes':
      return undefined;

    case 'String':
    case 'Text':
      return '';

    case 'Moment':
      return BN_ZERO;

    case 'Vote':
      return -1;

    case 'VoteThreshold':
      return 0;

    case 'BlockHash':
    case 'CodeHash':
    case 'Hash':
    case 'H256':
      return registry.createType('H256');

    case 'H512':
      return registry.createType('H512');

    case 'H160':
      return registry.createType('H160');

    case 'Raw':
    case 'Keys':
      return '';

    case 'AccountId':
      return keyring.getAccounts()[0].address;

    case 'AccountIdOf':
    case 'Address':
    case 'Call':
    case 'CandidateReceipt':
    case 'Digest':
    case 'Header':
    case 'KeyValue':
    case 'LookupSource':
    case 'MisbehaviorReport':
    case 'Proposal':
    case 'Signature':
    case 'SessionKey':
    case 'StorageKey':
    case 'ValidatorId':
      return undefined;

    case 'Extrinsic':
      return registry.createType('Raw');

    case 'Null':
      return null;

    default: {
      let error: string | null = null;

      try {
        const instance = registry.createType(type as 'u32');
        const raw = getTypeDef(instance.toRawType());

        if (isBn(instance)) {
          return BN_ZERO;
        } else if ([TypeDefInfo.Struct].includes(raw.info)) {
          return undefined;
        } else if ([TypeDefInfo.Enum, TypeDefInfo.Tuple].includes(raw.info)) {
          return getInitValue(registry, keyring, raw);
        }
      } catch (e) {
        error = (e as Error).message;
      }

      // we only want to warn once, not spam
      if (!warnList.includes(type)) {
        warnList.push(type);
        error && console.error(`params: initValue: ${error}`);
        console.info(
          `params: initValue: No default value for type ${type} from ${JSON.stringify(
            def
          )}, using defaults`
        );
      }

      return '0x';
    }
  }
}
Example #17
Source File: initValue.ts    From crust-apps with Apache License 2.0 4 votes vote down vote up
export default function getInitValue (registry: Registry, def: TypeDef): unknown {
  if (def.info === TypeDefInfo.Vec) {
    return [getInitValue(registry, def.sub as TypeDef)];
  } else if (def.info === TypeDefInfo.Tuple) {
    return Array.isArray(def.sub)
      ? def.sub.map((def) => getInitValue(registry, def))
      : [];
  } else if (def.info === TypeDefInfo.Struct) {
    return Array.isArray(def.sub)
      ? def.sub.reduce((result: Record<string, unknown>, def): Record<string, unknown> => {
        result[def.name as string] = getInitValue(registry, def);

        return result;
      }, {})
      : {};
  } else if (def.info === TypeDefInfo.Enum) {
    return Array.isArray(def.sub)
      ? { [def.sub[0].name as string]: getInitValue(registry, def.sub[0]) }
      : {};
  }

  const type = [TypeDefInfo.Compact, TypeDefInfo.Option].includes(def.info)
    ? (def.sub as TypeDef).type
    : def.type;

  switch (type) {
    case 'AccountIndex':
    case 'Balance':
    case 'BalanceOf':
    case 'BlockNumber':
    case 'Compact':
    case 'Gas':
    case 'Index':
    case 'Nonce':
    case 'ParaId':
    case 'PropIndex':
    case 'ProposalIndex':
    case 'ReferendumIndex':
    case 'i8':
    case 'i16':
    case 'i32':
    case 'i64':
    case 'i128':
    case 'u8':
    case 'u16':
    case 'u32':
    case 'u64':
    case 'u128':
    case 'VoteIndex':
      return BN_ZERO;

    case 'bool':
      return false;

    case 'Bytes':
      return undefined;

    case 'String':
    case 'Text':
      return '';

    case 'Moment':
      return BN_ZERO;

    case 'Vote':
      return -1;

    case 'VoteThreshold':
      return 0;

    case 'BlockHash':
    case 'CodeHash':
    case 'Hash':
    case 'H256':
      return registry.createType('H256');

    case 'H512':
      return registry.createType('H512');

    case 'H160':
      return registry.createType('H160');

    case 'Raw':
    case 'Keys':
      return '';

    case 'AccountId':
    case 'AccountIdOf':
    case 'Address':
    case 'Call':
    case 'CandidateReceipt':
    case 'Digest':
    case 'Header':
    case 'KeyValue':
    case 'LookupSource':
    case 'MisbehaviorReport':
    case 'Proposal':
    case 'Signature':
    case 'SessionKey':
    case 'StorageKey':
    case 'ValidatorId':
      return undefined;

    case 'Extrinsic':
      return registry.createType('Raw');

    case 'Null':
      return null;

    default: {
      let error: string | null = null;

      try {
        const instance = registry.createType(type as 'u32');
        const raw = getTypeDef(instance.toRawType());

        if (isBn(instance)) {
          return BN_ZERO;
        } else if ([TypeDefInfo.Struct].includes(raw.info)) {
          return undefined;
        } else if ([TypeDefInfo.Enum, TypeDefInfo.Tuple].includes(raw.info)) {
          return getInitValue(registry, raw);
        }
      } catch (e) {
        error = (e as Error).message;
      }

      // we only want to want once, not spam
      if (!warnList.includes(type)) {
        warnList.push(type);
        error && console.error(`params: initValue: ${error}`);
        console.info(`params: initValue: No default value for type ${type} from ${JSON.stringify(def)}, using defaults`);
      }

      return '0x';
    }
  }
}