types#UseBalance TypeScript Examples

The following examples show how to use types#UseBalance. 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: 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;
}