@polkadot/util#isString TypeScript Examples

The following examples show how to use @polkadot/util#isString. 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: ProposedAction.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function ProposedAction ({ className = '', expandNested, idNumber, proposal, withLinks }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const stringId = isString(idNumber)
    ? idNumber
    : formatNumber(idNumber);

  if (!proposal) {
    return (
      <h3>#{stringId}&nbsp;{t<string>('No execution details available for this proposal')}</h3>
    );
  }

  const { meta, method, section } = proposal.registry.findMetaCall(proposal.callIndex);

  const header = `#${stringId}: ${section}.${method}`;

  return (
    <div className={`ui--ProposedAction ${className}`}>
      <h3>{header}</h3>
      <Expander summaryMeta={meta}>
        {(isTreasuryProposalVote(proposal) && expandNested)
          ? (
            <TreasuryProposal
              asInset={withLinks}
              insetProps={{
                withBottomMargin: true,
                withTopMargin: true,
                ...(withLinks ? { href: '/treasury' } : {})
              }}
              proposalId={proposal.args[0].toString()}
            />
          )
          : <Call value={proposal} />
        }
      </Expander>
    </div>
  );
}
Example #2
Source File: Body.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function Body ({ children, className = '', empty, emptySpinner }: Props): React.ReactElement<Props> {
  return (
    <tbody className={className}>
      {children || (
        <tr><td colSpan={100}>{
          isString(empty)
            ? <div className='empty'>{empty}</div>
            : empty || <Spinner label={emptySpinner} />
        }</td></tr>
      )}
    </tbody>
  );
}
Example #3
Source File: useEventTrigger.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export function useEventTrigger (checks: EventCheck[]): string {
  const { api } = useApi();
  const [trigger, setTrigger] = useState('0x00');
  const mountedRef = useIsMountedRef();
  const eventRecords = useCall<Vec<EventRecord>>(api.query.system.events);

  useEffect((): void => {
    mountedRef.current && eventRecords && eventRecords.filter(({ event }) =>
      event && checks.some((check) => check && (
        isString(check)
          ? event.section === check
          : check.is(event)
      ))
    ).length && setTrigger(() => eventRecords.createdAtHash?.toHex() || '0x00');
  }, [eventRecords, checks, mountedRef]);

  return trigger;
}
Example #4
Source File: useExtrinsicTrigger.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export function useExtrinsicTrigger (checks: ExtrinsicCheck[]): string {
  const { api } = useApi();
  const [trigger, setTrigger] = useState('0x00');
  const mountedRef = useIsMountedRef();
  const block = useCall<SignedBlockExtended>(api.derive.chain.subscribeNewBlocks);

  useEffect((): void => {
    mountedRef.current && block && block.extrinsics && block.extrinsics.filter(({ extrinsic }) =>
      extrinsic && checks.some((check) => check && (
        isString(check)
          ? extrinsic.method.section === check
          : check.is(extrinsic)
      ))
    ).length && setTrigger(() => block.createdAtHash?.toHex() || '0x00');
  }, [block, checks, mountedRef]);

  return trigger;
}
Example #5
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 #6
Source File: Body.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function Body({ children, className = '', empty, emptySpinner, noBodyTag }: Props): React.ReactElement<Props> {
  return children ? (
    noBodyTag ? (
      <>{children}</>
    ) : (
      <tbody className={className}>{children}</tbody>
    )
  ) : (
    <tbody className={className}>
      <tr>
        <td colSpan={100}>
          {isString(empty) ? <div className="empty">{empty}</div> : empty || <Spinner label={emptySpinner} />}
        </td>
      </tr>
    </tbody>
  );
}
Example #7
Source File: Filtering.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function Filtering ({ children, className, nameFilter, setNameFilter, setWithCollateral, withCollateral }: Props): React.ReactElement<Props> | null {
  const { t } = useTranslation();
  const { api } = useApi();

  // on load, parse the query string and extract the filter
  useEffect((): void => {
    const queryFilter = queryString.parse(location.href.split('?')[1]).filter;

    if (isString(queryFilter)) {
      setNameFilter(queryFilter, true);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const _setNameFilter = useCallback(
    (value: string) => setNameFilter(value, false),
    [setNameFilter]
  );

  return (
    <div className={className}>
      <Input
        autoFocus
        isFull
        label={t<string>('filter by name, address or index')}
        onChange={_setNameFilter}
        value={nameFilter}
      />
      <div className='market--filter--optionsBar'>
        {children}
        {api.query.identity && (
          <Toggle
            className='market--filter--buttonToggle'
            label={t<string>('Only accounts with collateral')}
            onChange={setWithCollateral}
            value={withCollateral}
          />
        )}
      </div>
    </div>
  );
}
Example #8
Source File: Filtering.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function Filtering ({ children, className, nameFilter, setNameFilter, setWithIdentity, withIdentity }: Props): React.ReactElement<Props> | null {
  const { t } = useTranslation();
  const { api } = useApi();

  // on load, parse the query string and extract the filter
  useEffect((): void => {
    const queryFilter = queryString.parse(location.href.split('?')[1]).filter;

    if (isString(queryFilter)) {
      setNameFilter(queryFilter, true);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const _setNameFilter = useCallback(
    (value: string) => setNameFilter(value, false),
    [setNameFilter]
  );

  return (
    <div className={className}>
      <Input
        autoFocus
        isFull
        label={t<string>('filter by name, address or index')}
        onChange={_setNameFilter}
        value={nameFilter}
      />
      <div className='staking--optionsBar'>
        {children}
        {api.query.identity && (
          <Toggle
            className='staking--buttonToggle'
            label={t<string>('only with an identity')}
            onChange={setWithIdentity}
            value={withIdentity}
          />
        )}
      </div>
    </div>
  );
}
Example #9
Source File: Keyring.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
static fromJson(keypairJson: KeyringPair$Json | string, passphrase?: string): KeyringPair {
    const json: KeyringPair$Json = isString(keypairJson) ? JSON.parse(keypairJson) : keypairJson;
    const keyring = new Keyring().addFromJson(json);
    return GearKeyring.unlock(keyring, passphrase);
  }
Example #10
Source File: ProposedAction.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function ProposedAction({
  className = '',
  expandNested,
  idNumber,
  proposal,
  withLinks,
}: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const stringId = isString(idNumber) ? idNumber : formatNumber(idNumber);

  if (!proposal) {
    return (
      <h3>
        #{stringId}&nbsp;{t<string>('No execution details available for this proposal')}
      </h3>
    );
  }

  const { meta, method, section } = proposal.registry.findMetaCall(proposal.callIndex);

  const header = `#${stringId}: ${section}.${method}`;

  return (
    <div className={`ui--ProposedAction ${className}`}>
      <h3>{header}</h3>
      <Expander summaryMeta={meta}>
        {isTreasuryProposalVote(proposal) && expandNested ? (
          <TreasuryProposal
            asInset={withLinks}
            insetProps={{
              withBottomMargin: true,
              withTopMargin: true,
              ...(withLinks ? { href: '/treasury' } : {}),
            }}
            proposalId={proposal.args[0].toString()}
          />
        ) : (
          <Call value={proposal} />
        )}
      </Expander>
    </div>
  );
}
Example #11
Source File: useApiUrl.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export function useApiUrl(url?: string | string[]): ApiPromise | null {
  const apiRef = useRef<ApiPromise | null>(null);
  const mountedRef = useIsMountedRef();
  const [state, setState] = useState<ApiPromise | null>(null);

  useEffect((): (() => void) => {
    return (): void => {
      disconnect(apiRef.current);
      apiRef.current = null;
    };
  }, []);

  const _setApi = useCallback(
    (api: ApiPromise | null): void => {
      disconnect(apiRef.current);

      if (mountedRef.current) {
        apiRef.current = api;
        setState(api);
      }
    },
    [mountedRef]
  );

  useEffect((): void => {
    _setApi(null);

    // eslint-disable-next-line
    url &&
      (isString(url) || url.length) &&
      ApiPromise.create({
        provider: new WsProvider(url),
        // typesBundle,
        typesChain,
      })
        .then(_setApi)
        .catch(console.error);
  }, [_setApi, url]);

  return state;
}
Example #12
Source File: DayItem.tsx    From crust-apps with Apache License 2.0 4 votes vote down vote up
function DayItem ({ className, item: { date, info, type }, showAllEvents }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();

  const [description, setDescription] = useState<string>('');

  const _exportCal = useCallback(
    () => exportCalendar(date, description),
    [description, date]
  );

  const desc = useMemo(
    (): React.ReactNode => {
      const id: string | null = info && (
        isString(info)
          ? info
          : formatNumber(info)
      );
      const typeLink = ['councilElection'].includes(type)
        ? <div className='itemLink'><a href='#/council'>{t<string>('via Council')}</a></div>
        : ['councilMotion'].includes(type)
          ? <div className='itemLink'><a href='#/council/motions'>{t<string>('via Council/Motions')}</a></div>
          : ['democracyDispatch', 'scheduler'].includes(type)
            ? <div className='itemLink'><a href='#/democracy/dispatch'>{t<string>('via Democracy/Dispatch')}</a></div>
            : ['democracyLaunch', 'referendumDispatch', 'referendumVote'].includes(type)
              ? <div className='itemLink'><a href='#/democracy'>{t<string>('via Democracy')}</a></div>
              : ['societyChallenge', 'societyRotate'].includes(type)
                ? <div className='itemLink'><a href='#/society'>{t<string>('via Society')}</a></div>
                : ['stakingEpoch', 'stakingEra'].includes(type)
                  ? <div className='itemLink'><a href='#/staking'>{t<string>('via Staking')}</a></div>
                  : ['stakingSlash'].includes(type)
                    ? <div className='itemLink'><a href='#/staking/slashes'>{t<string>('via Staking/Slashed')}</a></div>
                    : ['treasurySpend'].includes(type)
                      ? <div className='itemLink'><a href='#/treasury'>{t<string>('via Treasury')}</a></div>
                      : undefined;
      let s = '';

      switch (type) {
        case 'councilElection':
          s = t<string>('Election of new council candidates');
          break;

        case 'councilMotion':
          s = t<string>('Voting ends on council motion {{id}}', { replace: { id } });
          break;

        case 'democracyDispatch':
          s = t<string>('Enactment of the result of referendum {{id}}', { replace: { id } });
          break;

        case 'democracyLaunch':
          s = t<string>('Start of the next referendum voting period');
          break;

        case 'referendumDispatch':
          s = t<string>('Potential dispatch of referendum {{id}} (if passed)', { replace: { id } });
          break;

        case 'referendumVote':
          s = t<string>('Voting ends for referendum {{id}}', { replace: { id } });
          break;

        case 'scheduler':
          s = id
            ? t<string>('Execute named scheduled task {{id}}', { replace: { id } })
            : t<string>('Execute anonymous scheduled task');
          break;

        case 'stakingEpoch':
          s = t<string>('Start of a new staking session {{id}}', { replace: { id } });
          break;

        case 'stakingEra':
          s = t<string>('Start of a new staking era {{id}}', { replace: { id } });
          break;

        case 'stakingSlash':
          s = t<string>('Application of slashes from era {{id}}', { replace: { id } });
          break;

        case 'treasurySpend':
          s = t<string>('Start of next spending period');
          break;

        case 'societyChallenge':
          s = t<string>('Start of next membership challenge period');
          break;

        case 'societyRotate':
          s = t<string>('Acceptance of new members and bids');
          break;

        default:
          return assertUnreachable(type);
      }

      setDescription(s);

      return (<><div className='itemDesc'>{s}</div>{typeLink}</>);
    },
    [info, t, type]
  );

  return (
    <div className={className}>
      {showAllEvents &&
        <div className='itemDate'>{date.toLocaleString(undefined, FORMAT_OPTIONS)}</div>
      }
      <div className='itemTime'>{date.toLocaleTimeString().split(':').slice(0, 2).join(':')}</div>
      {desc}
      {date && (
        <Button
          className={showAllEvents ? 'exportCal exportCal-allEvents' : 'exportCal'}
          icon='calendar-plus'
          onClick={_exportCal}
        />
      )}
    </div>
  );
}