How to use @polkadot/types - 10 common examples

To help you get started, we’ve selected a few @polkadot/types 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-derive / src / balances / all.ts View on Github external
switchMap(({ accountId }): Observable =>
        (accountId
          ? combineLatest([
            of(accountId),
            api.derive.chain.bestNumber(),
            queryBalances(api, accountId),
            // FIXME This is having issues with Kusama, only use accountNonce atm
            // api.rpc.account && api.rpc.account.nextIndex
            //   ? api.rpc.account.nextIndex(accountId)
            //   // otherwise we end up with this: type 'Codec | Index' is not assignable to type 'Index'.
            //   : api.query.system.accountNonce(accountId)
            api.query.system.accountNonce(accountId)
          ])
          : of([createType(api.registry, 'AccountId'), createType(api.registry, 'BlockNumber'), [createType(api.registry, 'Balance'), createType(api.registry, 'Balance'), createType(api.registry, 'Vec'), createType(api.registry, 'Option', null)], createType(api.registry, 'Index')])
        )
      ),
github polkadot-js / api / docs / examples / promise / 07_make_transfer_with_allowed_block_permissions_only / index.js View on Github external
const alice = keyring.addFromUri('//Alice');

  // Get nonce for account
  const nonce = await api.query.system.accountNonce(alice.address);

  // Get current block
  const signedBlock = await api.rpc.chain.getBlock();

  // Get current block height and hash
  const currentHeight = signedBlock.block.header.number;
  const blockHash = signedBlock.block.header.hash;

  // NOTE By default the API will send mortal transactions, only explicitly construct
  // if you wish to override the defaults
  // construct a mortal era
  const era = createType('ExtrinsicEra', { current: currentHeight, period: 10 });

  // Create an extrinsic, transferring 12345 units to Bob
  const transfer = api.tx.balances.transfer(BOB, 12345);

  // Sign and send the transaction using our account with a nonce and the length of blocks the transaction is valid for
  const hash = await transfer.signAndSend(alice, { blockHash, era, nonce });

  console.log('Transfer sent with hash', hash.toHex());
}
github polkadot-js / api / packages / metadata / src / Decorated / extrinsics / fromMetadata / fromMetadata.spec.ts View on Github external
// Copyright 2017-2019 @polkadot/metadata 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 { createType, Metadata, TypeRegistry } from '@polkadot/types';

import json from '../../../Metadata/static';
import fromMetadata from '.';

// Use the pre-generated metadata
const registry = new TypeRegistry();
const metadata = new Metadata(registry, json);
const newExtrinsics = fromMetadata(registry, metadata);

describe('fromMetadata', (): void => {
  it('should throw if an incorrect number of args is supplied', (): void => {
    expect((): any => newExtrinsics.balances.setBalance()).toThrowError(/expects 3 arguments/);
  });

  it('should return a value if the storage function does not expect an argument', (): void => {
    expect((): any => newExtrinsics.balances.setBalance('5C62W7ELLAAfix9LYrcx5smtcffbhvThkM5x7xfMeYXCtGwF', 2, 3)).not.toThrow();
  });

  it('should return properly-encoded transactions', (): void => {
    expect(
      createType(registry, 'Extrinsic', newExtrinsics.timestamp.set([10101])).toU8a()
    ).toEqual(
github polkadot-js / api / packages / metadata / src / Decorated / consts / fromMetadata / fromMetadata.spec.ts View on Github external
// Copyright 2017-2019 @polkadot/metadata 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 { ClassOf, Metadata, TypeRegistry } from '@polkadot/types';

import rpcMetadata from '../../../Metadata/static';
import fromMetadata from '../fromMetadata';

// Use the pre-generated metadata
const registry = new TypeRegistry();
const metadata = new Metadata(registry, rpcMetadata);
const consts = fromMetadata(registry, metadata);

describe('fromMetadata', (): void => {
  it('should return constants with the correct type and value', (): void => {
    expect(consts.democracy.cooloffPeriod).toBeInstanceOf(ClassOf(registry, 'BlockNumber'));
    // 3 second blocks, 28 days
    expect(consts.democracy.cooloffPeriod.toNumber()).toEqual(28 * 24 * 60 * (60 / 3));
  });

  it('correctly handles bytes', (): void => {
    // 0x34 removes as the length prefix removed
    expect(consts.session.dedupKeyPrefix.toHex()).toEqual('0x3a73657373696f6e3a6b657973');
  });
});
github polkadot-js / api / packages / api / src / checkTypes.manual.ts View on Github external
function types (): void {
  // check correct types with `createType`
  const balance = createType('Balance', 2);
  const gas = createType('Gas', 2);
  const compact = createType('Compact', 2);
  // const random = createType('RandomType', 2); // This one should deliberately show a TS error

  const gasUnsafe = createTypeUnsafe('Gas', [2]);
  const overriddenUnsafe = createTypeUnsafe<header>('Gas', [2]);

  console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe);
}
</header>
github polkadot-js / api / packages / rpc-core / src / index.ts View on Github external
//   - Codec - There is a valid value, non-empty
      //   - null - The storage key is empty
      return keys.reduce((results, key: StorageKey): Codec[] => {
        try {
          results.push(this.formatStorageSet(key, changes, withCache));
        } catch (error) {
          console.error(`Unable to decode storage ${key.section}.${key.method}:`, error.message);

          throw error;
        }

        return results;
      }, [] as Codec[]);
    }

    return createTypeUnsafe(this.registry, method.type, [result]);
  }
github polkadot-js / api / packages / api / src / checkTypes.manual.ts View on Github external
function types (): void {
  // check correct types with `createType`
  const balance = createType('Balance', 2);
  const gas = createType('Gas', 2);
  const compact = createType('Compact', 2);
  // const random = createType('RandomType', 2); // This one should deliberately show a TS error

  const gasUnsafe = createTypeUnsafe('Gas', [2]);
  const overriddenUnsafe = createTypeUnsafe<header>('Gas', [2]);

  console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe);
}
</header>
github polkadot-js / api / packages / api / src / checkTypes.manual.ts View on Github external
function types (): void {
  // check correct types with `createType`
  const balance = createType('Balance', 2);
  const gas = createType('Gas', 2);
  const compact = createType('Compact', 2);
  // const random = createType('RandomType', 2); // This one should deliberately show a TS error

  const gasUnsafe = createTypeUnsafe('Gas', [2]);
  const overriddenUnsafe = createTypeUnsafe<header>('Gas', [2]);

  console.log(balance, gas, compact, gasUnsafe, overriddenUnsafe);
}
</header>
github polkadot-js / apps / packages / react-params / src / Param / findComponent.ts View on Github external
return ['Vec'].includes(type)
          ? 'Vec'
          : 'Vec';

      default:
        return type;
    }
  })(def);

  let Component = findOne(type);

  if (!Component) {
    try {
      const instance = createType(registry, type as any);
      const raw = getTypeDef(instance.toRawType());

      Component = findOne(raw.type);

      if (Component) {
        return Component;
      } else if (instance instanceof BN) {
        return Amount;
      } else if ([TypeDefInfo.Enum, TypeDefInfo.Struct].includes(raw.info)) {
        return findComponent(raw, overrides);
      }
    } catch (error) {
      // console.error(error.message);
    }

    // we only want to want once, not spam
    if (!warnList.includes(type)) {
github polkadot-js / apps / packages / react-params / src / Param / findComponent.ts View on Github external
return ['Vec'].includes(type)
          ? 'Vec'
          : 'Vec';

      default:
        return type;
    }
  })(def);

  let Component = findOne(type);

  if (!Component) {
    try {
      const instance = createType(type as any);
      const raw = getTypeDef(instance.toRawType());

      Component = findOne(raw.type);

      if (Component) {
        return Component;
      } else if (instance instanceof BN) {
        return Amount;
      } else if ([TypeDefInfo.Enum, TypeDefInfo.Struct].includes(raw.info)) {
        return findComponent(raw, overrides);
      }
    } catch (error) {
      // console.error(error.message);
    }

    console.warn(`Cannot find Component for ${type}, defaulting to Unknown`);
  }