Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@polkadot-api/substrate-client

Package Overview
Dependencies
Maintainers
2
Versions
596
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@polkadot-api/substrate-client - npm Package Compare versions

Comparing version 0.0.1-54c1591a9d199ba11ff8a4812a07691b79f01f62.1.0 to 0.0.1-555f0404f08f78dbd3388bef9ab082674e43ba5e.1.0

117

dist/index.d.ts

@@ -1,3 +0,2 @@

import { ConnectProvider } from '@polkadot-api/json-rpc-provider';
export { ConnectProvider, Provider } from '@polkadot-api/json-rpc-provider';
import { JsonRpcProvider } from '@polkadot-api/json-rpc-provider';

@@ -27,3 +26,3 @@ interface IRpcError {

type FollowSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn;
type FollowSubscriptionCb<T> = (methodName: string, subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn;
type ClientRequestCb<T, TT> = {

@@ -39,2 +38,12 @@ onSuccess: (result: T, followSubscription: FollowSubscriptionCb<TT>) => void;

declare class DestroyedError extends Error {
constructor();
}
type FollowInnerSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn;
type ClientInnerRequestCb<T, TT> = {
onSuccess: (result: T, followSubscription: FollowInnerSubscriptionCb<TT>) => void;
onError: (e: Error) => void;
};
type ClientInnerRequest<T, TT> = (method: string, params: Array<any>, cb?: ClientInnerRequestCb<T, TT>) => UnsubscribeFn;
interface StorageItemInput {

@@ -60,3 +69,3 @@ key: string;

type: "initialized";
finalizedBlockHash: string;
finalizedBlockHashes: string[];
}

@@ -105,3 +114,3 @@ type InitializedWithRuntime$1 = Initialized & {

unpin: (hashes: Array<string>) => Promise<void>;
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn;
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientInnerRequestCb<Reply, Notification>) => UnsubscribeFn;
}

@@ -111,2 +120,3 @@ interface ChainHead {

(withRuntime: true, cb: (event: FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse;
(withRuntime: boolean, cb: (event: FollowEventWithoutRuntime | FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse;
}

@@ -138,6 +148,9 @@

}
interface InitializedRpc {
type InitializedRpc = {
event: "initialized";
finalizedBlockHash: string;
}
} | {
event: "initialized";
finalizedBlockHashes: string[];
};
type InitializedWithRuntime = InitializedRpc & {

@@ -209,87 +222,6 @@ finalizedBlockRuntime: RuntimeRpc;

interface TxValidated {
type: "validated";
}
interface TxBroadcasted {
type: "broadcasted";
numPeers: number;
}
interface TxBestChainBlockIncluded {
type: "bestChainBlockIncluded";
block: {
hash: string;
index: number;
} | null;
}
interface TxFinalized {
type: "finalized";
block: {
hash: string;
index: number;
};
}
interface TxInvalid {
type: "invalid";
error: string;
}
interface TxDropped {
type: "dropped";
broadcasted: boolean;
error: string;
}
interface TxError {
type: "error";
error: string;
}
type TxEvent = TxValidated | TxBroadcasted | TxBestChainBlockIncluded | TxFinalized | TxInvalid | TxDropped | TxError;
type Transaction = (tx: string, next: (event: TxEvent) => void, error: (e: Error) => void) => UnsubscribeFn;
type Transaction = (tx: string, error: (e: Error) => void) => UnsubscribeFn;
interface TxValidatedRpc {
event: "validated";
}
interface TxBroadcastedRpc {
event: "broadcasted";
numPeers: number;
}
interface TxBestChainBlockIncludedRpc {
event: "bestChainBlockIncluded";
block: {
hash: string;
index: number;
} | null;
}
interface TxFinalizedRpc {
event: "finalized";
block: {
hash: string;
index: number;
};
}
interface TxInvalidRpc {
event: "invalid";
error: string;
}
interface TxDroppedRpc {
event: "dropped";
broadcasted: boolean;
error: string;
}
interface TxErrorRpc {
event: "error";
error: string;
}
type TxEventRpc = TxValidatedRpc | TxBroadcastedRpc | TxBestChainBlockIncludedRpc | TxFinalizedRpc | TxInvalidRpc | TxDroppedRpc | TxErrorRpc;
declare const getTransaction: (request: ClientRequest<string, any>, rpcMethods: Promise<Set<string>> | Set<string>) => (tx: string, error: (e: Error) => void) => () => void;
type ErrorEvents = TxDroppedRpc | TxInvalidRpc | TxErrorRpc;
interface ITxError {
type: ErrorEvents["event"];
error: string;
}
declare class TransactionError extends Error implements ITxError {
type: "error" | "invalid" | "dropped";
error: string;
constructor(e: ErrorEvents);
}
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => Transaction;
interface SubstrateClient {

@@ -299,6 +231,7 @@ chainHead: ChainHead;

destroy: UnsubscribeFn;
request: <T>(method: string, params: any[], abortSignal?: AbortSignal) => Promise<T>;
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn;
}
declare const createClient: (provider: ConnectProvider) => SubstrateClient;
declare const createClient: (provider: JsonRpcProvider) => SubstrateClient;
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientRequest, type ClientRequestCb, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction };
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientInnerRequest, type ClientInnerRequestCb, type ClientRequest, type ClientRequestCb, DestroyedError, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowInnerSubscriptionCb, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, type UnsubscribeFn, createClient, getChainHead, getTransaction };

@@ -28,2 +28,3 @@ "use strict";

__export(src_exports, {
DestroyedError: () => DestroyedError,
DisjointError: () => DisjointError,

@@ -35,3 +36,2 @@ OperationError: () => OperationError,

StopError: () => StopError,
TransactionError: () => TransactionError,
createClient: () => createClient2

@@ -42,22 +42,17 @@ });

// src/internal-utils/abortablePromiseFn.ts
var AbortError = class extends Error {
constructor() {
super("Aborted by AbortSignal");
this.name = "AbortError";
}
};
var import_utils = require("@polkadot-api/utils");
var abortablePromiseFn = (fn) => (...args) => new Promise((res, rej) => {
let cancel = import_utils.noop;
const [actualArgs, abortSignal] = args[args.length - 1] instanceof AbortSignal ? [args.slice(0, args.length - 1), args[args.length - 1]] : [args];
const onAbort = () => {
cancel();
rej(new AbortError());
rej(new import_utils.AbortError());
};
abortSignal?.addEventListener("abort", onAbort, { once: true });
const removeAbortListener = (fn2) => (x) => {
const withCleanup = (fn2) => (x) => {
cancel = import_utils.noop;
abortSignal?.removeEventListener("abort", onAbort);
fn2(x);
};
const cancel = fn(
...[removeAbortListener(res), removeAbortListener(rej), ...actualArgs]
);
cancel = fn(...[withCleanup(res), withCleanup(rej), ...actualArgs]);
});

@@ -79,3 +74,3 @@

// src/internal-utils/noop.ts
var noop = () => {
var noop2 = () => {
};

@@ -115,51 +110,38 @@

// src/transaction/transaction.ts
var eventToType = (input) => {
const { event: type, ...rest } = input;
return { type, ...rest };
var getTxBroadcastNames = (input) => {
if (input.has("transaction_v1_broadcast"))
return ["transaction_v1_broadcast", "transaction_v1_stop"];
if (input.has("transactionWatch_unstable_submitAndWatch"))
return [
"transactionWatch_unstable_submitAndWatch",
"transactionWatch_unstable_unwatch"
];
return ["transaction_unstable_submitAndWatch", "transaction_unstable_unwatch"];
};
var terminalEvents = /* @__PURE__ */ new Set([
"dropped",
"invalid",
"finalized",
"error"
]);
function isTerminalEvent(event) {
return terminalEvents.has(event.event);
}
var TransactionError = class extends Error {
constructor(e) {
super(`TxError: ${e.event} - ${e.error}`);
__publicField(this, "type");
__publicField(this, "error");
this.type = e.event;
this.error = e.error;
this.name = "TransactionError";
}
};
var getTransaction = (request) => (tx, next, error) => {
let cancel = request("transaction_unstable_submitAndWatch", [tx], {
onSuccess: (subscriptionId, follow) => {
const done = follow(subscriptionId, {
next: (event) => {
if (isTerminalEvent(event)) {
done();
cancel = noop;
if (event.event !== "finalized")
return error(new TransactionError(event));
}
next(eventToType(event));
},
error(e) {
cancel();
cancel = noop;
error(e);
}
});
cancel = () => {
done();
request("transaction_unstable_unwatch", [subscriptionId]);
var getTransaction = (request, rpcMethods) => (tx, error) => {
const broadcast = (tx2, broadcastFn, cancelBroadcastFn) => request(broadcastFn, [tx2], {
onSuccess: (subscriptionId) => {
cancel = subscriptionId === null ? noop2 : () => {
request(cancelBroadcastFn, [subscriptionId]);
};
if (subscriptionId === null) {
error(
new Error("Max # of broadcasted transactions has been reached")
);
}
},
onError: error
});
let isActive = true;
let cancel = () => {
isActive = false;
};
if (rpcMethods instanceof Promise) {
rpcMethods.then(getTxBroadcastNames).then((names) => {
if (!isActive)
return;
cancel = broadcast(tx, ...names);
});
} else
cancel = broadcast(tx, ...getTxBroadcastNames(rpcMethods));
return () => {

@@ -208,7 +190,7 @@ cancel();

if (response.result === "limitReached") {
cancel = noop;
cancel = noop2;
return rej(new OperationLimitError());
}
let isOperationGoing = true;
let done = noop;
let done = noop2;
const _res = (x) => {

@@ -282,7 +264,7 @@ isOperationGoing = false;

// src/chainhead/storage-subscription.ts
var import_utils = require("@polkadot-api/utils");
var import_utils2 = require("@polkadot-api/utils");
var createStorageCb = (request) => (hash, inputs, childTrie, onItems, onError, onDone, onDiscardedItems) => {
if (inputs.length === 0) {
onDone();
return import_utils.noop;
return import_utils2.noop;
}

@@ -326,3 +308,3 @@ let cancel = request(

const _onError = (e) => {
cancel = import_utils.noop;
cancel = import_utils2.noop;
doneListening();

@@ -332,3 +314,3 @@ onError(e);

const _onDone = () => {
cancel = import_utils.noop;
cancel = import_utils2.noop;
doneListening();

@@ -379,3 +361,3 @@ onDone();

// src/chainhead/unpin.ts
var createUnpinFn = (request) => (hashes) => new Promise((res, rej) => {
var createUnpinFn = (request) => (hashes) => hashes.length > 0 ? new Promise((res, rej) => {
request("chainHead_unstable_unpin", [hashes], {

@@ -387,4 +369,12 @@ onSuccess() {

});
});
}) : Promise.resolve();
// src/client/DestroyedError.ts
var DestroyedError = class extends Error {
constructor() {
super("Client destroyed");
this.name = "DestroyedError";
}
};
// src/chainhead/chainhead.ts

@@ -402,12 +392,14 @@ function isOperationEvent(event) {

if (isOperationEvent(event)) {
if (!subscriptions.has(event.operationId)) {
console.debug(
`Unknown operationId(${event.operationId}) seen on message:
${JSON.stringify(event)}
`
);
}
if (!subscriptions.has(event.operationId))
console.warn("Uknown operationId on", event);
return subscriptions.next(event.operationId, event);
}
if (event.event !== "stop") {
if (event.event === "initialized") {
return onFollowEvent({
type: event.event,
finalizedBlockHashes: "finalizedBlockHash" in event ? [event.finalizedBlockHash] : event.finalizedBlockHashes,
finalizedBlockRuntime: event.finalizedBlockRuntime
});
}
const { event: type, ...rest } = event;

@@ -421,6 +413,6 @@ return onFollowEvent({ type, ...rest });

onFollowError(error);
unfollow();
unfollow(!(error instanceof DestroyedError));
};
const onFollowRequestSuccess = (subscriptionId, follow) => {
const done = follow(subscriptionId, {
const done = follow("chainHead_unstable_followEvent", subscriptionId, {
next: onAllFollowEventsNext,

@@ -431,3 +423,3 @@ error: onAllFollowEventsError

followSubscription = null;
unfollow = noop;
unfollow = noop2;
done();

@@ -445,3 +437,7 @@ sendUnfollow && request("chainHead_unstable_unfollow", [subscriptionId]);

const onFollowRequestError = (e) => {
onFollowError(e);
if (e instanceof DestroyedError) {
unfollow(false);
} else {
onFollowError(e);
}
followSubscription = null;

@@ -461,3 +457,3 @@ deferredFollow.res(e);

disjoint();
return noop;
return noop2;
}

@@ -471,3 +467,3 @@ const onSubscription = (subscription) => {

subscriber.error(new DisjointError());
return noop;
return noop2;
}

@@ -496,3 +492,3 @@ subscriptions.subscribe(operationId, subscriber);

return onSubscription(followSubscription);
let onCancel = noop;
let onCancel = noop2;
followSubscription.then((x) => {

@@ -537,8 +533,10 @@ if (x instanceof Error)

// src/client/createClient.ts
var nextClientId = 1;
var createClient = (gProvider) => {
let clientId = nextClientId++;
const responses = /* @__PURE__ */ new Map();
const subscriptions = getSubscriptionsManager();
let provider = null;
let connection = null;
const send = (id, method, params) => {
provider.send(
connection.send(
JSON.stringify({

@@ -555,3 +553,4 @@ jsonrpc: "2.0",

let id, result, error, params, subscription;
({ id, result, error, params } = JSON.parse(message));
const parsed = JSON.parse(message);
({ id, result, error, params } = parsed);
if (id) {

@@ -562,6 +561,7 @@ const cb = responses.get(id);

responses.delete(id);
return error ? cb.onError(new RpcError(error)) : cb.onSuccess(result, (subscriptionId, subscriber) => {
subscriptions.subscribe(subscriptionId, subscriber);
return error ? cb.onError(new RpcError(error)) : cb.onSuccess(result, (methodName, opaqueId, subscriber) => {
const subscriptionId2 = methodName + opaqueId;
subscriptions.subscribe(subscriptionId2, subscriber);
return () => {
subscriptions.unsubscribe(subscriptionId);
subscriptions.unsubscribe(subscriptionId2);
};

@@ -574,13 +574,7 @@ });

throw 0;
if (!subscriptions.has(subscription)) {
console.debug(
`Unknown subscription "${subscription}" seen on message:
${message}
`
);
}
const subscriptionId = parsed.method + subscription;
if (error) {
subscriptions.error(subscription, new RpcError(error));
subscriptions.error(subscriptionId, new RpcError(error));
} else {
subscriptions.next(subscription, result);
subscriptions.next(subscriptionId, result);
}

@@ -592,12 +586,15 @@ } catch (e) {

}
provider = gProvider(onMessage);
connection = gProvider(onMessage);
const disconnect = () => {
provider?.disconnect();
provider = null;
connection?.disconnect();
connection = null;
subscriptions.errorAll(new DestroyedError());
responses.forEach((r) => r.onError(new DestroyedError()));
responses.clear();
};
let nextId = 1;
const request = (method, params, cb) => {
if (!provider)
if (!connection)
throw new Error("Not connected");
const id = nextId++;
const id = `${clientId}-${nextId++}`;
if (cb)

@@ -619,8 +616,19 @@ responses.set(id, cb);

const client = createClient(provider);
const request = abortablePromiseFn(
(onSuccess, onError, method, params) => client.request(method, params, { onSuccess, onError })
);
let rpcMethods = request("rpc_methods", []).then(
(x) => rpcMethods = new Set(Array.isArray(x) ? x : x.methods)
);
rpcMethods.catch(noop2);
return {
chainHead: getChainHead(client.request),
transaction: getTransaction(client.request),
transaction: getTransaction(
client.request,
rpcMethods
),
destroy: () => {
client.disconnect();
},
request,
_request: client.request

@@ -627,0 +635,0 @@ };

@@ -1,3 +0,2 @@

import { ConnectProvider } from '@polkadot-api/json-rpc-provider';
export { ConnectProvider, Provider } from '@polkadot-api/json-rpc-provider';
import { JsonRpcProvider } from '@polkadot-api/json-rpc-provider';

@@ -27,3 +26,3 @@ interface IRpcError {

type FollowSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn;
type FollowSubscriptionCb<T> = (methodName: string, subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn;
type ClientRequestCb<T, TT> = {

@@ -39,2 +38,12 @@ onSuccess: (result: T, followSubscription: FollowSubscriptionCb<TT>) => void;

declare class DestroyedError extends Error {
constructor();
}
type FollowInnerSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn;
type ClientInnerRequestCb<T, TT> = {
onSuccess: (result: T, followSubscription: FollowInnerSubscriptionCb<TT>) => void;
onError: (e: Error) => void;
};
type ClientInnerRequest<T, TT> = (method: string, params: Array<any>, cb?: ClientInnerRequestCb<T, TT>) => UnsubscribeFn;
interface StorageItemInput {

@@ -60,3 +69,3 @@ key: string;

type: "initialized";
finalizedBlockHash: string;
finalizedBlockHashes: string[];
}

@@ -105,3 +114,3 @@ type InitializedWithRuntime$1 = Initialized & {

unpin: (hashes: Array<string>) => Promise<void>;
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn;
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientInnerRequestCb<Reply, Notification>) => UnsubscribeFn;
}

@@ -111,2 +120,3 @@ interface ChainHead {

(withRuntime: true, cb: (event: FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse;
(withRuntime: boolean, cb: (event: FollowEventWithoutRuntime | FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse;
}

@@ -138,6 +148,9 @@

}
interface InitializedRpc {
type InitializedRpc = {
event: "initialized";
finalizedBlockHash: string;
}
} | {
event: "initialized";
finalizedBlockHashes: string[];
};
type InitializedWithRuntime = InitializedRpc & {

@@ -209,87 +222,6 @@ finalizedBlockRuntime: RuntimeRpc;

interface TxValidated {
type: "validated";
}
interface TxBroadcasted {
type: "broadcasted";
numPeers: number;
}
interface TxBestChainBlockIncluded {
type: "bestChainBlockIncluded";
block: {
hash: string;
index: number;
} | null;
}
interface TxFinalized {
type: "finalized";
block: {
hash: string;
index: number;
};
}
interface TxInvalid {
type: "invalid";
error: string;
}
interface TxDropped {
type: "dropped";
broadcasted: boolean;
error: string;
}
interface TxError {
type: "error";
error: string;
}
type TxEvent = TxValidated | TxBroadcasted | TxBestChainBlockIncluded | TxFinalized | TxInvalid | TxDropped | TxError;
type Transaction = (tx: string, next: (event: TxEvent) => void, error: (e: Error) => void) => UnsubscribeFn;
type Transaction = (tx: string, error: (e: Error) => void) => UnsubscribeFn;
interface TxValidatedRpc {
event: "validated";
}
interface TxBroadcastedRpc {
event: "broadcasted";
numPeers: number;
}
interface TxBestChainBlockIncludedRpc {
event: "bestChainBlockIncluded";
block: {
hash: string;
index: number;
} | null;
}
interface TxFinalizedRpc {
event: "finalized";
block: {
hash: string;
index: number;
};
}
interface TxInvalidRpc {
event: "invalid";
error: string;
}
interface TxDroppedRpc {
event: "dropped";
broadcasted: boolean;
error: string;
}
interface TxErrorRpc {
event: "error";
error: string;
}
type TxEventRpc = TxValidatedRpc | TxBroadcastedRpc | TxBestChainBlockIncludedRpc | TxFinalizedRpc | TxInvalidRpc | TxDroppedRpc | TxErrorRpc;
declare const getTransaction: (request: ClientRequest<string, any>, rpcMethods: Promise<Set<string>> | Set<string>) => (tx: string, error: (e: Error) => void) => () => void;
type ErrorEvents = TxDroppedRpc | TxInvalidRpc | TxErrorRpc;
interface ITxError {
type: ErrorEvents["event"];
error: string;
}
declare class TransactionError extends Error implements ITxError {
type: "error" | "invalid" | "dropped";
error: string;
constructor(e: ErrorEvents);
}
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => Transaction;
interface SubstrateClient {

@@ -299,6 +231,7 @@ chainHead: ChainHead;

destroy: UnsubscribeFn;
request: <T>(method: string, params: any[], abortSignal?: AbortSignal) => Promise<T>;
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn;
}
declare const createClient: (provider: ConnectProvider) => SubstrateClient;
declare const createClient: (provider: JsonRpcProvider) => SubstrateClient;
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientRequest, type ClientRequestCb, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction };
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientInnerRequest, type ClientInnerRequestCb, type ClientRequest, type ClientRequestCb, DestroyedError, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowInnerSubscriptionCb, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, type UnsubscribeFn, createClient, getChainHead, getTransaction };

@@ -1,6 +0,2 @@

"use strict";var I=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var Z=(r,e,t)=>e in r?I(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ee=(r,e)=>{for(var t in e)I(r,t,{get:e[t],enumerable:!0})},re=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of X(e))!Y.call(r,i)&&i!==t&&I(r,i,{get:()=>e[i],enumerable:!(o=V(e,i))||o.enumerable});return r};var te=r=>re(I({},"__esModule",{value:!0}),r);var S=(r,e,t)=>(Z(r,typeof e!="symbol"?e+"":e,t),t);var ce={};ee(ce,{DisjointError:()=>y,OperationError:()=>x,OperationInaccessibleError:()=>T,OperationLimitError:()=>v,RpcError:()=>C,StopError:()=>O,TransactionError:()=>w,createClient:()=>ae});module.exports=te(ce);var W=class extends Error{constructor(){super("Aborted by AbortSignal"),this.name="AbortError"}},_=r=>(...e)=>new Promise((t,o)=>{let[i,a]=e[e.length-1]instanceof AbortSignal?[e.slice(0,e.length-1),e[e.length-1]]:[e],d=()=>{l(),o(new W)};a?.addEventListener("abort",d,{once:!0});let p=c=>m=>{a?.removeEventListener("abort",d),c(m)},l=r(p(t),p(o),...i)});function M(){let r=()=>{},e=()=>{};return{promise:new Promise((o,i)=>{r=o,e=i}),res:r,rej:e}}var E=()=>{};var A=()=>{let r=new Map;return{has:r.has.bind(r),subscribe(e,t){r.set(e,t)},unsubscribe(e){r.delete(e)},next(e,t){r.get(e)?.next(t)},error(e,t){let o=r.get(e);o&&(r.delete(e),o.error(t))},errorAll(e){let t=[...r.values()];r.clear(),t.forEach(o=>{o.error(e)})}}};var oe=r=>{let{event:e,...t}=r;return{type:e,...t}},ne=new Set(["dropped","invalid","finalized","error"]);function ie(r){return ne.has(r.event)}var w=class extends Error{constructor(t){super(`TxError: ${t.event} - ${t.error}`);S(this,"type");S(this,"error");this.type=t.event,this.error=t.error,this.name="TransactionError"}},L=r=>(e,t,o)=>{let i=r("transaction_unstable_submitAndWatch",[e],{onSuccess:(a,d)=>{let p=d(a,{next:l=>{if(ie(l)&&(p(),i=E,l.event!=="finalized"))return o(new w(l));t(oe(l))},error(l){i(),i=E,o(l)}});i=()=>{p(),r("transaction_unstable_unwatch",[a])}},onError:o});return()=>{i()}};var O=class extends Error{constructor(){super("ChainHead stopped"),this.name="StopError"}},y=class extends Error{constructor(){super("ChainHead disjointed"),this.name="DisjointError"}},v=class extends Error{constructor(){super("ChainHead operations limit reached"),this.name="OperationLimitError"}},x=class extends Error{constructor(e){super(e),this.name="OperationError"}},T=class extends Error{constructor(){super("ChainHead operation inaccessible"),this.name="OperationInaccessibleError"}};var P=(r,e)=>t=>_((o,i,...a)=>{let[d,p]=e(...a),l=t(r,d,{onSuccess:(c,m)=>{if(c.result==="limitReached")return l=E,i(new v);let u=!0,s=E,R=b=>{u=!1,s(),o(b)},n=b=>{u=!1,s(),i(b)};s=m(c.operationId,{next:b=>{let f=b;f.event==="operationError"?i(new x(f.error)):f.event==="operationInaccessible"?i(new T):p(b,R,n)},error:n}),l=()=>{u&&(s(),t("chainHead_unstable_stopOperation",[c.operationId]))}},onError:i});return()=>{l()}});var N=P("chainHead_unstable_body",r=>[[r],(e,t)=>{t(e.value)}]);var $=P("chainHead_unstable_call",(r,e,t)=>[[r,e,t],(o,i)=>{i(o.output)}]);var z=r=>e=>new Promise((t,o)=>{r("chainHead_unstable_header",[e],{onSuccess:t,onError:o})});var H=require("@polkadot-api/utils");var D=r=>(e,t,o,i,a,d,p)=>{if(t.length===0)return d(),H.noop;let l=r("chainHead_unstable_storage",[e,t,o],{onSuccess:(c,m)=>{if(c.result==="limitReached"||c.discardedItems===t.length)return a(new v);let u=m(c.operationId,{next:n=>{switch(n.event){case"operationStorageItems":{i(n.items);break}case"operationStorageDone":{R();break}case"operationError":{s(new x(n.error));break}case"operationInaccessible":{s(new T);break}default:r("chainHead_unstable_continue",[])}},error:a});l=()=>{u(),r("chainHead_unstable_stopOperation",[c.operationId])};let s=n=>{l=H.noop,u(),a(n)},R=()=>{l=H.noop,u(),d()};p(c.discardedItems)},onError:a});return()=>{l()}};var B=r=>{let e=D(r);return _((t,o,i,a,d,p)=>{let l=a.startsWith("descendants"),c=l?[]:null,u=e(i,[{key:d,type:a}],p??null,l?s=>{c.push(...s)}:s=>{c=s[0]?.[a]},o,()=>{t(c)},s=>{s>0&&(u(),o(new v))});return u})};var J=r=>e=>new Promise((t,o)=>{r("chainHead_unstable_unpin",[e],{onSuccess(){t()},onError:o})});function se(r){return r.operationId!==void 0}function U(r){return(e,t,o)=>{let i=A(),a=new Set,d=M(),p=d.promise,l=n=>{if(se(n))return i.has(n.operationId)||console.debug(`Unknown operationId(${n.operationId}) seen on message:
${JSON.stringify(n)}
`),i.next(n.operationId,n);if(n.event!=="stop"){let{event:b,...f}=n;return t({type:b,...f})}o(new O),s(!1)},c=n=>{o(n),s()},s=r("chainHead_unstable_follow",[e],{onSuccess:(n,b)=>{let f=b(n,{next:l,error:c});s=(g=!0)=>{p=null,s=E,f(),g&&r("chainHead_unstable_unfollow",[n]),i.errorAll(new y),a.forEach(q=>{q()}),a.clear()},p=n,d.res(n)},onError:n=>{o(n),p=null,d.res(n)}}),R=(n,b,f)=>{let g=()=>{f?.onError(new y)};if(p===null)return g(),E;let q=F=>{if(!f)return r(n,[F,...b]);a.add(g);let K=(h,k)=>p===null?(k.error(new y),E):(i.subscribe(h,k),()=>{i.unsubscribe(h)}),Q=r(n,[F,...b],{onSuccess:h=>{a.delete(g),f.onSuccess(h,K)},onError:h=>{a.delete(g),f.onError(h)}});return()=>{a.delete(g),Q()}};if(typeof p=="string")return q(p);let j=E;return p.then(F=>{if(F instanceof Error)return g();p&&(j=q(F))}),()=>{j()}};return{unfollow(){s(),p=null},body:N(R),call:$(R),header:z(R),storage:B(R),storageSubscription:D(R),unpin:J(R),_request:R}}}var C=class extends Error{constructor(t){super(t.message);S(this,"code");S(this,"data");this.code=t.code,this.data=t.data,this.name="RpcError"}};var G=r=>{let e=new Map,t=A(),o=null,i=(c,m,u)=>{o.send(JSON.stringify({jsonrpc:"2.0",id:c,method:m,params:u}))};function a(c){try{let m,u,s,R,n;if({id:m,result:u,error:s,params:R}=JSON.parse(c),m){let b=e.get(m);return b?(e.delete(m),s?b.onError(new C(s)):b.onSuccess(u,(f,g)=>(t.subscribe(f,g),()=>{t.unsubscribe(f)}))):void 0}if({subscription:n,result:u,error:s}=R,!n||!s&&!Object.hasOwn(R,"result"))throw 0;t.has(n)||console.debug(`Unknown subscription "${n}" seen on message:
${c}
`),s?t.error(n,new C(s)):t.next(n,u)}catch(m){console.warn("Error parsing incomming message: "+c),console.error(m)}}o=r(a);let d=()=>{o?.disconnect(),o=null},p=1;return{request:(c,m,u)=>{if(!o)throw new Error("Not connected");let s=p++;return u&&e.set(s,u),i(s,c,m),()=>{e.delete(s)}},disconnect:d}};var ae=r=>{let e=G(r);return{chainHead:U(e.request),transaction:L(e.request),destroy:()=>{e.disconnect()},_request:e.request}};
"use strict";var H=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(r,e,t)=>e in r?H(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var re=(r,e)=>{for(var t in e)H(r,t,{get:e[t],enumerable:!0})},te=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Y(e))!Z.call(r,o)&&o!==t&&H(r,o,{get:()=>e[o],enumerable:!(n=X(e,o))||n.enumerable});return r};var oe=r=>te(H({},"__esModule",{value:!0}),r);var L=(r,e,t)=>(ee(r,typeof e!="symbol"?e+"":e,t),t);var ae={};re(ae,{DestroyedError:()=>y,DisjointError:()=>S,OperationError:()=>v,OperationInaccessibleError:()=>w,OperationLimitError:()=>E,RpcError:()=>O,StopError:()=>_,createClient:()=>se});module.exports=oe(ae);var I=require("@polkadot-api/utils"),T=r=>(...e)=>new Promise((t,n)=>{let o=I.noop,[c,l]=e[e.length-1]instanceof AbortSignal?[e.slice(0,e.length-1),e[e.length-1]]:[e],a=()=>{o(),n(new I.AbortError)};l?.addEventListener("abort",a,{once:!0});let m=d=>b=>{o=I.noop,l?.removeEventListener("abort",a),d(b)};o=r(m(t),m(n),...c)});function J(){let r=()=>{},e=()=>{};return{promise:new Promise((n,o)=>{r=n,e=o}),res:r,rej:e}}var g=()=>{};var P=()=>{let r=new Map;return{has:r.has.bind(r),subscribe(e,t){r.set(e,t)},unsubscribe(e){r.delete(e)},next(e,t){r.get(e)?.next(t)},error(e,t){let n=r.get(e);n&&(r.delete(e),n.error(t))},errorAll(e){let t=[...r.values()];r.clear(),t.forEach(n=>{n.error(e)})}}};var M=r=>r.has("transaction_v1_broadcast")?["transaction_v1_broadcast","transaction_v1_stop"]:r.has("transactionWatch_unstable_submitAndWatch")?["transactionWatch_unstable_submitAndWatch","transactionWatch_unstable_unwatch"]:["transaction_unstable_submitAndWatch","transaction_unstable_unwatch"],N=(r,e)=>(t,n)=>{let o=(a,m,d)=>r(m,[a],{onSuccess:b=>{l=b===null?g:()=>{r(d,[b])},b===null&&n(new Error("Max # of broadcasted transactions has been reached"))},onError:n}),c=!0,l=()=>{c=!1};return e instanceof Promise?e.then(M).then(a=>{c&&(l=o(t,...a))}):l=o(t,...M(e)),()=>{l()}};var _=class extends Error{constructor(){super("ChainHead stopped"),this.name="StopError"}},S=class extends Error{constructor(){super("ChainHead disjointed"),this.name="DisjointError"}},E=class extends Error{constructor(){super("ChainHead operations limit reached"),this.name="OperationLimitError"}},v=class extends Error{constructor(e){super(e),this.name="OperationError"}},w=class extends Error{constructor(){super("ChainHead operation inaccessible"),this.name="OperationInaccessibleError"}};var W=(r,e)=>t=>T((n,o,...c)=>{let[l,a]=e(...c),m=t(r,l,{onSuccess:(d,b)=>{if(d.result==="limitReached")return m=g,o(new E);let u=!0,s=g,p=f=>{u=!1,s(),n(f)},i=f=>{u=!1,s(),o(f)};s=b(d.operationId,{next:f=>{let R=f;R.event==="operationError"?o(new v(R.error)):R.event==="operationInaccessible"?o(new w):a(f,p,i)},error:i}),m=()=>{u&&(s(),t("chainHead_unstable_stopOperation",[d.operationId]))}},onError:o});return()=>{m()}});var z=W("chainHead_unstable_body",r=>[[r],(e,t)=>{t(e.value)}]);var $=W("chainHead_unstable_call",(r,e,t)=>[[r,e,t],(n,o)=>{o(n.output)}]);var G=r=>e=>new Promise((t,n)=>{r("chainHead_unstable_header",[e],{onSuccess:t,onError:n})});var D=require("@polkadot-api/utils");var k=r=>(e,t,n,o,c,l,a)=>{if(t.length===0)return l(),D.noop;let m=r("chainHead_unstable_storage",[e,t,n],{onSuccess:(d,b)=>{if(d.result==="limitReached"||d.discardedItems===t.length)return c(new E);let u=b(d.operationId,{next:i=>{switch(i.event){case"operationStorageItems":{o(i.items);break}case"operationStorageDone":{p();break}case"operationError":{s(new v(i.error));break}case"operationInaccessible":{s(new w);break}default:r("chainHead_unstable_continue",[])}},error:c});m=()=>{u(),r("chainHead_unstable_stopOperation",[d.operationId])};let s=i=>{m=D.noop,u(),c(i)},p=()=>{m=D.noop,u(),l()};a(d.discardedItems)},onError:c});return()=>{m()}};var K=r=>{let e=k(r);return T((t,n,o,c,l,a)=>{let m=c.startsWith("descendants"),d=m?[]:null,u=e(o,[{key:l,type:c}],a??null,m?s=>{d.push(...s)}:s=>{d=s[0]?.[c]},n,()=>{t(d)},s=>{s>0&&(u(),n(new E))});return u})};var Q=r=>e=>e.length>0?new Promise((t,n)=>{r("chainHead_unstable_unpin",[e],{onSuccess(){t()},onError:n})}):Promise.resolve();var y=class extends Error{constructor(){super("Client destroyed"),this.name="DestroyedError"}};function ne(r){return r.operationId!==void 0}function j(r){return(e,t,n)=>{let o=P(),c=new Set,l=J(),a=l.promise,m=i=>{if(ne(i))return o.has(i.operationId)||console.warn("Uknown operationId on",i),o.next(i.operationId,i);if(i.event!=="stop"){if(i.event==="initialized")return t({type:i.event,finalizedBlockHashes:"finalizedBlockHash"in i?[i.finalizedBlockHash]:i.finalizedBlockHashes,finalizedBlockRuntime:i.finalizedBlockRuntime});let{event:f,...R}=i;return t({type:f,...R})}n(new _),s(!1)},d=i=>{n(i),s(!(i instanceof y))},s=r("chainHead_unstable_follow",[e],{onSuccess:(i,f)=>{let R=f("chainHead_unstable_followEvent",i,{next:m,error:d});s=(h=!0)=>{a=null,s=g,R(),h&&r("chainHead_unstable_unfollow",[i]),o.errorAll(new S),c.forEach(C=>{C()}),c.clear()},a=i,l.res(i)},onError:i=>{i instanceof y?s(!1):n(i),a=null,l.res(i)}}),p=(i,f,R)=>{let h=()=>{R?.onError(new S)};if(a===null)return h(),g;let C=x=>{if(!R)return r(i,[x,...f]);c.add(h);let B=(F,U)=>a===null?(U.error(new S),g):(o.subscribe(F,U),()=>{o.unsubscribe(F)}),A=r(i,[x,...f],{onSuccess:F=>{c.delete(h),R.onSuccess(F,B)},onError:F=>{c.delete(h),R.onError(F)}});return()=>{c.delete(h),A()}};if(typeof a=="string")return C(a);let q=g;return a.then(x=>{if(x instanceof Error)return h();a&&(q=C(x))}),()=>{q()}};return{unfollow(){s(),a=null},body:z(p),call:$(p),header:G(p),storage:K(p),storageSubscription:k(p),unpin:Q(p),_request:p}}}var O=class extends Error{constructor(t){super(t.message);L(this,"code");L(this,"data");this.code=t.code,this.data=t.data,this.name="RpcError"}};var ie=1,V=r=>{let e=ie++,t=new Map,n=P(),o=null,c=(b,u,s)=>{o.send(JSON.stringify({jsonrpc:"2.0",id:b,method:u,params:s}))};function l(b){try{let u,s,p,i,f,R=JSON.parse(b);if({id:u,result:s,error:p,params:i}=R,u){let C=t.get(u);return C?(t.delete(u),p?C.onError(new O(p)):C.onSuccess(s,(q,x,B)=>{let A=q+x;return n.subscribe(A,B),()=>{n.unsubscribe(A)}})):void 0}if({subscription:f,result:s,error:p}=i,!f||!p&&!Object.hasOwn(i,"result"))throw 0;let h=R.method+f;p?n.error(h,new O(p)):n.next(h,s)}catch(u){console.warn("Error parsing incomming message: "+b),console.error(u)}}o=r(l);let a=()=>{o?.disconnect(),o=null,n.errorAll(new y),t.forEach(b=>b.onError(new y)),t.clear()},m=1;return{request:(b,u,s)=>{if(!o)throw new Error("Not connected");let p=`${e}-${m++}`;return s&&t.set(p,s),c(p,b,u),()=>{t.delete(p)}},disconnect:a}};var se=r=>{let e=V(r),t=T((o,c,l,a)=>e.request(l,a,{onSuccess:o,onError:c})),n=t("rpc_methods",[]).then(o=>n=new Set(Array.isArray(o)?o:o.methods));return n.catch(g),{chainHead:j(e.request),transaction:N(e.request,n),destroy:()=>{e.disconnect()},request:t,_request:e.request}};
//# sourceMappingURL=index.js.map
{
"name": "@polkadot-api/substrate-client",
"version": "0.0.1-54c1591a9d199ba11ff8a4812a07691b79f01f62.1.0",
"version": "0.0.1-555f0404f08f78dbd3388bef9ab082674e43ba5e.1.0",
"author": "Josep M Sobrepere (https://github.com/josepot)",

@@ -43,5 +43,4 @@ "repository": {

"devDependencies": {
"@vitest/coverage-v8": "^0.34.3",
"@polkadot-api/json-rpc-provider": "0.0.1-54c1591a9d199ba11ff8a4812a07691b79f01f62.1.0",
"@polkadot-api/utils": "0.0.1-54c1591a9d199ba11ff8a4812a07691b79f01f62.1.0"
"@polkadot-api/utils": "0.0.1-555f0404f08f78dbd3388bef9ab082674e43ba5e.1.0",
"@polkadot-api/json-rpc-provider": "0.0.1-555f0404f08f78dbd3388bef9ab082674e43ba5e.1.0"
},

@@ -48,0 +47,0 @@ "scripts": {

# @polkadot-api/substrate-client
This TypeScript package provides low-level bindings to the [Substrate JSON-RPC Interface](https://paritytech.github.io/json-rpc-interface-spec/introduction.html), enabling interaction with Substrate-based blockchains.
## Usage
Start by creating a `SubstrateClient` object with the exported function `createClient`. To create one, you need a `ConnectProvider` provider defined in [@polkadot-api/json-rpc-provider](https://github.com/polkadot-api/polkadot-api/tree/main/packages/json-rpc-provider) for establishing a connection to a specific blockchain client.
For instance, you can use [@polkadot-api/sc-provider](https://github.com/polkadot-api/polkadot-api/tree/main/packages/sc-provider) to get a substrate-connect provider for connecting to the Polkadot relay chain through a light client:
```ts
import { getScProvider, WellKnownChain } from "@polkadot-api/sc-provider"
import { createClient } from "@polkadot-api/substrate-client"
const scProvider = getScProvider()
const { relayChain } = scProvider(WellKnownChain.polkadot)
const client = createClient(relayChain)
```
### Request
Invoke any method defined in the [JSON-RPC Spec](https://paritytech.github.io/json-rpc-interface-spec/introduction.html) using `client.request(method, params, abortSignal?)`. This returns a promise resolving with the response from the JSON-RPC server.
```ts
const genesisHash = await client.request("chainSpec_v1_genesisHash", [])
```
All promise-returning functions exported by this package accept an [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) for operation cancellation.
### ChainHead
Operations within the [`chainHead` group of functions](https://paritytech.github.io/json-rpc-interface-spec/api/chainHead.html) involve subscriptions and interdependencies between methods. The client has a function that simplifies the interaction with these group.
Calling `client.chainHead(withRuntime, onFollowEvent, onFollowError)` will start a `chainHead_unstable_follow` subscription, and will return a handle to perform operations with the chainHead.
```ts
const chainHead = client.chainHead(
true,
(event) => {
// ...
},
(error) => {
// ...
},
)
```
The handle provides one method per each of the functions defined inside `chainHead`: `chainHead_unstable_body`, `chainHead_unstable_call`, `chainHead_unstable_header`, `chainHead_unstable_storage`, and `chainHead_unstable_unpin`.
The JSON-RPC Spec for chainHead specifies that these functions return an `operationId`, and that the resolved response for the call will come through the `chainHead_unstable_follow` subscription, linking it through this `operationId`.
**`substrate-client`'s chainHead is an abstraction over this**: The events emitted through the `client.chainHead()` callback are only the ones initiated from the JSON-RPC Server. The promise returned by any of the `chainHead`'s handle functions will resolve with the respective event.
```ts
const chainHead = client.chainHead(
true,
async (event) => {
if (event.type === "newBlock") {
const body = await chainHead.body(event.blockHash)
// body is a string[] containing the SCALE-encoded values within the body
processBody(body)
chainHead.unpin([event.blockHash])
}
},
(error) => {
// ...
},
)
```
#### header
Calls `chainHead_unstable_call` and returns a promise that resolves with the SCALE-encoded header of the block
```ts
const header = await chainHead.header(blockHash)
```
#### body
Calls `chainHead_unstable_body` and returns a promise that will resolve with an array of strings containing the SCALE-encoded extrinsics found in the block
```ts
const body = await chainHead.body(blockHash)
```
#### call
Calls `chainHead_unstable_header` and returns a promise that resolves with the encoded output of the runtime function call
```ts
const result = await chainHead.call(blockHash, fnName, callParameters)
```
#### storage
Calls `chainHead_unstable_storage` and returns a promise that resolves with the value returned by the JSON-RPC server, which depends on the `type` parameter. See the [JSON-RPC spec for chainHead_unstable_storage](https://paritytech.github.io/json-rpc-interface-spec/api/chainHead_unstable_storage.html) for the details on the usage.
```ts
// string with the SCALE-encoded value
const value = await chainHead.storage(blockHash, "value", key, childTrie)
// string with the hash value
const hash = await chainHead.storage(blockHash, "hash", key, childTrie)
// string with the merkle value
const items = await chainHead.storage(
blockHash,
"closestDescendantMerkleValue",
key,
childTrie,
)
// array of key-value pairs
const items = await chainHead.storage(
blockHash,
"descendantsValues",
key,
childTrie,
)
// array of key-hash pairs
const hashes = await chainHead.storage(
blockHash,
"descendantsHashes",
key,
childTrie,
)
```
#### storageSubscription
While `storage` only can resolve for one specific item, the JSON-RPC specification allows to resolve multiple items within the same call. For this case, substrate-client also offers a lower-level version called `chainHead.storageSubscription(hash, inputs, childTrie, onItems, onError, onDone, onDiscardedItems)` that emits the storage items as they get resolved by the JSON-RPC server:
```ts
const abort = chainHead.storageSubscription(
hash,
[
{ key, type },
/* ... each item */
],
null,
(items) => {
// items is an array of { key, value?, hash?, closestDescendantMerkleValue? }
},
onError,
onDone,
(nDiscardedItems) => {
// amount of discarded items, as defined by the JSON-RPC spec.
},
)
```
`storageSubscription` returns a function to cancel the operation.
#### unpin
Calls `chainHead_unstable_unpin` and returns a promise that will resolve after the operation is done.
```ts
chainHead.unpin(blockHashes)
```
#### unfollow
To close the chainHead subscription, call `chainHead.unfollow()`.
### Transaction
[`transaction` group of functions](https://paritytech.github.io/json-rpc-interface-spec/api/transaction.html) also deals with subscriptions through `submitAndWatch`. SubstrateClient also abstracts over this:
```ts
const cancelRequest = client.transaction(
transaction, // SCALE-encoded transaction
(event) => {
// ...
},
(error) => {
// ...
},
)
// call `cancelRequest()` to abort the transaction (`transaction_unstable_stop`)
```
The `event` emitted through the callback are fully typed, and can be discriminated through `event.type`
```ts
switch (event.type) {
case "validated":
break
case "broadcasted":
const { numPeers } = event
break
case "bestChainBlockIncluded":
case "finalized":
const { block } = event
break
case "dropped":
case "error":
case "invalid":
const { error } = event
break
}
```
### Destroy
Call `client.destroy()` to disconnect from the provider.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc