How to use the @polkadot/types.createType function in @polkadot/types

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 / client / packages / client-p2p / src / handler / blockAnnounce.ts View on Github external
function handleBlockAnnounce ({ sync }: P2pInterface, peer: PeerInterface, message: BlockAnnounce): void {
  // self.l.debug(() => [peer.shortId, 'BlockAnnounce', JSON.stringify(message)]);

  const header = message.header;
  const blockNumber = header.number.unwrap();

  if (peer.bestNumber.lt(blockNumber)) {
    peer.setBest(blockNumber, createType('Header', header).hash);
  }

  sync.requestBlocks(peer);
}
github paritytech / substrate-light-ui / packages / ui-common / src / ContextGate.tsx View on Github external
.subscribe(([chain, health, name, properties, version]) => {
        if (!keyringInitialized) {
          // keyring with Schnorrkel support
          keyring.loadAll({
            ss58Format: properties.ss58Format.unwrapOr(createType('u8', SS58_PREFIX)).toNumber(),
            genesisHash: api.genesisHash,
            isDevelopment: isTestChain(chain.toString()),
            type: 'ed25519'
          });
          keyringInitialized = true;
        } else {
          // The keyring can only be initialized once. To make sure that the
          // keyring values are up-to-date in case the node has changed settings
          // we need to reinitialize it.
          window.location.reload();
          return;
        }

        l.log(`Api connected to ${WS_URL}`);
        l.log(`Api ready, connected to chain "${chain}" with properties ${JSON.stringify(properties)}`);
github polkadot-js / api / packages / api-derive / src / session / info.ts View on Github external
function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, sessionsPerEra], { currentIndex, currentEra, validatorCount }, [currentSlot, epochIndex, epochOrGenesisStartSlot, currentEraStartSessionIndex]]: Result): DerivedSessionInfo {
  const epochStartSlot = epochIndex.mul(epochDuration).add(epochOrGenesisStartSlot);
  const sessionProgress = currentSlot.sub(epochStartSlot);
  const eraProgress = currentIndex.sub(currentEraStartSessionIndex).mul(epochDuration).add(sessionProgress);

  return {
    currentEra,
    currentIndex,
    eraLength: createType(api.registry, 'BlockNumber', sessionsPerEra.mul(epochDuration)),
    eraProgress: createType(api.registry, 'BlockNumber', eraProgress),
    isEpoch: hasBabe,
    lastEraLengthChange: createType(api.registry, 'BlockNumber'),
    lastLengthChange: createType(api.registry, 'BlockNumber', epochStartSlot),
    sessionLength: epochDuration,
    sessionsPerEra,
    sessionProgress: createType(api.registry, 'BlockNumber', sessionProgress),
    validatorCount
  };
}
github polkadot-js / api / packages / api-derive / src / session / info.ts View on Github external
function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, sessionsPerEra], { currentIndex, currentEra, validatorCount }, [currentSlot, epochIndex, epochOrGenesisStartSlot, currentEraStartSessionIndex]]: Result): DerivedSessionInfo {
  const epochStartSlot = epochIndex.mul(epochDuration).add(epochOrGenesisStartSlot);
  const sessionProgress = currentSlot.sub(epochStartSlot);
  const eraProgress = currentIndex.sub(currentEraStartSessionIndex).mul(epochDuration).add(sessionProgress);

  return {
    currentEra,
    currentIndex,
    eraLength: createType(api.registry, 'BlockNumber', sessionsPerEra.mul(epochDuration)),
    eraProgress: createType(api.registry, 'BlockNumber', eraProgress),
    isEpoch: hasBabe,
    lastEraLengthChange: createType(api.registry, 'BlockNumber'),
    lastLengthChange: createType(api.registry, 'BlockNumber', epochStartSlot),
    sessionLength: epochDuration,
    sessionsPerEra,
    sessionProgress: createType(api.registry, 'BlockNumber', sessionProgress),
    validatorCount
  };
}
github polkadot-js / api / packages / api-derive / src / democracy / referendumVotesFor.ts View on Github external
votersFor.map((accountId, index): DerivedReferendumVote => ({
          accountId,
          balance: balances[index].votingBalance || createType(api.registry, 'Balance'),
          vote: votes[index] || createType(api.registry, 'Vote')
        } as DerivedReferendumVote))
      )
github polkadot-js / api / packages / metadata / src / Metadata / v6 / toV7.ts View on Github external
modules: modules.map(({ calls, constants, events, name, prefix, storage }): ModuleMetadataV7 =>
      createType(registry, 'ModuleMetadataV7', {
        calls,
        constants,
        events,
        name,
        storage: storage.isSome
          ? createType(registry, 'StorageMetadataV7', { prefix, items: storage.unwrap() })
          : null
      })
    )
github polkadot-js / api / packages / api-derive / src / session / info.ts View on Github external
function createDerivedLatest (api: ApiInterfaceRx, [[hasBabe, epochDuration, sessionsPerEra], { currentIndex, currentEra, validatorCount }, [currentSlot, epochIndex, epochOrGenesisStartSlot, currentEraStartSessionIndex]]: Result): DerivedSessionInfo {
  const epochStartSlot = epochIndex.mul(epochDuration).add(epochOrGenesisStartSlot);
  const sessionProgress = currentSlot.sub(epochStartSlot);
  const eraProgress = currentIndex.sub(currentEraStartSessionIndex).mul(epochDuration).add(sessionProgress);

  return {
    currentEra,
    currentIndex,
    eraLength: createType(api.registry, 'BlockNumber', sessionsPerEra.mul(epochDuration)),
    eraProgress: createType(api.registry, 'BlockNumber', eraProgress),
    isEpoch: hasBabe,
    lastEraLengthChange: createType(api.registry, 'BlockNumber'),
    lastLengthChange: createType(api.registry, 'BlockNumber', epochStartSlot),
    sessionLength: epochDuration,
    sessionsPerEra,
    sessionProgress: createType(api.registry, 'BlockNumber', sessionProgress),
    validatorCount
  };
}
github polkadot-js / apps / packages / react-signer / src / Checks / constants.ts View on Github external
import BN from 'bn.js';
import { registry } from '@polkadot/react-api';
import { createType } from '@polkadot/types';

const ZERO_BALANCE: DerivedBalances = {
  accountId: createType(registry, 'AccountId'),
  accountNonce: createType(registry, 'Index'),
  availableBalance: createType(registry, 'Balance'),
  freeBalance: createType(registry, 'Balance'),
  isVesting: false,
  lockedBalance: createType(registry, 'Balance'),
  lockedBreakdown: [],
  reservedBalance: createType(registry, 'Balance'),
  vestedBalance: createType(registry, 'Balance'),
  vestingTotal: createType(registry, 'Balance'),
  votingBalance: createType(registry, 'Balance')
};

const ZERO_FEES_BALANCES: DerivedFees = {
  creationFee: createType(registry, 'Balance'),
  existentialDeposit: createType(registry, 'Balance'),
  transactionBaseFee: createType(registry, 'Balance'),
  transactionByteFee: createType(registry, 'Balance'),
  transferFee: createType(registry, 'Balance')
};

const ZERO_FEES = ZERO_FEES_BALANCES;

const ZERO_FEES_CONTRACT: DerivedContractFees = {
  callBaseFee: new BN(0),
  contractFee: new BN(0),
  createBaseFee: new BN(0),