How to use @polkadot/util - 10 common examples

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 / client / packages / client-db / src / Trie.spec.js View on Github external
// Copyright 2017-2018 @polkadot/client-db authors & contributors
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.

import toU8a from '@polkadot/util/u8a/toU8a';

import TrieDb from './Trie/Memory';

const EMPTY_ROOT = toU8a('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421');
const HELLO_ROOT = toU8a('0x0a915659b88f80bfa200570bd2767a6ab8cb0a4e44fd240cc5ed7a27728c4531');
const FOO_ROOT = toU8a('0xed4e32371288ee83be74f78fb492f01261b7c3dc9c422581bb705c4376492dc6');

describe('TrieDb', () => {
  let memory = new TrieDb();

  it('starts with the default root', () => {
    expect(
      memory.getRoot()
    ).toEqual(EMPTY_ROOT);
  });

  it('has the correct root after a single insertion', () => {
    memory.put(toU8a('hello'), toU8a('world'));

    expect(
github vue-polkadot / vue-ui / packages / vue-keyring / src / Keyring.ts View on Github external
private loadAddress(json: KeyringJson, key: string): void {
    const { isRecent, whenCreated = 0 } = json.meta;

    if (isRecent && (Date.now() - whenCreated) > RECENT_EXPIRY) {
      this._store.remove(key);
      return;
    }

    const address = this.encodeAddress(
      isHex(json.address)
        ? hexToU8a(json.address)
        // FIXME Just for the transition period (ignoreChecksum)
        : this.decodeAddress(json.address, true)
    );
    const [, hexAddr] = key.split(':');

    this.addresses.add(this._store, address, json);
    this.rewriteKey(json, key, hexAddr, addressKey);
  }
github polkadot-js / ui / packages / ui-keyring / src / Keyring.ts View on Github external
private loadAddress (json: KeyringJson, key: string): void {
    const { isRecent, whenCreated = 0 } = json.meta;

    if (isRecent && (Date.now() - whenCreated) > RECENT_EXPIRY) {
      this._store.remove(key);
      return;
    }

    const address = this.encodeAddress(
      isHex(json.address)
        ? hexToU8a(json.address)
        // FIXME Just for the transition period (ignoreChecksum)
        : this.decodeAddress(json.address, true)
    );
    const [, hexAddr] = key.split(':');

    this.addresses.add(this._store, address, json);
    this.rewriteKey(json, key, hexAddr, addressKey);
  }
github polkadot-js / ui / packages / ui-keyring / src / Keyring.ts View on Github external
private loadAddress (json: KeyringJson, key: string): void {
    const { isRecent, whenCreated = 0 } = json.meta;

    if (isRecent && (Date.now() - whenCreated) > RECENT_EXPIRY) {
      this._store.remove(key);
      return;
    }

    const address = this.encodeAddress(
      isHex(json.address)
        ? hexToU8a(json.address)
        // FIXME Just for the transition period (ignoreChecksum)
        : this.decodeAddress(json.address, true)
    );
    const [, hexAddr] = key.split(':');

    this.addresses.add(this._store, address, json);
    this.rewriteKey(json, key, hexAddr, addressKey);
  }
github vue-polkadot / vue-ui / packages / vue-keyring / src / Keyring.ts View on Github external
private loadAddress(json: KeyringJson, key: string): void {
    const { isRecent, whenCreated = 0 } = json.meta;

    if (isRecent && (Date.now() - whenCreated) > RECENT_EXPIRY) {
      this._store.remove(key);
      return;
    }

    const address = this.encodeAddress(
      isHex(json.address)
        ? hexToU8a(json.address)
        // FIXME Just for the transition period (ignoreChecksum)
        : this.decodeAddress(json.address, true)
    );
    const [, hexAddr] = key.split(':');

    this.addresses.add(this._store, address, json);
    this.rewriteKey(json, key, hexAddr, addressKey);
  }
github polkadot-js / common / packages / keyring / src / keyring.ts View on Github external
if (isHex(phrase, 256)) {
      seed = hexToU8a(phrase);
    } else {
      const str = phrase as string;
      const parts = str.split(' ');

      if ([12, 15, 18, 21, 24].includes(parts.length)) {
        // FIXME This keeps compat with older versions, but breaks compat with subkey
        // seed = type === 'sr25519'
        //   ? mnemonicToMiniSecret(phrase, password)
        //   : mnemonicToSeed(phrase, password);
        seed = mnemonicToMiniSecret(phrase, password);
      } else {
        assert(str.length <= 32, 'specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');

        seed = stringToU8a(str.padEnd(32));
      }
    }

    const keypair = type === 'sr25519'
      ? schnorrkelFromSeed(seed)
      : naclFromSeed(seed);
    const derived = keyFromPath(keypair, path, type);

    return createPair(type, derived, meta, null);
  }
github polkadot-js / client / packages / client-cli / src / index.ts View on Github external
// Copyright 2017-2019 @polkadot/client-cli authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

import { Config, ConfigKeys } from '@polkadot/client/types';

import wrtc from 'wrtc';
import Client from '@polkadot/client';
import { logger } from '@polkadot/util';

import getArgv from './argv';
import getExternalIp from './getExternalIp';
import keyToCamel from './keyToCamel';

const l = logger('client/cli');

function cli (params?: string): Config {
  const argv = getArgv(params);

  return Object
    .keys(argv)
    .reduce((config: any, key): Config => {
      if (/^(db|dev|p2p|rpc|signal|telemetry|wasm)-/.test(key)) {
        const section = key.substr(0, key.indexOf('-')) as ConfigKeys;
        const name = keyToCamel(key, 1);

        config[section] = config[section] || {};
        // ummm... no index, not Map-ing this one
        config[section][name] = (argv as any)[key];
      } else if (!/^(db|dev|p2p|rpc|signal|telemetry|wasm)[A-Z]/.test(key)) {
        const name = keyToCamel(key) as ConfigKeys;
github polkadot-js / api / packages / api / src / SubmittableExtrinsic.ts View on Github external
function getPrelimState (address: string, options: Partial): Observable<[Index, Header | null]> {
    return combineLatest([
      // if we have a nonce already, don't retrieve the latest, use what is there
      isUndefined(options.nonce)
        ? api.query.system.accountNonce(address)
        : of(createType('Index', options.nonce)),
      // if we have an era provided already or eraLength is <= 0 (immortal)
      // don't get the latest block, just pass null, handle in mergeMap
      (isUndefined(options.era) || (isNumber(options.era) && options.era > 0))
        ? api.rpc.chain.getHeader()
        : of(null)
    ]);
  }
github polkadot-js / api / packages / type-params / src / encode / type / index.ts View on Github external
return u8aConcat(
            bnToU8a(u8a.length, 32, true),
            u8a
          );
        })();

      case 'Timestamp':
        if (value instanceof Date) {
          value = Math.ceil(value.getTime() / 1000);
        }

        return bnToU8a(value, 64, true);

      case 'u128':
        return bnToU8a(value, 128, true);

      // TODO enums?
      case 'VoteThreshold':
        return bnToU8a(value || 0, 8, true);

      default:
        // tslint:disable-next-line
        (type as never);
        throw new Error(`No formatter for ${type}`);
    }
  } catch (error) {
    console.error('Failed encoding', type, 'with', value, error);

    throw error;
  }
}
github polkadot-js / api / packages / type-params / src / encode / type / index.ts View on Github external
);
        })();

      case 'Timestamp':
        if (value instanceof Date) {
          value = Math.ceil(value.getTime() / 1000);
        }

        return bnToU8a(value, 64, true);

      case 'u128':
        return bnToU8a(value, 128, true);

      // TODO enums?
      case 'VoteThreshold':
        return bnToU8a(value || 0, 8, true);

      default:
        // tslint:disable-next-line
        (type as never);
        throw new Error(`No formatter for ${type}`);
    }
  } catch (error) {
    console.error('Failed encoding', type, 'with', value, error);

    throw error;
  }
}