Pezkuwi API
    Preparing search index...

    Class ApiPromise

    @pezkuwi/api/promise

    ApiPromise

    ApiPromise is a standard JavaScript wrapper around the RPC and interfaces on the Pezkuwi network. As a full Promise-based, all interface calls return Promises, including the static .create(...). Subscription calls utilise (value) => {} callbacks to pass through the latest values.

    The API is well suited to real-time applications where either the single-shot state is needed or use is to be made of the subscription-based features of Pezkuwi (and Bizinikiwi) clients.

    [[ApiRx]]

    Making rpc calls -

    import ApiPromise from '@pezkuwi/api/promise';

    // initialise via static create
    const api = await ApiPromise.create();

    // make a subscription to the network head
    api.rpc.chain.subscribeNewHeads((header) => {
    console.log(`Chain is at #${header.number}`);
    });

    Subscribing to chain state -

    import { ApiPromise, WsProvider } from '@pezkuwi/api';

    // initialise a provider with a specific endpoint
    const provider = new WsProvider('wss://example.com:9944')

    // initialise via isReady & new with specific provider
    const api = await new ApiPromise({ provider }).isReady;

    // retrieve the block target time
    const blockPeriod = await api.query.timestamp.blockPeriod().toNumber();
    let last = 0;

    // subscribe to the current block timestamp, updates automatically (callback provided)
    api.query.timestamp.now((timestamp) => {
    const elapsed = last
    ? `, ${timestamp.toNumber() - last}s since last`
    : '';

    last = timestamp.toNumber();
    console.log(`timestamp ${timestamp}${elapsed} (${blockPeriod}s target)`);
    });

    Submitting a transaction -

    import ApiPromise from '@pezkuwi/api/promise';

    ApiPromise.create().then((api) => {
    const [nonce] = await api.query.system.account(keyring.alice.address);

    api.tx.balances
    // create transfer
    transfer(keyring.bob.address, 12345)
    // sign the transcation
    .sign(keyring.alice, { nonce })
    // send the transaction (optional status callback)
    .send((status) => {
    console.log(`current status ${status.type}`);
    })
    // retrieve the submitted extrinsic hash
    .then((hash) => {
    console.log(`submitted with hash ${hash}`);
    });
    });

    Hierarchy

    • ApiBase<"promise">
      • ApiPromise
    Index
    • Parameters

      • Optionaloptions: ApiOptions

        Options to create an instance. This can be either [[ApiOptions]] or an [[WsProvider]].

      Returns ApiPromise

      Creates an instance of the ApiPromise class


      import Api from '@pezkuwi/api/promise';

      new Api().isReady.then((api) => {
      api.rpc.subscribeNewHeads((header) => {
      console.log(`new block #${header.number.toNumber()}`);
      });
      });
    __phantom: BN = ...
    _call: QueryableCalls<"promise"> = ...
    _consts: QueryableConsts<"promise"> = ...
    _decorateMethod: DecorateMethod<"promise">

    This is the one and only method concrete children classes need to implement. It's a higher-order function, which takes one argument method: Method extends (...args: any[]) => Observable<any> (and one optional options), and should return the user facing method. For example:

    • For ApiRx, decorateMethod should just be identity, because the input function is already an Observable
    • For ApiPromise, decorateMethod should return a function that takes all the parameters from method, adds an optional callback argument, and returns a Promise.

    We could easily imagine other user-facing interfaces, which are simply implemented by transforming the Observable to Stream/Iterator/Kefir/Bacon via decorateMethod.

    _derive?: AllDerives<"promise">
    _errors: DecoratedErrors<"promise"> = ...
    _events: DecoratedEvents<"promise"> = ...
    _extrinsics?: SubmittableExtrinsics<"promise">
    _extrinsicType: number = GenericExtrinsic.LATEST_EXTRINSIC_VERSION
    _genesisHash?: Hash
    _isConnected: BehaviorSubject<boolean>
    _isReady: boolean = false
    _options: ApiOptions
    _query: QueryableStorage<"promise"> = ...
    _queryMulti?: QueryableStorageMultiPromise<"promise">
    _rpc?: DecoratedRpc<"promise", RpcInterface>
    _rpcCore: RpcCore & RpcInterface
    _runtimeChain?: Text
    _runtimeMap: Record<HexString, string> = {}
    _runtimeMetadata?: Metadata
    _runtimeVersion?: RuntimeVersion
    _rx: ApiInterfaceRx = ...
    _type: ApiTypes
    • get call(): QueryableCalls<ApiType>

      Returns QueryableCalls<ApiType>

      Runtime call interfaces (currently untyped, only decorated via API options)

    • get consts(): QueryableConsts<ApiType>

      Returns QueryableConsts<ApiType>

      Contains the parameter types (constants) of all modules.

      The values are instances of the appropriate type and are accessible using section.constantName,


      console.log(api.consts.democracy.enactmentPeriod.toString())
      
    • get derive(): ReturnType<Getters<ApiType>["_decorateDerive"]>

      Returns ReturnType<Getters<ApiType>["_decorateDerive"]>

      Derived results that are injected into the API, allowing for combinations of various query results.


      api.derive.chain.bestNumber((number) => {
      console.log('best number', number);
      });
    • get errors(): DecoratedErrors<ApiType>

      Returns DecoratedErrors<ApiType>

      Errors from metadata

    • get events(): DecoratedEvents<ApiType>

      Returns DecoratedEvents<ApiType>

      Events from metadata

    • get extrinsicVersion(): number

      Returns number

      Returns the version of extrinsics in-use on this chain

    • get genesisHash(): Hash

      Returns Hash

      Contains the genesis Hash of the attached chain. Apart from being useful to determine the actual chain, it can also be used to sign immortal transactions.

    • get isConnected(): boolean

      Returns boolean

      true is the underlying provider is connected

    • get libraryInfo(): string

      Returns string

      The library information name & version (from package.json)

    • get query(): QueryableStorage<ApiType>

      Returns QueryableStorage<ApiType>

      Contains all the chain state modules and their subsequent methods in the API. These are attached dynamically from the runtime metadata.

      All calls inside the namespace, is denoted by section.method and may take an optional query parameter. As an example, api.query.timestamp.now() (current block timestamp) does not take parameters, while api.query.system.account(<accountId>) (retrieving the associated nonce & balances for an account), takes the AccountId as a parameter.


      api.query.system.account(<accountId>, ([nonce, balance]) => {
      console.log('new free balance', balance.free, 'new nonce', nonce);
      });
    • get queryMulti(): QueryableStorageMulti<ApiType>

      Returns QueryableStorageMulti<ApiType>

      Allows for the querying of multiple storage entries and the combination thereof into a single result. This is a very optimal way to make multiple queries since it only makes a single connection to the node and retrieves the data over one subscription.


      const unsub = await api.queryMulti(
      [
      // you can include the storage without any parameters
      api.query.balances.totalIssuance,
      // or you can pass parameters to the storage query
      [api.query.system.account, '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']
      ],
      ([existential, [, { free }]]) => {
      console.log(`You have ${free.sub(existential)} more than the existential deposit`);

      unsub();
      }
      );
    • get rpc(): DecoratedRpc<ApiType, RpcInterface>

      Returns DecoratedRpc<ApiType, RpcInterface>

      Contains all the raw rpc sections and their subsequent methods in the API as defined by the jsonrpc interface definitions. Unlike the dynamic api.query and api.tx sections, these methods are fixed (although extensible with node upgrades) and not determined by the runtime.

      RPC endpoints available here allow for the query of chain, node and system information, in addition to providing interfaces for the raw queries of state (using known keys) and the submission of transactions.


      api.rpc.chain.subscribeNewHeads((header) => {
      console.log('new header', header);
      });
    • get runtimeMetadata(): Metadata

      Returns Metadata

      Yields the current attached runtime metadata. Generally this is only used to construct extrinsics & storage, but is useful for current runtime inspection.

    • get runtimeVersion(): RuntimeVersion

      Returns RuntimeVersion

      Contains the version information for the current runtime.

    • get rx(): Pick<ApiInterfaceRx, "tx" | "rpc" | "query" | "call">

      Returns Pick<ApiInterfaceRx, "tx" | "rpc" | "query" | "call">

      The underlying Rx API interface

    • get stats(): RpcCoreStats | undefined

      Returns RpcCoreStats | undefined

      Returns the underlying provider stats

    • get tx(): SubmittableExtrinsics<ApiType>

      Returns SubmittableExtrinsics<ApiType>

      Contains all the extrinsic modules and their subsequent methods in the API. It allows for the construction of transactions and the submission thereof. These are attached dynamically from the runtime metadata.


      api.tx.balances
      .transferAllowDeath(<recipientId>, <balance>)
      .signAndSend(<keyPair>, ({status}) => {
      console.log('tx status', status.asFinalized.toHex());
      });
    • get type(): ApiTypes

      Returns ApiTypes

      The type of this API instance, either 'rxjs' or 'promise'

    • Parameters

      • result: DefinitionsCall
      • Optionaladditional: DefinitionsCall

      Returns void

    • Parameters

      • registry: VersionedRegistry<"promise">
      • fromEmpty: boolean
      • decoratedApi: ApiDecoration<"promise"> | null
      • OptionalblockHash: Uint8Array

      Returns FullDecoration<"promise">

    • Type Parameters

      • ApiType extends ApiTypes

      Parameters

      • registry: Registry
      • def: DefinitionCallNamed
      • stateCall: (method: string, bytes: Uint8Array) => Observable<Codec>
      • decorateMethod: DecorateMethod<ApiType>

      Returns AugmentedCall<ApiType>

    • Type Parameters

      • ApiType extends ApiTypes

      Parameters

      • __namedParameters: VersionedRegistry<any>
      • decorateMethod: DecorateMethod<ApiType>
      • OptionalblockHash: string | Uint8Array | null

      Returns QueryableCalls<ApiType>

    • Parameters

      • decorateMethod: DecorateMethod<"promise">

      Returns AllDerives<ApiType>

    • Parameters

      • decorateMethod: DecorateMethod<"promise">

      Returns AllDerives<"rxjs">

    • Type Parameters

      • ApiType extends ApiTypes

      Parameters

      • __namedParameters: DecoratedMeta
      • decorateMethod: DecorateMethod<ApiType>

      Returns SubmittableExtrinsics<ApiType>

    • Type Parameters

      • ApiType extends ApiTypes

      Parameters

      • atApi: ApiDecoration<ApiType>
      • decorateMethod: DecorateMethod<ApiType>
      • blockHash: string | Uint8Array

      Returns QueryableStorageMulti<ApiType>

    • Type Parameters

      • ApiType extends ApiTypes

      Parameters

      • rpc: RpcCore & RpcInterface
      • decorateMethod: DecorateMethod<ApiType>
      • input: Partial<DecoratedRpc<ApiType, RpcInterface>> = ...

      Returns DecoratedRpc<ApiType, RpcInterface>

    • Type Parameters

      • ApiType extends ApiTypes

      Parameters

      • __namedParameters: DecoratedMeta
      • decorateMethod: DecorateMethod<ApiType>
      • OptionalblockHash: Uint8Array

      Returns QueryableStorage<ApiType>

    • Parameters

      • registry: Registry
      • OptionalblockHash: Uint8Array

      Returns ApiDecoration<"promise">

    • Parameters

      • methods: string[]
      • additional: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>

      Returns void

    • Parameters

      • registry: Registry
      • methods: Vec<RuntimeApiMethodMetadataV16>

      Returns Record<string, DefinitionCall>

    • Parameters

      • registry: Registry
      • specName: Text
      • chain: string | Text = ''

      Returns [string, DefinitionsCallEntry[]][]

    • Parameters

      • registry: Registry

      Returns [string, DefinitionsCallEntry[]][]

    • Parameters

      • registry: VersionedRegistry<"promise">
      • fromEmpty: boolean = false

      Returns void

    • Parameters

      • blockHash: string | Uint8Array
      • OptionalknownVersion: RuntimeVersion

      Returns Promise<ApiDecoration<"promise">>

      Returns a decorated API instance at a specific point in time

    • Type Parameters

      • T extends any[] = any[]

      Parameters

      • fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[]

        An array of function to combine, each in the form of (cb: (value: void)) => void

      • callback: CombinatorCallback<T>

        A callback that will return an Array of all the values this combinator has been applied to

      Returns UnsubscribePromise

      Creates a combinator that can be used to combine the latest results from multiple subscriptions


      const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFacT7';

      // combines values from balance & nonce as it updates
      api.combineLatest([
      api.rpc.chain.subscribeNewHeads,
      (cb) => api.query.system.account(address, cb)
      ], ([head, [balance, nonce]]) => {
      console.log(`#${head.number}: You have ${balance.free} units, with ${nonce} transactions sent`);
      });
    • Returns Promise<void>

      Connect from the underlying provider, halting all network traffic

    • Type Parameters

      • T extends Codec = Codec
      • K extends string = string

      Parameters

      • type: K
      • ...params: unknown[]

      Returns DetectCodec<T, K>

      Creates an instance of a type as registered

    • Returns Promise<void>

      Disconnect from the underlying provider, halting all network traffic

    • Parameters

      • type: ApiInterfaceEvents
      • ...args: unknown[]

      Returns boolean

    • Parameters

      • callIndex: string | Uint8Array

      Returns CallFunction

      Finds the definition for a specific [[CallFunction]] based on the index supplied

    • Parameters

      • errorIndex: string | Uint8Array

      Returns RegistryError

      Finds the definition for a specific [[RegistryError]] based on the index supplied

    • Parameters

      • blockHash: Uint8Array
      • OptionalknownVersion: RuntimeVersion

      Returns Promise<VersionedRegistry<"promise">>

      Sets up a registry based on the block hash defined

    • Parameters

      • metadata: Metadata
      • OptionalfromEmpty: boolean
      • Optionalregistry: Registry

      Returns void

      backwards compatible endpoint for metadata injection, may be removed in the future (However, it is still useful for testing injection)

    • Parameters

      • type: ApiInterfaceEvents

        The type of event the callback was attached to. Available events are connected, disconnected, ready and error

      • handler: (...args: any[]) => any

        The callback to unregister.

      Returns this

      Remove the given eventemitter handler


      const handler = (): void => {
      console.log('Connected !);
      };

      // Start listening
      api.on('connected', handler);

      // Stop listening
      api.off('connected', handler);
    • Parameters

      • type: ApiInterfaceEvents

        The type of event to listen to. Available events are connected, disconnected, ready and error

      • handler: (...args: any[]) => any

        The callback to be called when the event fires. Depending on the event type, it could fire with additional arguments.

      Returns this

      Attach an eventemitter handler to listen to a specific event


      api.on('connected', (): void => {
      console.log('API has been connected to the endpoint');
      });

      api.on('disconnected', (): void => {
      console.log('API has been disconnected from the endpoint');
      });
    • Parameters

      • type: ApiInterfaceEvents

        The type of event to listen to. Available events are connected, disconnected, ready and error

      • handler: (...args: any[]) => any

        The callback to be called when the event fires. Depending on the event type, it could fire with additional arguments.

      Returns this

      Attach an one-time eventemitter handler to listen to a specific event


      api.once('connected', (): void => {
      console.log('API has been connected to the endpoint');
      });

      api.once('disconnected', (): void => {
      console.log('API has been disconnected from the endpoint');
      });
    • Parameters

      • Optionaltypes: RegistryTypes

      Returns void

      Register additional user-defined of chain-specific types in the type registry

    • Parameters

      • signer: Signer | undefined

      Returns void

      Set an external signer which will be used to sign extrinsic when account passed in is not KeyringPair

    • Parameters

      • address: string | KeyringSigner
      • data: SignerPayloadRawBase
      • __namedParameters: SignerRawOptions = {}

      Returns Promise<string>

      Signs a raw signer payload, string or Uint8Array

    • Parameters

      • Optionaloptions: ApiOptions

        options that is passed to the class contructor. Can be either [[ApiOptions]] or a provider (see the constructor arguments)

      Returns Promise<ApiPromise>

      Creates an ApiPromise instance using the supplied provider. Returns an Promise containing the actual Api instance.


      import Api from '@pezkuwi/api/promise';

      Api.create().then(async (api) => {
      const timestamp = await api.query.timestamp.now();

      console.log(`lastest block timestamp ${timestamp}`);
      });