How to use the @polkadot/util.assert function in @polkadot/util

To help you get started, we’ve selected a few @polkadot/util examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github polkadot-js / api / packages / api / src / promise / Api.ts View on Github external
function extractArgs (args: any[], needsCallback: boolean): [any[], Callback | undefined] {
  let callback: Callback | undefined;
  const actualArgs = args.slice();

  // If the last arg is a function, we pop it, put it into callback.
  // actualArgs will then hold the actual arguments to be passed to `method`
  if (args.length && isFunction(args[args.length - 1])) {
    callback = actualArgs.pop();
  }

  // When we need a subscription, ensure that a valid callback is actually passed
  assert(!needsCallback || isFunction(callback), 'Expected a callback to be passed with subscriptions');

  return [actualArgs, callback];
}
github polkadot-js / api / packages / api-observable / src / Combined.ts View on Github external
accountIdAndIndex = (address?: AccountId | AccountIndex | string | null): Observable<[AccountId | undefined, AccountIndex | undefined]> => {
    try {
      // yes, this can fail, don't care too much, catch will catch it
      const length = decodeAddress((address as any).toString()).length;

      assert([1, 2, 4, 8, 32].indexOf(length) !== -1, `Invalid length for decoded address, found ${length}`);

      if (length === 32) {
        const accountId = new AccountId(address as string);

        return this
          .accountIndexFromId(accountId)
          .pipe(
            map((accountIndex?: AccountIndex): [AccountId, AccountIndex | undefined] =>
              [accountId, accountIndex]
            )
          );
      }

      const accountIndex = new AccountIndex(address as string);

      return this
github polkadot-js / apps / packages / ui-api / src / with / call.tsx View on Github external
if (endpoint === 'subscribe') {
          const [fn, ...params] = newParams;

          return [
            fn,
            params,
            true
          ];
        }

        const [area, section, method, ...others] = endpoint.split('.');

        assert(area.length &amp;&amp; section.length &amp;&amp; method.length &amp;&amp; others.length === 0, `Invalid API format, expected <area>.<section>., found ${endpoint}`);
        assert(['rpc', 'query', 'derive'].includes(area), `Unknown api.${area}, expected rpc, query or derive`);
        assert(!at || area === 'query', 'Only able todo an at query on the api.query interface');

        const apiSection = (api as any)[area][section];

        assert(apiSection &amp;&amp; apiSection[method], `Unable to find api.${area}.${section}.${method}`);

        const meta = apiSection[method].meta;

        if (area === 'query' &amp;&amp; meta &amp;&amp; meta.type.isMap) {
          const arg = newParams[0];

          assert(!isUndefined(arg) &amp;&amp; !isNull(arg), `${meta.name} expects one argument`);
        }

        return [
          apiSection[method],
          newParams,</section>
github polkadot-js / api / packages / api-contract / src / MetaRegistry.ts View on Github external
function detectedType ({ def, id }: MetaType): MetaTypeInfo {
  assert(!(def as MetaTypeDefUnion)['union.fields'], 'Invalid union type definition found');

  const lookup = def === 'builtin'
    ? builtinMap.find(([test]): boolean => test(id))
    : typeMap.find(([test]): boolean => !!(def as any)[test]);

  return lookup
    ? lookup[1]
    : MetaTypeInfo.Null;
}
github polkadot-js / api / packages / types / src / codec / create / getTypeClass.ts View on Github external
function getSubDef (value: TypeDef): TypeDef {
  assert(value.sub && !Array.isArray(value.sub), `Expected subtype as TypeDef in ${JSON.stringify(value)}`);

  return value.sub;
}
github polkadot-js / api / packages / types / src / rpc / ExtrinsicStatus.ts View on Github external
public get asReady (): Null {
    assert(this.isReady, `Cannot convert '${this.type}' via asReady`);

    return this.value as Null;
  }
github polkadot-js / api / packages / types / src / codec / Enum.ts View on Github external
function createFromValue (registry: Registry, def: TypesDef, index = 0, value?: any): Decoded {
  const Clazz = Object.values(def)[index];

  assert(!isUndefined(Clazz), `Unable to create Enum via index ${index}, in ${Object.keys(def).join(', ')}`);

  return {
    index,
    value: new Clazz(registry, value)
  };
}
github polkadot-js / api / packages / api-contract / src / MetaRegistry.ts View on Github external
protected itemAt (index: number, variant: MetaRegistryItem): any {
    assert(this.hasItemAt(index, variant), `MetaRegistry: Invalid ${variant} index ${index} found in metadata`);

    switch (variant) {
      case MetaRegistryItem.String:
        return this._strings[index - 1];
      case MetaRegistryItem.Type:
        return this._types[index - 1];
      case MetaRegistryItem.TypeDef:
        return this.typeDefs[index - 1];
    }
  }
github polkadot-js / api / packages / api-contract / src / MetaRegistry.ts View on Github external
private typeDefForBuiltinVec (id: MetaTypeIdVec, typeIndex?: TypeIndex): Pick {
    const { 'slice.type': vecTypeIndex } = id;

    assert(!typeIndex || vecTypeIndex !== typeIndex, `MetaRegistry: self-referencing registry type at index ${typeIndex}`);

    const type = displayType(this.typeDefFromMetaTypeAt(vecTypeIndex));
    assert(type &amp;&amp; type.length &gt; 0, `MetaRegistry: Invalid builtin Vec type found at index ${typeIndex}`);

    return {
      info: TypeDefInfo.Vec,
      type: `Vec&lt;${type}&gt;`,
      sub: this.typeDefFromMetaTypeAt(vecTypeIndex)
    };
  }
github polkadot-js / api / packages / api-contract / src / validation.ts View on Github external
export function validateArgs (name: string, args: ContractABIArg[]): void {
  assert(Array.isArray(args), `Expected 'args' to exist on ${name}`);

  args.forEach((arg): void => {
    const unknownKeys = Object.keys(arg).filter((key): boolean => !['name', 'type'].includes(key));

    assert(unknownKeys.length === 0, `Unknown keys ${unknownKeys.join(', ')} found in ABI args for ${name}`);
    assert(isString(arg.name), `${name} args should have valid name `);
    assert(isString(arg.type) || isObject(arg.type), `${name} args should have valid type`);
  });
}