@polkadot/util#isHex TypeScript Examples

The following examples show how to use @polkadot/util#isHex. 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: utils.ts    From bodhi.js with Apache License 2.0 7 votes vote down vote up
export function toBN(bigNumberis: BigNumberish = 0): BN {
  if (isU8a(bigNumberis)) {
    return u8aToBn(bigNumberis);
  }
  if (isHex(bigNumberis)) {
    return hexToBn(bigNumberis);
  }

  if (BigNumber.isBigNumber(bigNumberis)) {
    const hex = bigNumberis.toHexString();
    if (hex[0] === '-') {
      return new BN('-' + hex.substring(3), 16);
    }
    return new BN(hex.substring(2), 16);
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return new BN(bigNumberis as any);
}
Example #2
Source File: utils.ts    From evm-provider.js with Apache License 2.0 7 votes vote down vote up
export function toBN(bigNumberis: BigNumberish = 0): BN {
  if (isU8a(bigNumberis)) {
    return u8aToBn(bigNumberis);
  }
  if (isHex(bigNumberis)) {
    return hexToBn(bigNumberis);
  }

  if (BigNumber.isBigNumber(bigNumberis)) {
    const hex = bigNumberis.toHexString();
    if (hex[0] === '-') {
      return new BN('-' + hex.substring(3), 16);
    }
    return new BN(hex.substring(2), 16);
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return new BN(bigNumberis as any);
}
Example #3
Source File: utils.ts    From gear-js with GNU General Public License v3.0 7 votes vote down vote up
export function getTypesFromTypeDef(
  types: Uint8Array | Hex,
  registry?: Registry,
): { typesFromTypeDef: any; namespaces: Map<string, string> } {
  if (!registry) {
    registry = new TypeRegistry();
  }
  const typesFromTypeDef = {};
  const namespaces = new Map<string, string>();
  const portableReg = new PortableRegistry(registry, isHex(types) ? hexToU8a(types) : types, true);
  portableReg.types.forEach(({ id, type: { path } }) => {
    const typeDef = portableReg.getTypeDef(id);
    if (path.length === 0 || (!typeDef.lookupName && !typeDef.lookupNameRoot)) {
      return;
    }
    const name = portableReg.getName(id);
    let camelCasedNamespace = toCamelCase(path.slice(0, path.length - 1));
    if (camelCasedNamespace === name) {
      camelCasedNamespace = path.length > 2 ? toCamelCase(path.slice(0, path.length - 2)) : undefined;
    }
    namespaces.set(name.replace(camelCasedNamespace, ''), name);
    typesFromTypeDef[typeDef.lookupName || typeDef.lookupNameRoot] = typeDef.type.toString();
  });
  return { typesFromTypeDef, namespaces };
}
Example #4
Source File: addressSwapper.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
AddressSwapper = (options) => {
  if (!options.address) throw new Error('No address provided to swap');
  if (!options.currentPrefix) return options.address;
  if (isU8a(options.address) || isHex(options.address)) {
    throw new Error('address not in SS58 format');
  }
  // check if it is valid as an address
  let decodedAddress: Uint8Array;
  try {
    decodedAddress = decodeAddress(options.address);
  } catch (e) {
    throw new Error('failed to decode address');
  }
  // check if it is valid with the current prefix & reencode if needed
  const [valid, errorMsg] = checkAddress(options.address, options.currentPrefix);
  if (!valid) {
    try {
      return encodeAddress(decodedAddress, options.currentPrefix);
    } catch (e) {
      throw new Error('failed to reencode address');
    }
  } else {
    return options.address;
  }
}
Example #5
Source File: KeyValueArray.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function parseFile (raw: Uint8Array): Parsed {
  const json = JSON.parse(u8aToString(raw)) as Record<string, string>;
  const keys = Object.keys(json);
  let isValid = keys.length !== 0;
  const value = keys.map((key): [Uint8Array, Uint8Array] => {
    const value = json[key];

    assert(isHex(key) && isHex(value), `Non-hex key/value pair found in ${key.toString()} => ${value.toString()}`);

    const encKey = createParam(key);
    const encValue = createParam(value);

    isValid = isValid && encKey.isValid && encValue.isValid;

    return [encKey.u8a, encValue.u8a];
  });

  return {
    isValid,
    value
  };
}
Example #6
Source File: GasSpent.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
private getPayload(
    payload: PayloadType,
    metaOrTypeOfPayload: string | Metadata,
    meta_type: string,
  ): Hex | Uint8Array {
    if (isHex(payload)) {
      return payload;
    } else if (isU8a(payload)) {
      return u8aToHex(payload);
    }
    if (!metaOrTypeOfPayload) {
      throw new GetGasSpentError('Impossible to create bytes from payload without specified type or meta');
    }
    const [type, meta] = isString(metaOrTypeOfPayload)
      ? [metaOrTypeOfPayload, undefined]
      : [metaOrTypeOfPayload[meta_type], metaOrTypeOfPayload];
    return createPayload(this.createType, type, payload, meta);
  }
Example #7
Source File: GasSpent.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
async init(
    sourceId: Hex,
    code: Hex | Buffer,
    payload: PayloadType,
    value: number | string,
    metaOrTypeOfPayload?: string | Metadata,
  ): Promise<u64> {
    return await this.api.rpc['gear'].getInitGasSpent(
      sourceId,
      isHex(code) ? code : this.createType.create('bytes', Array.from(code)).toHex(),
      this.getPayload(payload, metaOrTypeOfPayload, 'init_input'),
      value || 0,
    );
  }
Example #8
Source File: CreateType.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
private createRegistry(types?: any): Map<string, string> {
    if (!types) {
      return null;
    }
    if (isHex(types) || isU8a(types)) {
      const { typesFromTypeDef, namespaces } = getTypesFromTypeDef(types, this.registry);
      types = typesFromTypeDef;
      this.namespaces = namespaces;
    }
    this.registerTypes(types);
    return this.namespaces;
  }
Example #9
Source File: generate.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
export function createPayload(createType: CreateType, type: any, data: any, meta?: Metadata): Hex {
  if (data === undefined) {
    return '0x00';
  }
  if (isHex(data)) {
    return data;
  } else if (isU8a(data)) {
    return u8aToHex(data);
  }
  let payload = data;
  if (meta && type) {
    const encoded = createType.create(type, data, meta);
    payload = isHex(encoded) ? encoded : encoded.toHex();
  } else if (type) {
    try {
      const encoded = createType.create(type, data);
      payload = isHex(encoded) ? encoded : encoded.toHex();
    } catch (error) {
      console.error(error.message);
    }
  }
  return payload;
}
Example #10
Source File: address_swapper.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
AddressSwapper = (options: {
  address: string, currentPrefix: number,
}): string => {
  if (!options.address) throw new Error('No address provided to swap');
  if (!options.currentPrefix) return options.address;
  if (isU8a(options.address) || isHex(options.address)) {
    throw new Error('address not in SS58 format');
  }
  // check if it is valid as an address
  let decodedAddress: Uint8Array;
  try {
    decodedAddress = decodeAddress(options.address);
  } catch (e) {
    throw new Error('failed to decode address');
  }
  // check if it is valid with the current prefix & reencode if needed
  const [valid, errorMsg] = checkAddress(options.address, options.currentPrefix);
  if (!valid) {
    try {
      return encodeAddress(decodedAddress, options.currentPrefix);
    } catch (e) {
      throw new Error('failed to reencode address');
    }
  } else {
    return options.address;
  }
}
Example #11
Source File: Blocks.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Get data of particular block by blockNumber or blockHash
   * @param hashOrNumber
   * @returns
   */
  async get(hashOrNumber: `0x${string}` | Uint8Array | number): Promise<SignedBlock> {
    const hash = isU8a(hashOrNumber) || isHex(hashOrNumber) ? hashOrNumber : await this.getBlockHash(+hashOrNumber);
    try {
      return await this.api.rpc.chain.getBlock(hash);
    } catch (error) {
      throw new GetBlockError(error.message, hash);
    }
  }
Example #12
Source File: is-valid-polkadot-address.ts    From interbtc-ui with Apache License 2.0 6 votes vote down vote up
isValidPolkadotAddress = (address: string): boolean => {
  try {
    encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address));

    return true;
  } catch {
    return false;
  }
}
Example #13
Source File: InputFile.tsx    From contracts-ui with GNU General Public License v3.0 6 votes vote down vote up
function convertResult(result: ArrayBuffer): Uint8Array {
  const data = new Uint8Array(result);

  // this converts the input (if detected as hex), via the hex conversion route
  if (data[0] === BYTE_STR_0 && data[1] === BYTE_STR_X) {
    let hex = u8aToString(data);

    while (hex[hex.length - 1] === STR_NL) {
      hex = hex.substr(0, hex.length - 1);
    }

    if (isHex(hex)) {
      return hexToU8a(hex);
    }
  }

  return data;
}
Example #14
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
async _resolveBlockHash(
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<string> {
    await this.resolveApi;

    if (!blockTag) return undefined;

    const resolvedBlockHash = await blockTag;

    if (resolvedBlockHash === 'pending') {
      throw new Error('Unsupport Block Pending');
    }

    if (resolvedBlockHash === 'latest') {
      const hash = await this.api.query.system.blockHash();
      return hash.toString();
    }

    if (resolvedBlockHash === 'earliest') {
      const hash = this.api.query.system.blockHash(0);
      return hash.toString();
    }

    if (isHex(resolvedBlockHash)) {
      return resolvedBlockHash;
    }

    const hash = await this.api.query.system.blockHash(resolvedBlockHash);

    return hash.toString();
  }
Example #15
Source File: InputFile.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function convertResult(result: ArrayBuffer): Uint8Array {
  const data = new Uint8Array(result);

  // this converts the input (if detected as hex), via the hex conversion route
  if (data[0] === BYTE_STR_0 && data[1] === BYTE_STR_X) {
    let hex = u8aToString(data);

    while (hex[hex.length - 1] === STR_NL) {
      hex = hex.substr(0, hex.length - 1);
    }

    if (isHex(hex)) {
      return hexToU8a(hex);
    }
  }

  return data;
}
Example #16
Source File: toAddress.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
// eslint-disable-next-line complexity
export default function toAddress(value?: string | Uint8Array | null, allowIndices = false): string | undefined {
  if (value) {
    try {
      const u8a = isHex(value) ? hexToU8a(value) : keyring.decodeAddress(value);

      assert(allowIndices || u8a.length === 32 || u8a.length === 20, 'AccountIndex values not allowed');

      if (u8a.length === 20) {
        return ethereumEncode(u8a);
      } else {
        return keyring.encodeAddress(u8a);
      }
    } catch (error) {
      // noop, undefined return indicates invalid/transient
    }
  }

  return undefined;
}
Example #17
Source File: KeyValueArray.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function parseFile(raw: Uint8Array): Parsed {
  const json = JSON.parse(u8aToString(raw)) as Record<string, string>;
  const keys = Object.keys(json);
  let isValid = keys.length !== 0;
  const value = keys.map((key): [Uint8Array, Uint8Array] => {
    const val = json[key];

    assert(isHex(key) && isHex(val), `Non-hex key/value pair found in ${key.toString()} => ${val.toString()}`);

    const encKey = createParam(key);
    const encValue = createParam(val);

    isValid = isValid && encKey.isValid && encValue.isValid;

    return [encKey.u8a, encValue.u8a];
  });

  return {
    isValid,
    value,
  };
}
Example #18
Source File: validate.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
isSS58Address = (address: string) => {
  try {
    encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address));

    return true;
  } catch (error) {
    return false;
  }
}
Example #19
Source File: ValidateCode.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function ValidateCode ({ codeHash, onChange }: Props): React.ReactElement<Props> | null {
  const { api } = useApi();
  const { t } = useTranslation();
  const codeStorage = useCall<Option<PrefabWasmModule>>((api.query.contracts || api.query.contract).codeStorage, [codeHash]);
  const [isValidHex, isValid] = useMemo(
    (): [boolean, boolean] => {
      const isValidHex = !!codeHash && isHex(codeHash) && codeHash.length === 66;
      const isStored = !!codeStorage && codeStorage.isSome;
      const isValid = isValidHex && isStored;

      onChange(isValid);

      return [
        isValidHex,
        isValid
      ];
    },
    [codeHash, codeStorage, onChange]
  );

  if (isValid || !isValidHex) {
    return null;
  }

  return (
    <InfoForInput type='error'>
      {
        isValidHex
          ? t('Unable to find on-chain WASM code for the supplied codeHash')
          : t('The codeHash is not a valid hex hash')
      }
    </InfoForInput>
  );
}
Example #20
Source File: toAddress.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default function toAddress (value?: string | Uint8Array | null, allowIndices = false): string | undefined {
  if (value) {
    try {
      const u8a = isHex(value)
        ? hexToU8a(value)
        : keyring.decodeAddress(value);

      assert(allowIndices || u8a.length === 32 || u8a.length === 20, 'AccountIndex values not allowed');

      if (u8a.length === 20) {
        return ethereumEncode(u8a);
      } else {
        return keyring.encodeAddress(u8a);
      }
    } catch (error) {
      // noop, undefined return indicates invalid/transient
    }
  }

  return undefined;
}
Example #21
Source File: InputFile.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function convertResult (result: ArrayBuffer): Uint8Array {
  const data = new Uint8Array(result);

  // this converts the input (if detected as hex), via the hex conversion route
  if (data[0] === BYTE_STR_0 && data[1] === BYTE_STR_X) {
    let hex = u8aToString(data);

    while (hex[hex.length - 1] === STR_NL) {
      hex = hex.substr(0, hex.length - 1);
    }

    if (isHex(hex)) {
      return hexToU8a(hex);
    }
  }

  return data;
}
Example #22
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function Entry (): React.ReactElement | null {
  const bestNumber = useBestNumber();
  const { value } = useParams<{ value: string }>();
  const [stateValue, setStateValue] = useState<string | undefined>(value);

  useEffect((): void => {
    setStateValue((stateValue) =>
      value && value !== stateValue
        ? value
        : !stateValue && bestNumber
          ? bestNumber.toString()
          : stateValue
    );
  }, [bestNumber, value]);

  if (!stateValue) {
    return null;
  }

  const Component = isHex(stateValue)
    ? BlockByHash
    : BlockByNumber;

  return (
    <>
      <Query />
      <Component
        key={stateValue}
        value={stateValue}
      />
    </>
  );
}
Example #23
Source File: Query.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function stateFromValue (value: string): State {
  return {
    isValid: isHex(value, 256) || /^\d+$/.test(value),
    value
  };
}
Example #24
Source File: index.ts    From sdk with Apache License 2.0 5 votes vote down vote up
async function signPayload(api: ApiPromise, { payload }, password: string) {
  const { method, params } = payload;
  const address = params[0];
  const keyPair = ((window as any).keyring as Keyring).getPair(address);
  try {
    if (!keyPair.isLocked) {
      keyPair.lock();
    }
    keyPair.decodePkcs8(password);

    if (method == "signExtrinsic") {
      const txInfo = params[1];
      const { header, mortalLength, nonce } = (await api.derive.tx.signingInfo(address)) as any;
      const tx = api.tx[txInfo.module][txInfo.call](...txInfo.params);

      const signerPayload = api.registry.createType("SignerPayload", {
        address,
        blockHash: header.hash,
        blockNumber: header ? header.number : 0,
        era: api.registry.createType("ExtrinsicEra", {
          current: header.number,
          period: mortalLength,
        }),
        genesisHash: api.genesisHash,
        method: tx.method,
        nonce,
        signedExtensions: ["CheckNonce"],
        tip: txInfo.tip,
        runtimeVersion: {
          specVersion: api.runtimeVersion.specVersion,
          transactionVersion: api.runtimeVersion.transactionVersion,
        },
        version: api.extrinsicVersion,
      });
      const payload = signerPayload.toPayload();
      const txPayload = api.registry.createType("ExtrinsicPayload", payload, {
        version: payload.version,
      });
      const signed = txPayload.sign(keyPair);
      return signed;
    }
    if (method == "signBytes") {
      const msg = params[1];
      const isDataHex = isHex(msg);
      return {
        signature: u8aToHex(keyPair.sign(isDataHex ? hexToU8a(msg) : stringToU8a(msg))),
      };
    }
  } catch (err) {
    (window as any).send({ error: err.message });
  }

  return {};
}
Example #25
Source File: index.ts    From parity-bridges-ui with GNU General Public License v3.0 5 votes vote down vote up
export async function getTransactionCallWeight({
  action,
  account,
  targetApi,
  transactionState
}: TransactionCallWeightInput) {
  let weight: number = 0;
  let call: Uint8Array | null = null;
  const { receiverAddress, transferAmount, remarkInput, customCallInput, weightInput } = transactionState;

  if (account) {
    switch (action) {
      case TransactionTypes.REMARK:
        call = (await targetApi.tx.system.remark(remarkInput)).toU8a();
        // TODO [#121] Figure out what the extra bytes are about
        logger.info(`system::remark: ${u8aToHex(call)}`);
        weight = (await targetApi.tx.system.remark(remarkInput).paymentInfo(account)).weight.toNumber();
        break;
      case TransactionTypes.TRANSFER:
        if (receiverAddress) {
          call = (await targetApi.tx.balances.transfer(receiverAddress, transferAmount || 0)).toU8a();
          // TODO [#121] Figure out what the extra bytes are about
          logger.info(`balances::transfer: ${u8aToHex(call)}`);
          logger.info(`after balances::transfer: ${u8aToHex(call)}`);
          weight = (
            await targetApi.tx.balances.transfer(receiverAddress, transferAmount || 0).paymentInfo(account)
          ).weight.toNumber();
        }
        break;
      case TransactionTypes.CUSTOM:
        if (customCallInput) {
          call = isHex(customCallInput) ? hexToU8a(customCallInput.toString()) : null;
          weight = parseInt(weightInput!);
        }
        break;
      default:
        throw new Error(`Unknown type: ${action}`);
    }
  }
  return { call, weight };
}
Example #26
Source File: CreateConfirmation.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function CreateConfirmation ({ address, derivePath, name, pairType, seed }: Props): React.ReactElement<Props> | null {
  const { t } = useTranslation();

  const splitSeed = seed && seed.split(' ');
  const shortSeed = isHex(seed)
    ? `${seed.substr(10)}${seed.substr(-8)}`
    : splitSeed && splitSeed.map((value, index) => (index % 3) ? '…' : value).join(' ');

  return (
    <Modal.Content>
      <Modal.Columns hint={
        <>
          <p>{t<string>('We will provide you with a generated backup file after your account is created. As long as you have access to your account you can always download this file later by clicking on "Backup" button from the Accounts section.')}</p>
          <p>{t<string>('Please make sure to save this file in a secure location as it is required, together with your password, to restore your account.')}</p>
        </>
      }>
        {address && name && <AddressRow
          defaultName={name}
          isInline
          noDefaultNameOpacity
          value={address}
        />}
        {shortSeed && (
          <Static
            label={t<string>('partial seed')}
            value={shortSeed}
          />
        )}
        <Static
          label={t<string>('keypair type')}
          value={pairType}
        />
        <Static
          label={t<string>('derivation path')}
          value={derivePath || t<string>('<none provided>')}
        />
      </Modal.Columns>
    </Modal.Content>
  );
}
Example #27
Source File: BaseBytes.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function BaseBytes({
  asHex,
  children,
  className = '',
  defaultValue: { value },
  isDisabled,
  isError,
  label,
  length = -1,
  onChange,
  onEnter,
  onEscape,
  size = 'full',
  validate = defaultValidate,
  withCopy,
  withLabel,
  withLength,
}: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const [defaultValue] = useState(
    value
      ? isDisabled && isU8a(value) && isAscii(value)
        ? u8aToString(value)
        : isHex(value)
        ? value
        : // eslint-disable-next-line no-magic-numbers
          u8aToHex(value as Uint8Array, isDisabled ? 256 : -1)
      : undefined
  );
  const [isValid, setIsValid] = useState(false);

  const _onChange = useCallback(
    (hex: string): void => {
      let [beValid, val] = convertInput(hex);

      beValid = beValid && validate(val) && (length !== -1 ? val.length === length : val.length !== 0);

      if (withLength && beValid) {
        val = compactAddLength(val);
      }

      // eslint-disable-next-line
      onChange &&
        onChange({
          isValid: beValid,
          value: asHex ? u8aToHex(val) : val,
        });

      setIsValid(beValid);
    },
    [asHex, length, onChange, validate, withLength]
  );

  return (
    <Bare className={className}>
      <Input
        className={size}
        defaultValue={defaultValue as string}
        isAction={!!children}
        isDisabled={isDisabled}
        isError={isError || !isValid}
        label={label}
        onChange={_onChange}
        onEnter={onEnter}
        onEscape={onEscape}
        placeholder={t<string>('0x prefixed hex, e.g. 0x1234 or ascii data')}
        type="text"
        withEllipsis
        withLabel={withLabel}
      >
        {children}
        {withCopy && <CopyButton value={defaultValue} />}
      </Input>
    </Bare>
  );
}
Example #28
Source File: Propose.tsx    From crust-apps with Apache License 2.0 5 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 [balance, setBalance] = useState<BN | undefined>();
  const [{ hash, isHashValid }, setHash] = useState<HashState>({ hash: '', isHashValid: false });
  const publicProps = useCall<unknown[]>(api.query.democracy.publicProps);

  const _onChangeHash = useCallback(
    (hash?: string): void => setHash({ hash, isHashValid: isHex(hash, 256) }),
    []
  );

  const hasMinLocked = balance?.gte(api.consts.democracy.minimumDeposit);

  return (
    <Modal
      className={className}
      header={t<string>('Submit proposal')}
      size='large'
    >
      <Modal.Content>
        <Modal.Columns hint={t<string>('The proposal will be registered from this account and the balance lock will be applied here.')}>
          <InputAddress
            help={t<string>('The account you want to register the proposal from')}
            label={t<string>('send from account')}
            labelExtra={
              <Available
                label={<span className='label'>{t<string>('transferrable')}</span>}
                params={accountId}
              />
            }
            onChange={setAccountId}
            type='account'
          />
        </Modal.Columns>
        <Modal.Columns hint={t<string>('The hash of the preimage for the proposal as previously submitted or intended.')}>
          <Input
            autoFocus
            help={t<string>('The preimage hash of the proposal')}
            label={t<string>('preimage hash')}
            onChange={_onChangeHash}
            value={hash}
          />
        </Modal.Columns>
        <Modal.Columns hint={t<string>('The associated deposit for this proposal should be more then the minimum on-chain deposit required. It will be locked until the proposal passes.')}>
          <InputBalance
            defaultValue={api.consts.democracy.minimumDeposit}
            help={t<string>('The locked value for this proposal')}
            isError={!hasMinLocked}
            label={t<string>('locked balance')}
            onChange={setBalance}
          />
          <InputBalance
            defaultValue={api.consts.democracy.minimumDeposit}
            help={t<string>('The minimum deposit required')}
            isDisabled
            label={t<string>('minimum deposit')}
          />
        </Modal.Columns>
      </Modal.Content>
      <Modal.Actions onCancel={onClose}>
        <TxButton
          accountId={accountId}
          icon='plus'
          isDisabled={!balance || !hasMinLocked || !isHashValid || !accountId || !publicProps}
          label={t<string>('Submit proposal')}
          onStart={onClose}
          params={
            api.tx.democracy.propose.meta.args.length === 3
              ? [hash, balance, publicProps?.length]
              : [hash, balance]
          }
          tx={api.tx.democracy.propose}
        />
      </Modal.Actions>
    </Modal>
  );
}
Example #29
Source File: Hash.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function Hash (): React.ReactElement {
  const { t } = useTranslation();
  const [{ data, hash, isHexData }, setState] = useState<State>({
    data: '',
    hash: blake2AsHex(stringToU8a(''), 256),
    isHexData: false
  });

  const _onChangeData = useCallback(
    (data: string): void => {
      const isHexData = isHex(data);

      setState({
        data,
        hash: blake2AsHex(
          isHexData
            ? hexToU8a(data)
            : stringToU8a(data),
          256
        ),
        isHexData
      });
    },
    []
  );

  return (
    <div className='toolbox--Hash'>
      <div className='ui--row'>
        <Input
          autoFocus
          className='full'
          help={t<string>('The input data to hash. This can be either specified as a hex value (0x-prefix) or as a string.')}
          label={t<string>('from the following data')}
          onChange={_onChangeData}
          value={data}
        />
      </div>
      <div className='ui--row'>
        <Static
          className='medium'
          help={t<string>('Detection on the input string to determine if it is hex or non-hex.')}
          label={t<string>('hex input data')}
          value={
            isHexData
              ? t<string>('Yes')
              : t<string>('No')
          }
        />
      </div>
      <div className='ui--row'>
        <Output
          className='full'
          help={t<string>('The blake2b 256-bit hash of the actual input data.')}
          isHidden={hash.length === 0}
          isMonospace
          label={t<string>('the resulting hash is')}
          value={hash}
          withCopy
        />
      </div>
    </div>
  );
}