@polkadot/types/types#TypeDef TypeScript Examples

The following examples show how to use @polkadot/types/types#TypeDef. 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: Logs.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function formatStruct (struct: Struct): React.ReactNode {
  const params = Object.entries(struct.Type).map(([name, value]): { name: string; type: TypeDef } => ({
    name,
    type: getTypeDef(value)
  }));
  const values = struct.toArray().map((value): { isValid: boolean; value: Codec } => ({
    isValid: true,
    value
  }));

  return (
    <Params
      isDisabled
      params={params}
      values={values}
    />
  );
}
Example #2
Source File: Logs.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function formatTuple (tuple: Tuple): React.ReactNode {
  const params = tuple.Types.map((type): { type: TypeDef } => ({
    type: getTypeDef(type)
  }));
  const values = tuple.toArray().map((value): { isValid: boolean; value: Codec } => ({
    isValid: true,
    value
  }));

  return (
    <Params
      isDisabled
      params={params}
      values={values}
    />
  );
}
Example #3
Source File: Logs.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function formatVector (vector: Vec<Codec>): React.ReactNode {
  const type = getTypeDef(vector.Type);
  const values = vector.toArray().map((value): { isValid: boolean; value: Codec } => ({
    isValid: true,
    value
  }));
  const params = values.map((_, index): { name: string; type: TypeDef } => ({
    name: `${index}`,
    type
  }));

  return (
    <Params
      isDisabled
      params={params}
      values={values}
    />
  );
}
Example #4
Source File: Justifications.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function formatTuple (tuple: Tuple): React.ReactNode {
  const params = tuple.Types.map((type): { type: TypeDef } => ({
    type: getTypeDef(type)
  }));
  const values = tuple.toArray().map((value): { isValid: boolean; value: Codec } => ({
    isValid: true,
    value
  }));

  return (
    <Params
      isDisabled
      params={params}
      values={values}
    />
  );
}
Example #5
Source File: Option.tsx    From crust-apps with Apache License 2.0 6 votes vote down vote up
function Option ({ className = '', defaultValue, isDisabled, name, onChange, onEnter, onEscape, registry, type: { sub, withOptionActive } }: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const [isActive, setIsActive] = useState(withOptionActive || false);

  useEffect((): void => {
    !isActive && onChange && onChange({
      isValid: true,
      value: null
    });
  }, [isActive, onChange]);

  return (
    <div className={className}>
      <Param
        defaultValue={defaultValue}
        isDisabled={isDisabled || !isActive}
        isInOption
        isOptional={!isActive && !isDisabled}
        name={name}
        onChange={onChange}
        onEnter={onEnter}
        onEscape={onEscape}
        registry={registry}
        type={sub as TypeDef}
      />
      {!isDisabled && (
        <Toggle
          isOverlay
          label={t<string>('include option')}
          onChange={setIsActive}
          value={isActive}
        />
      )}
    </div>
  );
}
Example #6
Source File: useParamDefs.ts    From subscan-multisig-react with Apache License 2.0 6 votes vote down vote up
export default function useParamDefs(registry: Registry, type: TypeDef): ParamDef[] {
  const [params, setParams] = useState<ParamDef[]>([]);

  useEffect((): void => {
    const typeDef = expandDef(registry, type);

    if (!typeDef.sub) {
      return setParams([]);
    }

    setParams(
      (Array.isArray(typeDef.sub) ? typeDef.sub : [typeDef.sub]).map(
        (td): ParamDef => ({
          length: typeDef.length,
          name: td.name,
          type: td, // expandDef(td)
        })
      )
    );
  }, [registry, type]);

  return params;
}
Example #7
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 #8
Source File: useParamDefs.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
function expandDef (registry: Registry, td: TypeDef): TypeDef {
  try {
    return getTypeDef(
      registry.createType(td.type as 'u32').toRawType()
    );
  } catch (e) {
    return td;
  }
}
Example #9
Source File: useParamDefs.ts    From crust-apps with Apache License 2.0 6 votes vote down vote up
export default function useParamDefs (registry: Registry, type: TypeDef): ParamDef[] {
  const [params, setParams] = useState<ParamDef[]>([]);

  useEffect((): void => {
    const typeDef = expandDef(registry, type);

    if (!typeDef.sub) {
      return setParams([]);
    }

    setParams(
      (Array.isArray(typeDef.sub) ? typeDef.sub : [typeDef.sub]).map((td): ParamDef => ({
        length: typeDef.length,
        name: td.name,
        type: td // expandDef(td)
      }))
    );
  }, [registry, type]);

  return params;
}
Example #10
Source File: values.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export default function createValues(registry: Registry, params: { type: TypeDef }[]): RawParam[] {
  return params.map((param) => createValue(registry, param));
}
Example #11
Source File: values.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
export function createValue(registry: Registry, param: { type: TypeDef }): RawParam {
  const value = getInitValue(registry, param.type);

  return {
    isValid: !isUndefined(value),
    value,
  };
}
Example #12
Source File: useParamDefs.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function expandDef(registry: Registry, td: TypeDef): TypeDef {
  try {
    return getTypeDef(registry.createType(td.type as 'u32').toRawType());
  } catch (e) {
    return td;
  }
}
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: findComponent.ts    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
// eslint-disable-next-line complexity
function fromDef({ displayName, info, sub, type }: TypeDef): string {
  if (displayName && SPECIAL_TYPES.includes(displayName)) {
    return displayName;
  }

  switch (info) {
    case TypeDefInfo.Compact:
      return (sub as TypeDef).type;

    case TypeDefInfo.Option:
      return 'Option';

    case TypeDefInfo.Enum:
      return 'Enum';

    case TypeDefInfo.Struct:
      return 'Struct';

    case TypeDefInfo.Tuple:
      if (components[type] === Account) {
        return type;
      }

      return 'Tuple';

    case TypeDefInfo.Vec:
      if (type === 'Vec<u8>') {
        return 'Bytes';
      }

      return ['Vec<KeyValue>'].includes(type) ? 'Vec<KeyValue>' : 'Vec';

    case TypeDefInfo.VecFixed:
      if ((sub as TypeDef).type === 'u8') {
        return type;
      }

      return 'VecFixed';

    default:
      return type;
  }
}
Example #15
Source File: Option.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function Option({
  className = '',
  defaultValue,
  isDisabled,
  name,
  onChange,
  onEnter,
  onEscape,
  registry,
  type: { sub, withOptionActive },
}: Props): React.ReactElement<Props> {
  const { t } = useTranslation();
  const [isActive, setIsActive] = useState(withOptionActive || false);

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

  return (
    <div className={className}>
      <Param
        defaultValue={defaultValue}
        isDisabled={isDisabled || !isActive}
        isInOption
        isOptional={!isActive && !isDisabled}
        name={name}
        onChange={onChange}
        onEnter={onEnter}
        onEscape={onEscape}
        registry={registry}
        type={sub as TypeDef}
      />
      {!isDisabled && <Toggle isOverlay label={t<string>('include option')} onChange={setIsActive} value={isActive} />}
    </div>
  );
}
Example #16
Source File: Extrinsic.tsx    From subscan-multisig-react with Apache License 2.0 5 votes vote down vote up
function getParams({ meta }: SubmittableExtrinsicFunction<'promise'>): { name: string; type: TypeDef }[] {
  return meta.args.map((arg): { name: string; type: TypeDef } => ({
    name: arg.name.toString(),
    type: getTypeDef(arg.type.toString()),
  }));
}
Example #17
Source File: values.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export default function createValues (registry: Registry, params: { type: TypeDef }[]): RawParam[] {
  return params.map((param) => createValue(registry, param));
}
Example #18
Source File: values.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
export function createValue (registry: Registry, param: { type: TypeDef }): RawParam {
  const value = getInitValue(registry, param.type);

  return {
    isValid: !isUndefined(value),
    value
  };
}
Example #19
Source File: findComponent.ts    From crust-apps with Apache License 2.0 5 votes vote down vote up
function fromDef ({ displayName, info, sub, type }: TypeDef): string {
  if (displayName && SPECIAL_TYPES.includes(displayName)) {
    return displayName;
  }

  switch (info) {
    case TypeDefInfo.Compact:
      return (sub as TypeDef).type;

    case TypeDefInfo.Option:
      return 'Option';

    case TypeDefInfo.Enum:
      return 'Enum';

    case TypeDefInfo.Struct:
      return 'Struct';

    case TypeDefInfo.Tuple:
      if (components[type] === Account) {
        return type;
      }

      return 'Tuple';

    case TypeDefInfo.Vec:
      if (type === 'Vec<u8>') {
        return 'Bytes';
      }

      return ['Vec<KeyValue>'].includes(type)
        ? 'Vec<KeyValue>'
        : 'Vec';

    case TypeDefInfo.VecFixed:
      if ((sub as TypeDef).type === 'u8') {
        return type;
      }

      return 'VecFixed';

    default:
      return type;
  }
}
Example #20
Source File: Extrinsic.tsx    From crust-apps with Apache License 2.0 5 votes vote down vote up
function getParams ({ meta }: SubmittableExtrinsicFunction<'promise'>): { name: string; type: TypeDef }[] {
  return GenericCall.filterOrigin(meta).map((arg): { name: string; type: TypeDef } => ({
    name: arg.name.toString(),
    type: getTypeDef(arg.type.toString())
  }));
}
Example #21
Source File: Enum.tsx    From subscan-multisig-react with Apache License 2.0 4 votes vote down vote up
function EnumParam(props: Props): React.ReactElement<Props> {
  const {
    className = '',
    defaultValue,
    isDisabled,
    isError,
    label,
    onChange,
    overrides,
    registry,
    type,
    withLabel,
  } = props;
  const [current, setCurrent] = useState<ParamDef[] | null>(null);
  const [initialValue, setInitialValue] = useState<string | null>(null);
  const [{ options, subTypes }, setOptions] = useState<Options>({ options: [], subTypes: [] });

  useEffect((): void => {
    const rawType = registry.createType(type.type as 'u32').toRawType();
    const typeDef = getTypeDef(rawType);
    const subType = typeDef.sub as TypeDef[];

    setOptions({
      options: subType.map(
        ({ name }): Option => ({
          text: name,
          value: name,
        })
      ),
      subTypes: subType,
    });
    setCurrent([{ name: subType[0].name, type: subType[0] }]);
  }, [registry, type]);

  useEffect((): void => {
    setInitialValue(
      defaultValue && defaultValue.value
        ? defaultValue.value instanceof Enum
          ? defaultValue.value.type
          : Object.keys(defaultValue.value as Record<string, unknown>)[0]
        : null
    );
  }, [defaultValue]);

  const _onChange = useCallback(
    (value: string): void => {
      const newType = subTypes.find(({ name }): boolean => name === value) || null;

      setCurrent(newType ? [{ name: newType.name, type: newType }] : null);
    },
    [subTypes]
  );

  const _onChangeParam = useCallback(
    ([{ isValid, value }]: RawParam[]): void => {
      // eslint-disable-next-line
      current &&
        onChange &&
        onChange({
          isValid,
          value: { [current[0].name as string]: value },
        });
    },
    [current, onChange]
  );

  if (isDisabled) {
    return <Static {...props} />;
  }

  return (
    <Bare className={className}>
      <Dropdown
        className="full"
        defaultValue={initialValue}
        isDisabled={isDisabled}
        isError={isError}
        label={label}
        onChange={_onChange}
        options={options}
        withEllipsis
        withLabel={withLabel}
      />
      {current && <Params onChange={_onChangeParam} overrides={overrides} params={current} registry={registry} />}
    </Bare>
  );
}
Example #22
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 #23
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';
    }
  }
}
Example #24
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 #25
Source File: Enum.tsx    From crust-apps with Apache License 2.0 4 votes vote down vote up
function EnumParam (props: Props): React.ReactElement<Props> {
  const { className = '', defaultValue, isDisabled, isError, label, onChange, overrides, registry, type, withLabel } = props;
  const [current, setCurrent] = useState<ParamDef[] | null>(null);
  const [initialValue, setInitialValue] = useState<string | null>(null);
  const [{ options, subTypes }, setOptions] = useState<Options>({ options: [], subTypes: [] });

  useEffect((): void => {
    const rawType = registry.createType(type.type as 'u32').toRawType();
    const typeDef = getTypeDef(rawType);
    const subTypes = typeDef.sub as TypeDef[];

    setOptions({
      options: subTypes.map(({ name }): Option => ({
        text: name,
        value: name
      })),
      subTypes
    });
    setCurrent([{ name: subTypes[0].name, type: subTypes[0] }]);
  }, [registry, type]);

  useEffect((): void => {
    setInitialValue(
      defaultValue && defaultValue.value
        ? defaultValue.value instanceof Enum
          ? defaultValue.value.type
          : Object.keys(defaultValue.value as Record<string, unknown>)[0]
        : null
    );
  }, [defaultValue]);

  const _onChange = useCallback(
    (value: string): void => {
      const newType = subTypes.find(({ name }): boolean => name === value) || null;

      setCurrent(
        newType
          ? [{ name: newType.name, type: newType }]
          : null
      );
    },
    [subTypes]
  );

  const _onChangeParam = useCallback(
    ([{ isValid, value }]: RawParam[]): void => {
      current && onChange && onChange({
        isValid,
        value: { [current[0].name as string]: value }
      });
    },
    [current, onChange]
  );

  if (isDisabled) {
    return <Static {...props} />;
  }

  return (
    <Bare className={className}>
      <Dropdown
        className='full'
        defaultValue={initialValue}
        isDisabled={isDisabled}
        isError={isError}
        label={label}
        onChange={_onChange}
        options={options}
        withEllipsis
        withLabel={withLabel}
      />
      {current && (
        <Params
          onChange={_onChangeParam}
          overrides={overrides}
          params={current}
          registry={registry}
        />
      )}
    </Bare>
  );
}