@polkadot/types/types#DefinitionRpcExt TypeScript Examples

The following examples show how to use @polkadot/types/types#DefinitionRpcExt. 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: method.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default function createOptions (api: ApiPromise, rpcs: Record<string, Record<string, DefinitionRpcExt>>, sectionName: string): DropdownOptions {
  const section = rpcs[sectionName];

  if (!section || Object.keys((api.rpc as Record<string, Record<string, unknown>>)[sectionName]).length === 0) {
    return [];
  }

  return Object
    .keys((api.rpc as Record<string, Record<string, unknown>>)[sectionName])
    .sort()
    .map((methodName) => section[methodName])
    .filter((ext): ext is DefinitionRpcExt => !!ext)
    .filter(({ isSubscription }) => !isSubscription)
    .map(({ description, method, params }): DropdownOption => {
      const inputs = params.map(({ name }) => name).join(', ');

      return {
        className: 'ui--DropdownLinked-Item',
        key: `${sectionName}_${method}`,
        text: [
          <div
            className='ui--DropdownLinked-Item-call'
            key={`${sectionName}_${method}:call`}
          >
            {method}({inputs})
          </div>,
          <div
            className='ui--DropdownLinked-Item-text'
            key={`${sectionName}_${method}:text`}
          >
            {description || method}
          </div>
        ],
        value: method
      };
    });
}
Example #2
Source File: rpcs.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
function toExt (section: string, input: Record<string, DefinitionRpc>): Record<string, DefinitionRpcExt> {
  return Object.entries(input).reduce((output: Record<string, DefinitionRpcExt>, [method, def]): Record<string, DefinitionRpcExt> => {
    output[method] = {
      isSubscription: false,
      jsonrpc: `${method}_${section}`,
      method,
      section,
      ...def
    };

    return output;
  }, {});
}
Example #3
Source File: rpcs.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export function getAllRpc (registry: Registry, chain: Text, { specName }: RuntimeVersion): Record<string, Record<string, DefinitionRpcExt>> {
  return Object
    .entries(getSpecRpc(registry, chain, specName))
    .reduce((all: Record<string, Record<string, DefinitionRpcExt>>, [section, contents]): Record<string, Record<string, DefinitionRpcExt>> => {
      all[section] ??= toExt(section, contents);

      return all;
    }, { ...jsonrpc });
}
Example #4
Source File: index.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
async function submitRpc (api: ApiPromise, { method, section }: DefinitionRpcExt, values: any[]): Promise<QueueTxResult> {
  try {
    const rpc = api.rpc as Record<string, Record<string, (...params: unknown[]) => Promise<unknown>>>;

    assert(isFunction(rpc[section] && rpc[section][method]), `api.rpc.${section}.${method} does not exist`);

    const result = await rpc[section][method](...values);

    console.log('submitRpc: result ::', loggerFormat(result));

    return {
      result,
      status: 'sent'
    };
  } catch (error) {
    console.error(error);

    return {
      error: error as Error,
      status: 'error'
    };
  }
}
Example #5
Source File: method.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export default function createOptions(
  api: ApiPromise,
  rpcs: Record<string, Record<string, DefinitionRpcExt>>,
  sectionName: string
): DropdownOptions {
  const section = rpcs[sectionName];

  if (!section || Object.keys((api.rpc as Record<string, Record<string, unknown>>)[sectionName]).length === 0) {
    return [];
  }

  return Object.keys((api.rpc as Record<string, Record<string, unknown>>)[sectionName])
    .sort()
    .map((methodName) => section[methodName])
    .filter((ext): ext is DefinitionRpcExt => !!ext)
    .filter(({ isSubscription }) => !isSubscription)
    .map(({ description, method, params }): DropdownOption => {
      const inputs = params.map(({ name }) => name).join(', ');

      return {
        className: 'ui--DropdownLinked-Item',
        key: `${sectionName}_${method}`,
        text: [
          <div className="ui--DropdownLinked-Item-call" key={`${sectionName}_${method}:call`}>
            {method}({inputs})
          </div>,
          <div className="ui--DropdownLinked-Item-text" key={`${sectionName}_${method}:text`}>
            {description || method}
          </div>,
        ],
        value: method,
      };
    });
}
Example #6
Source File: rpcs.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
function toExt(section: string, input: Record<string, DefinitionRpc>): Record<string, DefinitionRpcExt> {
  return Object.entries(input).reduce(
    (output: Record<string, DefinitionRpcExt>, [method, def]): Record<string, DefinitionRpcExt> => {
      output[method] = {
        isSubscription: false,
        jsonrpc: `${method}_${section}`,
        method,
        section,
        ...def,
      };

      return output;
    },
    {}
  );
}
Example #7
Source File: rpcs.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export function getAllRpc(
  registry: Registry,
  chain: Text,
  { specName }: RuntimeVersion
): Record<string, Record<string, DefinitionRpcExt>> {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  return Object.entries(getSpecRpc(registry, chain, specName)).reduce(
    (
      all: Record<string, Record<string, DefinitionRpcExt>>,
      [section, contents]
    ): Record<string, Record<string, DefinitionRpcExt>> => {
      all[section] = all[section] ?? toExt(section, contents);

      return all;
    },
    { ...jsonrpc }
  );
}
Example #8
Source File: index.tsx    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
async function submitRpc(
  api: ApiPromise,
  { method, section }: DefinitionRpcExt,
  values: any[]
): Promise<QueueTxResult> {
  try {
    const rpc = api.rpc as Record<string, Record<string, (...params: unknown[]) => Promise<unknown>>>;

    assert(isFunction(rpc[section] && rpc[section][method]), `api.rpc.${section}.${method} does not exist`);

    const result = await rpc[section][method](...values);

    return {
      result,
      status: 'sent',
    };
  } catch (error) {
    console.error(error);

    return {
      error: error as Error,
      status: 'error',
    };
  }
}
Example #9
Source File: Selection.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function Selection ({ queueRpc }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const [{ isValid, rpc, values }, setState] = useState<State>({
    isValid: false,
    rpc: defaultMethod,
    values: []
  });

  const params = useMemo(
    () => rpc.params.map(({ isOptional, name, type }): ParamDef => ({
      name,
      type: getTypeDef(isOptional ? `Option<${type}>` : type)
    })),
    [rpc]
  );

  const _nextState = useCallback(
    (newState: Partial<State>) => setState((prevState: State): State => {
      const { rpc = prevState.rpc, values = prevState.values } = newState;
      const reqCount = rpc.params.reduce((count, { isOptional }) => count + (isOptional ? 0 : 1), 0);
      const isValid = values.reduce((isValid, value) => isValid && value.isValid === true, reqCount <= values.length);

      return {
        isValid,
        rpc,
        values
      };
    }),
    []
  );

  const _onChangeMethod = useCallback(
    (rpc: DefinitionRpcExt) => _nextState({ rpc, values: [] }),
    [_nextState]
  );

  const _onChangeValues = useCallback(
    (values: RawParam[]) => _nextState({ values }),
    [_nextState]
  );

  const _onSubmit = useCallback(
    (): void => queueRpc({
      rpc,
      values: values
        .filter(({ value }) => !isNull(value))
        .map(({ value }): any => value)
    }),
    [queueRpc, rpc, values]
  );

  return (
    <section className='rpc--Selection'>
      <InputRpc
        defaultValue={defaultMethod}
        help={t<string>('The actual JSONRPC module and function to make a call to.')}
        label={t<string>('call the selected endpoint')}
        onChange={_onChangeMethod}
      />
      <Params
        key={`${rpc.section}.${rpc.method}:params` /* force re-render on change */}
        onChange={_onChangeValues}
        params={params}
      />
      <Button.Group>
        <Button
          icon='sign-in-alt'
          isDisabled={!isValid}
          label={t<string>('Submit RPC call')}
          onClick={_onSubmit}
        />
      </Button.Group>
    </section>
  );
}
Example #10
Source File: index.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function InputRpc ({ className = '', defaultValue, help, label, onChange, withLabel }: Props): React.ReactElement<Props> {
  const { api } = useApi();
  const rpcs = useRpcs();
  const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(() => methodOptions(api, rpcs, defaultValue.section));
  const [optionsSection] = useState<DropdownOptions>(() => sectionOptions(api));
  const [value, setValue] = useState<DefinitionRpcExt>((): DefinitionRpcExt => defaultValue);

  useEffect((): void => {
    onChange && onChange(value);
  }, [onChange, value]);

  const _onMethodChange = useCallback(
    (newValue: DefinitionRpcExt): void => {
      if (value.section === newValue.section && value.method === newValue.method) {
        return;
      }

      // set via callback since the method is a function itself
      setValue(() => newValue);
    },
    [value]
  );

  const _onSectionChange = useCallback(
    (section: string): void => {
      if (section === value.section) {
        return;
      }

      const optionsMethod = methodOptions(api, rpcs, section);

      setOptionsMethod(optionsMethod);
      _onMethodChange(rpcs[section][optionsMethod[0].value]);
    },
    [_onMethodChange, api, rpcs, value]
  );

  return (
    <LinkedWrapper
      className={className}
      help={help}
      label={label}
      withLabel={withLabel}
    >
      <SelectSection
        className='small'
        onChange={_onSectionChange}
        options={optionsSection}
        value={value}
      />
      <SelectMethod
        className='large'
        onChange={_onMethodChange}
        options={optionsMethod}
        value={value}
      />
    </LinkedWrapper>
  );
}
Example #11
Source File: useRpcs.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export default function useRpcs (): Record<string, Record<string, DefinitionRpcExt>> {
  const { api } = useApi();

  return useMemo(
    () => getAllRpc(api.registry, api.runtimeChain, api.runtimeVersion),
    [api]
  );
}
Example #12
Source File: index.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function InputRpc({
  className = '',
  defaultValue,
  help,
  label,
  onChange,
  withLabel,
}: Props): React.ReactElement<Props> {
  const { api } = useApi();
  const rpcs = useRpcs();
  const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(() =>
    methodOptions(api, rpcs, defaultValue.section)
  );
  const [optionsSection] = useState<DropdownOptions>(() => sectionOptions(api));
  const [value, setValue] = useState<DefinitionRpcExt>((): DefinitionRpcExt => defaultValue);

  useEffect((): void => {
    // eslint-disable-next-line
    onChange && onChange(value);
  }, [onChange, value]);

  const _onMethodChange = useCallback(
    (newValue: DefinitionRpcExt): void => {
      if (value.section === newValue.section && value.method === newValue.method) {
        return;
      }

      // set via callback since the method is a function itself
      setValue(() => newValue);
    },
    [value]
  );

  const _onSectionChange = useCallback(
    (section: string): void => {
      if (section === value.section) {
        return;
      }

      const result = methodOptions(api, rpcs, section);

      setOptionsMethod(result);
      _onMethodChange(rpcs[section][result[0].value]);
    },
    [_onMethodChange, api, rpcs, value]
  );

  return (
    <LinkedWrapper className={className} help={help} label={label} withLabel={withLabel}>
      <SelectSection className="small" onChange={_onSectionChange} options={optionsSection} value={value} />
      <SelectMethod className="large" onChange={_onMethodChange} options={optionsMethod} value={value} />
    </LinkedWrapper>
  );
}
Example #13
Source File: useRpcs.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export default function useRpcs(): Record<string, Record<string, DefinitionRpcExt>> {
  const { api } = useApi();

  return useMemo(() => getAllRpc(api.registry, api.runtimeChain, api.runtimeVersion), [api]);
}