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-87501f61c24616648ccce3e54a19c22477938e7a.1.0 to 0.0.1-87b10c43c1862eec15d3a29e752a1b05b4cc16b1.1.0

35

dist/index.d.ts

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

import { GetProvider } from '@polkadot-api/json-rpc-provider';
export { GetProvider, Provider, ProviderStatus } 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> = {

@@ -35,3 +34,2 @@ onSuccess: (result: T, followSubscription: FollowSubscriptionCb<TT>) => void;

interface Client {
connect: () => void;
disconnect: () => void;

@@ -41,2 +39,12 @@ request: ClientRequest<any, any>;

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 {

@@ -62,3 +70,3 @@ key: string;

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

@@ -107,3 +115,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;
}

@@ -113,2 +121,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;
}

@@ -140,6 +149,9 @@

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

@@ -294,3 +306,3 @@ finalizedBlockRuntime: RuntimeRpc;

}
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => Transaction;
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => (namespace: string, tx: string, next: (event: TxEvent) => void, error: (e: Error) => void) => () => void;

@@ -301,6 +313,7 @@ interface SubstrateClient {

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: GetProvider) => SubstrateClient;
declare const createClient: (provider: JsonRpcProvider) => SubstrateClient;
export { AbortablePromiseFn, BestBlockChanged, ChainHead, Client, ClientRequest, ClientRequestCb, DisjointError, Finalized, FollowEventWithRuntime, FollowEventWithoutRuntime, FollowResponse, FollowSubscriptionCb, IRpcError, Initialized, InitializedWithRuntime$1 as InitializedWithRuntime, NewBlock, NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, Runtime, StopError, StorageItemInput, StorageItemResponse, StorageResult, SubstrateClient, Transaction, TransactionError, TxBestChainBlockIncluded, TxBroadcasted, TxDropped, TxError, TxEvent, TxFinalized, TxInvalid, TxValidated, 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, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction };

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

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

@@ -41,22 +42,17 @@ OperationError: () => OperationError,

// 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]);
});

@@ -78,3 +74,3 @@

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

@@ -113,2 +109,98 @@

// src/client/RpcError.ts
var RpcError = class extends Error {
constructor(e) {
super(e.message);
__publicField(this, "code");
__publicField(this, "data");
this.code = e.code;
this.data = e.data;
this.name = "RpcError";
}
};
// src/client/DestroyedError.ts
var DestroyedError = class extends Error {
constructor() {
super("Client destroyed");
this.name = "DestroyedError";
}
};
// src/client/createClient.ts
var nextClientId = 1;
var createClient = (gProvider) => {
let clientId = nextClientId++;
const responses = /* @__PURE__ */ new Map();
const subscriptions = getSubscriptionsManager();
let connection = null;
const send = (id, method, params) => {
connection.send(
JSON.stringify({
jsonrpc: "2.0",
id,
method,
params
})
);
};
function onMessage(message) {
try {
let id, result, error, params, subscription;
const parsed = JSON.parse(message);
({ id, result, error, params } = parsed);
if (id) {
const cb = responses.get(id);
if (!cb)
return;
responses.delete(id);
return error ? cb.onError(new RpcError(error)) : cb.onSuccess(result, (methodName, opaqueId, subscriber) => {
const subscriptionId2 = methodName + opaqueId;
subscriptions.subscribe(subscriptionId2, subscriber);
return () => {
subscriptions.unsubscribe(subscriptionId2);
};
});
}
;
({ subscription, result, error } = params);
if (!subscription || !error && !Object.hasOwn(params, "result"))
throw 0;
const subscriptionId = parsed.method + subscription;
if (error) {
subscriptions.error(subscriptionId, new RpcError(error));
} else {
subscriptions.next(subscriptionId, result);
}
} catch (e) {
console.warn("Error parsing incomming message: " + message);
console.error(e);
}
}
connection = gProvider(onMessage);
const disconnect = () => {
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 (!connection)
throw new Error("Not connected");
const id = `${clientId}-${nextId++}`;
if (cb)
responses.set(id, cb);
send(id, method, params);
return () => {
responses.delete(id);
};
};
return {
request,
disconnect
};
};
// src/transaction/transaction.ts

@@ -138,24 +230,29 @@ var eventToType = (input) => {

};
var getTransaction = (request) => (tx, next, error) => {
let cancel = request("transaction_unstable_submitAndWatch", [tx], {
var getTransaction = (request) => (namespace, tx, next, error) => {
let cancel = request(namespace + "_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));
const done = follow(
namespace + "_unstable_watchEvent",
subscriptionId,
{
next: (event) => {
if (isTerminalEvent(event)) {
done();
cancel = noop2;
if (event.event !== "finalized")
return error(new TransactionError(event));
}
next(eventToType(event));
},
error(e) {
if (!(e instanceof DestroyedError))
cancel();
cancel = noop2;
error(e);
}
next(eventToType(event));
},
error(e) {
cancel();
cancel = noop;
error(e);
}
});
);
cancel = () => {
done();
request("transaction_unstable_unwatch", [subscriptionId]);
request(namespace + "_unstable_unwatch", [subscriptionId]);
};

@@ -208,7 +305,7 @@ },

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 +379,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 +423,3 @@ let cancel = request(

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

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

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

@@ -379,3 +476,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,3 +484,3 @@ onSuccess() {

});
});
}) : Promise.resolve();

@@ -401,5 +498,15 @@ // src/chainhead/chainhead.ts

const onAllFollowEventsNext = (event) => {
if (isOperationEvent(event))
if (isOperationEvent(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;

@@ -413,6 +520,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,

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

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

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

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

@@ -453,3 +564,3 @@ deferredFollow.res(e);

disjoint();
return noop;
return noop2;
}

@@ -463,3 +574,3 @@ const onSubscription = (subscription) => {

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

@@ -488,3 +599,3 @@ subscriptions.subscribe(operationId, subscriber);

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

@@ -516,135 +627,49 @@ if (x instanceof Error)

// src/client/RpcError.ts
var RpcError = class extends Error {
constructor(e) {
super(e.message);
__publicField(this, "code");
__publicField(this, "data");
this.code = e.code;
this.data = e.data;
this.name = "RpcError";
}
};
// src/client/createClient.ts
var createClient = (gProvider) => {
const responses = /* @__PURE__ */ new Map();
const subscriptions = getSubscriptionsManager();
const queuedRequests = /* @__PURE__ */ new Map();
let provider = null;
let isConnecting = true;
const send = (id, method, params) => {
provider.send(
JSON.stringify({
jsonrpc: "2.0",
id,
method,
params
})
);
};
function onMessage(message) {
try {
let id, result, error, params, subscription;
({ id, result, error, params } = JSON.parse(message));
if (id) {
const cb = responses.get(id);
if (!cb)
return;
responses.delete(id);
return error ? cb.onError(new RpcError(error)) : cb.onSuccess(result, (subscriptionId, subscriber) => {
subscriptions.subscribe(subscriptionId, subscriber);
return () => {
subscriptions.unsubscribe(subscriptionId);
};
});
}
;
({ subscription, result, error } = params);
if (!subscription || !error && !Object.hasOwn(params, "result"))
throw 0;
if (error) {
subscriptions.error(subscription, new RpcError(error));
} else {
subscriptions.next(subscription, result);
}
} catch (e) {
console.warn("Error parsing incomming message: " + message);
console.error(e);
}
}
function onStatusChange(e) {
if (e === "connected") {
isConnecting = false;
queuedRequests.forEach((args, id) => {
process(id, ...args);
});
queuedRequests.clear();
return;
}
if (isConnecting) {
isConnecting = false;
} else {
provider = null;
disconnect();
}
}
const connect = () => {
provider = gProvider(onMessage, onStatusChange);
provider.open();
};
const disconnect = () => {
provider?.close();
provider = null;
const disconnectError = new Error("disconnect");
[...queuedRequests.values()].forEach((request2) => {
request2[2]?.onError(disconnectError);
});
queuedRequests.clear();
[...responses.values()].forEach((response) => {
response.onError(disconnectError);
});
responses.clear();
subscriptions.errorAll(disconnectError);
};
const process = (id, ...args) => {
const [method, params, cb] = args;
if (cb)
responses.set(id, cb);
send(id, method, params);
};
let nextId = 1;
const request = (method, params, cb) => {
if (!provider && !isConnecting)
throw new Error("Not connected");
const id = nextId++;
if (isConnecting)
queuedRequests.set(id, [method, params, cb]);
else
process(id, method, params, cb);
return () => {
if (queuedRequests.has(id)) {
queuedRequests.delete(id);
return;
}
responses.delete(id);
};
};
return {
request,
connect,
disconnect
};
};
// src/index.ts
var import_utils3 = require("@polkadot-api/utils");
var createClient2 = (provider) => {
const client = createClient(provider);
client.connect();
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(import_utils3.noop);
const getSubmitAndWatchNamespace = (input) => input.has("transaction_unstable_submitAndWatch") ? "transaction" : "transactionWatch";
const innerTransaction = getTransaction(
client.request
);
return {
chainHead: getChainHead(client.request),
transaction: getTransaction(client.request),
transaction: (tx, next, err) => {
if (rpcMethods instanceof Promise) {
let cleanup = import_utils3.noop;
let isRunning = true;
rpcMethods.then((result) => {
if (!isRunning)
return;
cleanup = innerTransaction(
getSubmitAndWatchNamespace(result),
tx,
next,
err
);
});
return () => {
isRunning = false;
cleanup();
};
}
return innerTransaction(
getSubmitAndWatchNamespace(rpcMethods),
tx,
next,
err
);
},
destroy: () => {
client.disconnect();
},
request,
_request: client.request

@@ -651,0 +676,0 @@ };

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

import { GetProvider } from '@polkadot-api/json-rpc-provider';
export { GetProvider, Provider, ProviderStatus } 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> = {

@@ -35,3 +34,2 @@ onSuccess: (result: T, followSubscription: FollowSubscriptionCb<TT>) => void;

interface Client {
connect: () => void;
disconnect: () => void;

@@ -41,2 +39,12 @@ request: ClientRequest<any, any>;

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 {

@@ -62,3 +70,3 @@ key: string;

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

@@ -107,3 +115,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;
}

@@ -113,2 +121,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;
}

@@ -140,6 +149,9 @@

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

@@ -294,3 +306,3 @@ finalizedBlockRuntime: RuntimeRpc;

}
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => Transaction;
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => (namespace: string, tx: string, next: (event: TxEvent) => void, error: (e: Error) => void) => () => void;

@@ -301,6 +313,7 @@ interface SubstrateClient {

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: GetProvider) => SubstrateClient;
declare const createClient: (provider: JsonRpcProvider) => SubstrateClient;
export { AbortablePromiseFn, BestBlockChanged, ChainHead, Client, ClientRequest, ClientRequestCb, DisjointError, Finalized, FollowEventWithRuntime, FollowEventWithoutRuntime, FollowResponse, FollowSubscriptionCb, IRpcError, Initialized, InitializedWithRuntime$1 as InitializedWithRuntime, NewBlock, NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, Runtime, StopError, StorageItemInput, StorageItemResponse, StorageResult, SubstrateClient, Transaction, TransactionError, TxBestChainBlockIncluded, TxBroadcasted, TxDropped, TxError, TxEvent, TxFinalized, TxInvalid, TxValidated, 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, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction };

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

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

@@ -43,13 +43,12 @@ "repository": {

"devDependencies": {
"@vitest/coverage-v8": "^0.34.3",
"@polkadot-api/json-rpc-provider": "0.0.1-87501f61c24616648ccce3e54a19c22477938e7a.1.0",
"@polkadot-api/utils": "0.0.1-87501f61c24616648ccce3e54a19c22477938e7a.1.0"
"@polkadot-api/json-rpc-provider": "0.0.1-87b10c43c1862eec15d3a29e752a1b05b4cc16b1.1.0",
"@polkadot-api/utils": "0.0.1-87b10c43c1862eec15d3a29e752a1b05b4cc16b1.1.0"
},
"scripts": {
"build": "tsup-node src/index.ts --clean --sourcemap --platform neutral --target=es2020 --format esm,cjs --dts && tsup-node src/index.ts --clean --sourcemap --platform neutral --target=es2020 --format cjs --dts --minify --out-dir dist/min",
"build": "tsc --noEmit && tsup-node src/index.ts --clean --sourcemap --platform neutral --target=es2020 --format esm,cjs --dts && tsup-node src/index.ts --clean --sourcemap --platform neutral --target=es2020 --format cjs --dts --minify --out-dir dist/min",
"test": "vitest",
"coverage": "vitest run --coverage",
"lint": "tsc --noEmit && prettier --check README.md \"src/**/*.{js,jsx,ts,tsx,json,md}\"",
"lint": "prettier --check README.md \"src/**/*.{js,jsx,ts,tsx,json,md}\"",
"format": "prettier --write README.md \"src/**/*.{js,jsx,ts,tsx,json,md}\""
}
}
# @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