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-587a50d366fe387ce869c46a060d184215af2f4e.1.0 to 0.0.1-5a0915fac7774b8a002e2bd58e977d732739cbe0.1.0

203

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,22 @@ 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 {
key: string;
type: "value" | "hash" | "closestDescendantMerkleValue" | "descendantsValues" | "descendantsHashes";
}
interface StorageItemResponse {
key: string;
value?: string;
hash?: string;
closestDescendantMerkleValue?: string;
}
interface Runtime {

@@ -51,22 +69,22 @@ specName: string;

interface Initialized {
event: "initialized";
finalizedBlockHash: string;
type: "initialized";
finalizedBlockHashes: string[];
}
type InitializedWithRuntime = Initialized & {
type InitializedWithRuntime$1 = Initialized & {
finalizedBlockRuntime: Runtime;
};
interface NewBlock {
event: "newBlock";
type: "newBlock";
blockHash: string;
parentBlockHash: string;
}
type NewBlockWithRuntime = NewBlock & {
type NewBlockWithRuntime$1 = NewBlock & {
newRuntime: Runtime | null;
};
interface BestBlockChanged {
event: "bestBlockChanged";
type: "bestBlockChanged";
bestBlockHash: string;
}
interface Finalized {
event: "finalized";
type: "finalized";
finalizedBlockHashes: Array<string>;

@@ -76,17 +94,11 @@ prunedBlockHashes: Array<string>;

type CommonFollowEvents = BestBlockChanged | Finalized;
type FollowEventWithRuntime = InitializedWithRuntime | NewBlockWithRuntime | CommonFollowEvents;
type FollowEventWithRuntime = InitializedWithRuntime$1 | NewBlockWithRuntime$1 | CommonFollowEvents;
type FollowEventWithoutRuntime = Initialized | NewBlock | CommonFollowEvents;
interface StorageResponse {
values: Record<string, string>;
hashes: Record<string, string>;
closests: Record<string, string>;
descendantsValues: Record<string, Array<{
key: string;
value: string;
}>>;
descendantsHashes: Record<string, Array<{
key: string;
hash: string;
}>>;
}
type StorageResult<Input extends StorageItemInput["type"]> = Input extends "descendantsHashes" ? Array<{
key: string;
hash: string;
}> : Input extends "descendantsValues" ? Array<{
key: string;
value: string;
}> : string | null;
interface FollowResponse {

@@ -100,16 +112,7 @@ unfollow: UnsubscribeFn;

], string>;
storage: AbortablePromiseFn<[
hash: string,
query: Partial<{
value: Array<string>;
hash: Array<string>;
descendantsValues: Array<string>;
descendantsHashes: Array<string>;
closestDescendantMerkleValue: Array<string>;
}>,
childTrie: string | null
], StorageResponse>;
storage: <Type extends StorageItemInput["type"]>(hash: string, type: Type, key: string, childTrie: string | null, abortSignal?: AbortSignal | undefined) => Promise<StorageResult<Type>>;
storageSubscription: (hash: string, inputs: Array<StorageItemInput>, childTrie: string | null, onItems: (items: Array<StorageItemResponse>) => void, onError: (e: Error) => void, onDone: () => void, onDiscardedItems: (nDiscarded: number) => void) => () => void;
header: (hash: string) => Promise<string>;
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;
}

@@ -119,2 +122,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;
}

@@ -131,3 +135,3 @@

}
declare class OperationError$1 extends Error {
declare class OperationError extends Error {
constructor(error: string);

@@ -139,28 +143,66 @@ }

interface Stop {
interface RuntimeRpc {
specName: string;
implName: string;
specVersion: number;
implVersion: number;
transactionVersion: number;
apis: Record<string, number>;
}
type InitializedRpc = {
event: "initialized";
finalizedBlockHash: string;
} | {
event: "initialized";
finalizedBlockHashes: string[];
};
type InitializedWithRuntime = InitializedRpc & {
finalizedBlockRuntime: RuntimeRpc;
};
interface NewBlockRpc {
event: "newBlock";
blockHash: string;
parentBlockHash: string;
}
type NewBlockWithRuntime = NewBlockRpc & {
newRuntime: RuntimeRpc | null;
};
interface BestBlockChangedRpc {
event: "bestBlockChanged";
bestBlockHash: string;
}
interface FinalizedRpc {
event: "finalized";
finalizedBlockHashes: Array<string>;
prunedBlockHashes: Array<string>;
}
type CommonFollowEventsRpc = BestBlockChangedRpc | FinalizedRpc;
type FollowEventWithRuntimeRpc = InitializedWithRuntime | NewBlockWithRuntime | CommonFollowEventsRpc;
type FollowEventWithoutRuntimeRpc = InitializedRpc | NewBlockRpc | CommonFollowEventsRpc;
interface StopRpc {
event: "stop";
}
interface OperationEvent {
interface OperationEventRpc {
operationId: string;
}
type OperationWaitingForContinue = OperationEvent & {
type OperationWaitingForContinueRpc = OperationEventRpc & {
event: "operationWaitingForContinue";
};
type OperationInaccessible = OperationEvent & {
type OperationInaccessibleRpc = OperationEventRpc & {
event: "operationInaccessible";
};
type OperationError = OperationEvent & {
type OperationErrorRpc = OperationEventRpc & {
event: "operationError";
error: string;
};
type CommonOperationEvents = OperationInaccessible | OperationError;
type OperationBodyDone = OperationEvent & {
type CommonOperationEventsRpc = OperationInaccessibleRpc | OperationErrorRpc;
type OperationBodyDoneRpc = OperationEventRpc & {
event: "operationBodyDone";
value: Array<string>;
};
type OperationCallDone = OperationEvent & {
type OperationCallDoneRpc = OperationEventRpc & {
event: "operationCallDone";
output: string;
};
interface StorageItemResponse {
interface StorageItemResponseRpc {
key: string;

@@ -171,62 +213,17 @@ value?: string;

}
type OperationStorageItems = OperationEvent & {
type OperationStorageItemsRpc = OperationEventRpc & {
event: "operationStorageItems";
items: Array<StorageItemResponse>;
items: Array<StorageItemResponseRpc>;
};
type OperationStorageDone = OperationEvent & {
type OperationStorageDoneRpc = OperationEventRpc & {
event: "operationStorageDone";
};
type OperationEvents = OperationBodyDone | OperationCallDone | OperationStorageItems | OperationWaitingForContinue | OperationStorageDone | CommonOperationEvents;
type OperationEventsRpc = OperationBodyDoneRpc | OperationCallDoneRpc | OperationStorageItemsRpc | OperationWaitingForContinueRpc | OperationStorageDoneRpc | CommonOperationEventsRpc;
type FollowEvent = FollowEventWithRuntime | FollowEventWithoutRuntime | OperationEvents | Stop;
declare function getChainHead(request: ClientRequest<string, FollowEvent>): ChainHead;
type FollowEventRpc = FollowEventWithRuntimeRpc | FollowEventWithoutRuntimeRpc | OperationEventsRpc | StopRpc;
declare function getChainHead(request: ClientRequest<string, FollowEventRpc>): ChainHead;
interface TxValidated {
event: "validated";
}
interface TxBroadcasted {
event: "broadcasted";
numPeers: number;
}
interface TxBestChainBlockIncluded {
event: "bestChainBlockIncluded";
block: {
hash: string;
index: number;
} | null;
}
interface TxFinalized {
event: "finalized";
block: {
hash: string;
index: number;
};
}
interface TxInvalid {
event: "invalid";
error: string;
}
interface TxDropped {
event: "dropped";
broadcasted: boolean;
error: string;
}
interface TxError {
event: "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;
type ErrorEvents = TxDropped | TxInvalid | TxError;
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, TxEvent>) => Transaction;
declare const getTransaction: (request: ClientRequest<string, any>, rpcMethods: Promise<Set<string>> | Set<string>) => (tx: string, error: (e: Error) => void) => () => void;

@@ -236,6 +233,8 @@ interface SubstrateClient {

transaction: Transaction;
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, NewBlock, NewBlockWithRuntime, OperationError$1 as OperationError, OperationInaccessibleError, OperationLimitError, RpcError, Runtime, StopError, StorageResponse, 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, 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,47 +110,38 @@

// src/transaction/transaction.ts
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 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 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(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 () => {

@@ -204,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) => {

@@ -277,95 +263,102 @@ isOperationGoing = false;

// src/chainhead/storage-subscription.ts
var import_utils2 = require("@polkadot-api/utils");
var createStorageCb = (request) => (hash, inputs, childTrie, onItems, onError, onDone, onDiscardedItems) => {
if (inputs.length === 0) {
onDone();
return import_utils2.noop;
}
let cancel = request(
"chainHead_unstable_storage",
[hash, inputs, childTrie],
{
onSuccess: (response, followSubscription) => {
if (response.result === "limitReached" || response.discardedItems === inputs.length)
return onError(new OperationLimitError());
const doneListening = followSubscription(response.operationId, {
next: (event) => {
switch (event.event) {
case "operationStorageItems": {
onItems(event.items);
break;
}
case "operationStorageDone": {
_onDone();
break;
}
case "operationError": {
_onError(new OperationError(event.error));
break;
}
case "operationInaccessible": {
_onError(new OperationInaccessibleError());
break;
}
default:
request("chainHead_unstable_continue", []);
}
},
error: onError
});
cancel = () => {
doneListening();
request("chainHead_unstable_stopOperation", [response.operationId]);
};
const _onError = (e) => {
cancel = import_utils2.noop;
doneListening();
onError(e);
};
const _onDone = () => {
cancel = import_utils2.noop;
doneListening();
onDone();
};
onDiscardedItems(response.discardedItems);
},
onError
}
);
return () => {
cancel();
};
};
// src/chainhead/storage.ts
var createStorageFn = createOperationPromise(
"chainHead_unstable_storage",
(hash, query, childTrie) => {
const queries = {
value: new Set(query.value ?? []),
hash: new Set(query.hash ?? []),
closestDescendantMerkleValue: new Set(
query.closestDescendantMerkleValue ?? []
),
descendantsValues: new Set(query.descendantsValues ?? []),
descendantsHashes: new Set(query.descendantsHashes ?? [])
var createStorageFn = (request) => {
const cbStore = createStorageCb(request);
return abortablePromiseFn((resolve, reject, hash, type, key, childTrie) => {
const isDescendants = type.startsWith("descendants");
let result = isDescendants ? [] : null;
const onItems = isDescendants ? (items) => {
result.push(items);
} : (items) => {
result = items[0]?.[type];
};
const items = [];
query.value?.forEach((key) => {
items.push({
type: "value",
key
});
});
query.hash?.forEach((key) => {
items.push({
type: "hash",
key
});
});
query.descendantsValues?.forEach((key) => {
items.push({
type: "descendantsValues",
key
});
});
query.descendantsHashes?.forEach((key) => {
items.push({
type: "descendantsHashes",
key
});
});
queries["closestDescendantMerkleValue"]?.forEach((key) => {
items.push({
type: "closestDescendantMerkleValue",
key
});
});
const requestArgs = [hash, items, childTrie];
const result = {
values: {},
hashes: {},
closests: {},
descendantsHashes: {},
descendantsValues: {}
};
const resultBuilder = (e, res) => {
if (e.event === "operationStorageDone")
return res(result);
e.items.forEach((item) => {
if (item.value) {
if (queries.value.has(item.key)) {
result.values[item.key] = item.value;
} else {
const queriedKey = [...queries["descendantsValues"]].filter((key) => item.key.startsWith(key)).sort((a, b) => b.length - a.length)[0];
const values = result.descendantsValues[queriedKey] ?? [];
values.push({
key: item.key,
value: item.value
});
result.descendantsValues[queriedKey] = values;
}
const cancel = cbStore(
hash,
[{ key, type }],
childTrie ?? null,
onItems,
reject,
() => {
try {
resolve(isDescendants ? result.flat() : result);
} catch (e) {
reject(e);
}
if (item.hash) {
if (queries.hash.has(item.key)) {
result.hashes[item.key] = item.hash;
} else {
const queriedKey = [...queries["descendantsHashes"]].filter((key) => item.key.startsWith(key)).sort((a, b) => b.length - a.length)[0];
const hashes = result.descendantsHashes[queriedKey] ?? [];
hashes.push({
key: item.key,
hash: item.hash
});
result.descendantsHashes[queriedKey] = hashes;
}
},
(nDiscarded) => {
if (nDiscarded > 0) {
cancel();
reject(new OperationLimitError());
}
if (item["closestDescendantMerkleValue"] && queries["closestDescendantMerkleValue"].has(item.key)) {
result.closests[item.key] = item["closestDescendantMerkleValue"];
}
});
};
return [requestArgs, resultBuilder];
}
);
}
);
return cancel;
});
};
// 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], {

@@ -377,4 +370,12 @@ onSuccess() {

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

@@ -391,6 +392,18 @@ function isOperationEvent(event) {

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")
return onFollowEvent(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;
return onFollowEvent({ type, ...rest });
}
onFollowError(new StopError());

@@ -401,6 +414,6 @@ unfollow(false);

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

@@ -411,3 +424,3 @@ error: onAllFollowEventsError

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

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

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

@@ -441,3 +458,3 @@ deferredFollow.res(e);

disjoint();
return noop;
return noop2;
}

@@ -451,3 +468,3 @@ const onSubscription = (subscription) => {

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

@@ -476,3 +493,3 @@ subscriptions.subscribe(operationId, subscriber);

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

@@ -497,2 +514,3 @@ if (x instanceof Error)

storage: createStorageFn(fRequest),
storageSubscription: createStorageCb(fRequest),
unpin: createUnpinFn(fRequest),

@@ -517,10 +535,10 @@ _request: fRequest

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

@@ -537,3 +555,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) {

@@ -544,6 +563,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);
};

@@ -556,6 +576,7 @@ });

throw 0;
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);
}

@@ -567,43 +588,19 @@ } catch (e) {

}
function onStatusChange(e) {
if (e === "connected") {
queuedRequests.forEach((args, id) => {
process(id, ...args);
});
queuedRequests.clear();
}
state = e;
}
const connect = () => {
provider = gProvider(onMessage, onStatusChange);
provider.open();
};
connection = gProvider(onMessage);
const disconnect = () => {
provider?.close();
provider = null;
connection?.disconnect();
connection = null;
subscriptions.errorAll(new DestroyedError());
responses.forEach((r) => r.onError(new DestroyedError()));
responses.clear();
queuedRequests.clear();
subscriptions.errorAll(new Error("disconnected"));
};
const process = (id, ...args) => {
const [method, params, cb] = args;
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);
};
let nextId = 1;
const request = (method, params, cb) => {
if (!provider)
throw new Error("Not connected");
const id = nextId++;
if (state === "connected") {
process(id, method, params, cb);
} else {
queuedRequests.set(id, [method, params, cb]);
}
return () => {
if (queuedRequests.has(id)) {
queuedRequests.delete(id);
return;
}
responses.delete(id);

@@ -614,3 +611,2 @@ };

request,
connect,
disconnect

@@ -623,6 +619,19 @@ };

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(noop2);
return {
chainHead: getChainHead(client.request),
transaction: getTransaction(client.request),
transaction: getTransaction(
client.request,
rpcMethods
),
destroy: () => {
client.disconnect();
},
request,
_request: client.request

@@ -629,0 +638,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,22 @@ 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 {
key: string;
type: "value" | "hash" | "closestDescendantMerkleValue" | "descendantsValues" | "descendantsHashes";
}
interface StorageItemResponse {
key: string;
value?: string;
hash?: string;
closestDescendantMerkleValue?: string;
}
interface Runtime {

@@ -51,22 +69,22 @@ specName: string;

interface Initialized {
event: "initialized";
finalizedBlockHash: string;
type: "initialized";
finalizedBlockHashes: string[];
}
type InitializedWithRuntime = Initialized & {
type InitializedWithRuntime$1 = Initialized & {
finalizedBlockRuntime: Runtime;
};
interface NewBlock {
event: "newBlock";
type: "newBlock";
blockHash: string;
parentBlockHash: string;
}
type NewBlockWithRuntime = NewBlock & {
type NewBlockWithRuntime$1 = NewBlock & {
newRuntime: Runtime | null;
};
interface BestBlockChanged {
event: "bestBlockChanged";
type: "bestBlockChanged";
bestBlockHash: string;
}
interface Finalized {
event: "finalized";
type: "finalized";
finalizedBlockHashes: Array<string>;

@@ -76,17 +94,11 @@ prunedBlockHashes: Array<string>;

type CommonFollowEvents = BestBlockChanged | Finalized;
type FollowEventWithRuntime = InitializedWithRuntime | NewBlockWithRuntime | CommonFollowEvents;
type FollowEventWithRuntime = InitializedWithRuntime$1 | NewBlockWithRuntime$1 | CommonFollowEvents;
type FollowEventWithoutRuntime = Initialized | NewBlock | CommonFollowEvents;
interface StorageResponse {
values: Record<string, string>;
hashes: Record<string, string>;
closests: Record<string, string>;
descendantsValues: Record<string, Array<{
key: string;
value: string;
}>>;
descendantsHashes: Record<string, Array<{
key: string;
hash: string;
}>>;
}
type StorageResult<Input extends StorageItemInput["type"]> = Input extends "descendantsHashes" ? Array<{
key: string;
hash: string;
}> : Input extends "descendantsValues" ? Array<{
key: string;
value: string;
}> : string | null;
interface FollowResponse {

@@ -100,16 +112,7 @@ unfollow: UnsubscribeFn;

], string>;
storage: AbortablePromiseFn<[
hash: string,
query: Partial<{
value: Array<string>;
hash: Array<string>;
descendantsValues: Array<string>;
descendantsHashes: Array<string>;
closestDescendantMerkleValue: Array<string>;
}>,
childTrie: string | null
], StorageResponse>;
storage: <Type extends StorageItemInput["type"]>(hash: string, type: Type, key: string, childTrie: string | null, abortSignal?: AbortSignal | undefined) => Promise<StorageResult<Type>>;
storageSubscription: (hash: string, inputs: Array<StorageItemInput>, childTrie: string | null, onItems: (items: Array<StorageItemResponse>) => void, onError: (e: Error) => void, onDone: () => void, onDiscardedItems: (nDiscarded: number) => void) => () => void;
header: (hash: string) => Promise<string>;
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;
}

@@ -119,2 +122,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;
}

@@ -131,3 +135,3 @@

}
declare class OperationError$1 extends Error {
declare class OperationError extends Error {
constructor(error: string);

@@ -139,28 +143,66 @@ }

interface Stop {
interface RuntimeRpc {
specName: string;
implName: string;
specVersion: number;
implVersion: number;
transactionVersion: number;
apis: Record<string, number>;
}
type InitializedRpc = {
event: "initialized";
finalizedBlockHash: string;
} | {
event: "initialized";
finalizedBlockHashes: string[];
};
type InitializedWithRuntime = InitializedRpc & {
finalizedBlockRuntime: RuntimeRpc;
};
interface NewBlockRpc {
event: "newBlock";
blockHash: string;
parentBlockHash: string;
}
type NewBlockWithRuntime = NewBlockRpc & {
newRuntime: RuntimeRpc | null;
};
interface BestBlockChangedRpc {
event: "bestBlockChanged";
bestBlockHash: string;
}
interface FinalizedRpc {
event: "finalized";
finalizedBlockHashes: Array<string>;
prunedBlockHashes: Array<string>;
}
type CommonFollowEventsRpc = BestBlockChangedRpc | FinalizedRpc;
type FollowEventWithRuntimeRpc = InitializedWithRuntime | NewBlockWithRuntime | CommonFollowEventsRpc;
type FollowEventWithoutRuntimeRpc = InitializedRpc | NewBlockRpc | CommonFollowEventsRpc;
interface StopRpc {
event: "stop";
}
interface OperationEvent {
interface OperationEventRpc {
operationId: string;
}
type OperationWaitingForContinue = OperationEvent & {
type OperationWaitingForContinueRpc = OperationEventRpc & {
event: "operationWaitingForContinue";
};
type OperationInaccessible = OperationEvent & {
type OperationInaccessibleRpc = OperationEventRpc & {
event: "operationInaccessible";
};
type OperationError = OperationEvent & {
type OperationErrorRpc = OperationEventRpc & {
event: "operationError";
error: string;
};
type CommonOperationEvents = OperationInaccessible | OperationError;
type OperationBodyDone = OperationEvent & {
type CommonOperationEventsRpc = OperationInaccessibleRpc | OperationErrorRpc;
type OperationBodyDoneRpc = OperationEventRpc & {
event: "operationBodyDone";
value: Array<string>;
};
type OperationCallDone = OperationEvent & {
type OperationCallDoneRpc = OperationEventRpc & {
event: "operationCallDone";
output: string;
};
interface StorageItemResponse {
interface StorageItemResponseRpc {
key: string;

@@ -171,62 +213,17 @@ value?: string;

}
type OperationStorageItems = OperationEvent & {
type OperationStorageItemsRpc = OperationEventRpc & {
event: "operationStorageItems";
items: Array<StorageItemResponse>;
items: Array<StorageItemResponseRpc>;
};
type OperationStorageDone = OperationEvent & {
type OperationStorageDoneRpc = OperationEventRpc & {
event: "operationStorageDone";
};
type OperationEvents = OperationBodyDone | OperationCallDone | OperationStorageItems | OperationWaitingForContinue | OperationStorageDone | CommonOperationEvents;
type OperationEventsRpc = OperationBodyDoneRpc | OperationCallDoneRpc | OperationStorageItemsRpc | OperationWaitingForContinueRpc | OperationStorageDoneRpc | CommonOperationEventsRpc;
type FollowEvent = FollowEventWithRuntime | FollowEventWithoutRuntime | OperationEvents | Stop;
declare function getChainHead(request: ClientRequest<string, FollowEvent>): ChainHead;
type FollowEventRpc = FollowEventWithRuntimeRpc | FollowEventWithoutRuntimeRpc | OperationEventsRpc | StopRpc;
declare function getChainHead(request: ClientRequest<string, FollowEventRpc>): ChainHead;
interface TxValidated {
event: "validated";
}
interface TxBroadcasted {
event: "broadcasted";
numPeers: number;
}
interface TxBestChainBlockIncluded {
event: "bestChainBlockIncluded";
block: {
hash: string;
index: number;
} | null;
}
interface TxFinalized {
event: "finalized";
block: {
hash: string;
index: number;
};
}
interface TxInvalid {
event: "invalid";
error: string;
}
interface TxDropped {
event: "dropped";
broadcasted: boolean;
error: string;
}
interface TxError {
event: "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;
type ErrorEvents = TxDropped | TxInvalid | TxError;
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, TxEvent>) => Transaction;
declare const getTransaction: (request: ClientRequest<string, any>, rpcMethods: Promise<Set<string>> | Set<string>) => (tx: string, error: (e: Error) => void) => () => void;

@@ -236,6 +233,8 @@ interface SubstrateClient {

transaction: Transaction;
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, NewBlock, NewBlockWithRuntime, OperationError$1 as OperationError, OperationInaccessibleError, OperationLimitError, RpcError, Runtime, StopError, StorageResponse, 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, type UnsubscribeFn, createClient, getChainHead, getTransaction };

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

"use strict";var I=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var X=(r,e,t)=>e in r?I(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Y=(r,e)=>{for(var t in e)I(r,t,{get:e[t],enumerable:!0})},Z=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $(e))!Q.call(r,o)&&o!==t&&I(r,o,{get:()=>e[o],enumerable:!(n=K(e,o))||n.enumerable});return r};var ee=r=>Z(I({},"__esModule",{value:!0}),r);var C=(r,e,t)=>(X(r,typeof e!="symbol"?e+"":e,t),t);var se={};Y(se,{DisjointError:()=>x,OperationError:()=>A,OperationInaccessibleError:()=>P,OperationLimitError:()=>O,RpcError:()=>T,StopError:()=>F,TransactionError:()=>R,createClient:()=>oe});module.exports=ee(se);var D=class extends Error{constructor(){super("Aborted by AbortSignal"),this.name="AbortError"}},U=r=>(...e)=>new Promise((t,n)=>{let[o,m]=e[e.length-1]instanceof AbortSignal?[e.slice(0,e.length-1),e[e.length-1]]:[e],u=()=>{i(),n(new D)};m?.addEventListener("abort",u,{once:!0});let d=y=>c=>{m?.removeEventListener("abort",u),y(c)},i=r(d(t),d(n),...o)});function j(){let r=()=>{},e=()=>{};return{promise:new Promise((n,o)=>{r=n,e=o}),res:r,rej:e}}var E=()=>{};var _=()=>{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 re=new Set(["dropped","invalid","finalized","error"]);function te(r){return re.has(r.event)}var R=class extends Error{constructor(t){super(`TxError: ${t.event} - ${t.error}`);C(this,"type");C(this,"error");this.type=t.event,this.error=t.error,this.name="TransactionError"}},M=r=>(e,t,n)=>{let o=r("transaction_unstable_submitAndWatch",[e],{onSuccess:(m,u)=>{let d=u(m,{next:i=>{if(te(i)&&(d(),o=E,i.event!=="finalized"))return n(new R(i));t(i)},error(i){o(),o=E,n(i)}});o=()=>{d(),r("transaction_unstable_unwatch",[m])}},onError:n});return()=>{o()}};var F=class extends Error{constructor(){super("ChainHead stopped"),this.name="StopError"}},x=class extends Error{constructor(){super("ChainHead disjointed"),this.name="DisjointError"}},O=class extends Error{constructor(){super("ChainHead operations limit reached"),this.name="OperationLimitError"}},A=class extends Error{constructor(e){super(e),this.name="OperationError"}},P=class extends Error{constructor(){super("ChainHead operation inaccessible"),this.name="OperationInaccessibleError"}};var q=(r,e)=>t=>U((n,o,...m)=>{let[u,d]=e(...m),i=t(r,u,{onSuccess:(y,c)=>{if(y.result==="limitReached")return i=E,o(new O);let b=!0,f=E,h=a=>{b=!1,f(),n(a)},s=a=>{b=!1,f(),o(a)};f=c(y.operationId,{next:a=>{let l=a;l.event==="operationError"?o(new A(l.error)):l.event==="operationInaccessible"?o(new P):d(a,h,s)},error:s}),i=()=>{b&&(f(),t("chainHead_unstable_stopOperation",[y.operationId]))}},onError:o});return()=>{i()}});var B=q("chainHead_unstable_body",r=>[[r],(e,t)=>{t(e.value)}]);var G=q("chainHead_unstable_call",(r,e,t)=>[[r,e,t],(n,o)=>{o(n.output)}]);var N=r=>e=>new Promise((t,n)=>{r("chainHead_unstable_header",[e],{onSuccess:t,onError:n})});var L=q("chainHead_unstable_storage",(r,e,t)=>{let n={value:new Set(e.value??[]),hash:new Set(e.hash??[]),closestDescendantMerkleValue:new Set(e.closestDescendantMerkleValue??[]),descendantsValues:new Set(e.descendantsValues??[]),descendantsHashes:new Set(e.descendantsHashes??[])},o=[];e.value?.forEach(i=>{o.push({type:"value",key:i})}),e.hash?.forEach(i=>{o.push({type:"hash",key:i})}),e.descendantsValues?.forEach(i=>{o.push({type:"descendantsValues",key:i})}),e.descendantsHashes?.forEach(i=>{o.push({type:"descendantsHashes",key:i})}),n.closestDescendantMerkleValue?.forEach(i=>{o.push({type:"closestDescendantMerkleValue",key:i})});let m=[r,o,t],u={values:{},hashes:{},closests:{},descendantsHashes:{},descendantsValues:{}};return[m,(i,y)=>{if(i.event==="operationStorageDone")return y(u);i.items.forEach(c=>{if(c.value)if(n.value.has(c.key))u.values[c.key]=c.value;else{let b=[...n.descendantsValues].filter(h=>c.key.startsWith(h)).sort((h,s)=>s.length-h.length)[0],f=u.descendantsValues[b]??[];f.push({key:c.key,value:c.value}),u.descendantsValues[b]=f}if(c.hash)if(n.hash.has(c.key))u.hashes[c.key]=c.hash;else{let b=[...n.descendantsHashes].filter(h=>c.key.startsWith(h)).sort((h,s)=>s.length-h.length)[0],f=u.descendantsHashes[b]??[];f.push({key:c.key,hash:c.hash}),u.descendantsHashes[b]=f}c.closestDescendantMerkleValue&&n.closestDescendantMerkleValue.has(c.key)&&(u.closests[c.key]=c.closestDescendantMerkleValue)})}]});var z=r=>e=>new Promise((t,n)=>{r("chainHead_unstable_unpin",[e],{onSuccess(){t()},onError:n})});function ne(r){return r.operationId!==void 0}function V(r){return(e,t,n)=>{let o=_(),m=new Set,u=j(),d=u.promise,i=s=>{if(ne(s))return o.next(s.operationId,s);if(s.event!=="stop")return t(s);n(new F),f(!1)},y=s=>{n(s),f()},f=r("chainHead_unstable_follow",[e],{onSuccess:(s,a)=>{let l=a(s,{next:i,error:y});f=(p=!0)=>{d=null,f=E,l(),p&&r("chainHead_unstable_unfollow",[s]),o.errorAll(new x),m.forEach(v=>{v()}),m.clear()},d=s,u.res(s)},onError:s=>{n(s),d=null,u.res(s)}}),h=(s,a,l)=>{let p=()=>{l?.onError(new x)};if(d===null)return p(),E;let v=g=>{if(!l)return r(s,[g,...a]);m.add(p);let H=(w,W)=>d===null?(W.error(new x),E):(o.subscribe(w,W),()=>{o.unsubscribe(w)}),k=r(s,[g,...a],{onSuccess:w=>{m.delete(p),l.onSuccess(w,H)},onError:w=>{m.delete(p),l.onError(w)}});return()=>{m.delete(p),k()}};if(typeof d=="string")return v(d);let S=E;return d.then(g=>{if(g instanceof Error)return p();d&&(S=v(g))}),()=>{S()}};return{unfollow(){f(),d=null},body:B(h),call:G(h),header:N(h),storage:L(h),unpin:z(h),_request:h}}}var T=class extends Error{constructor(t){super(t.message);C(this,"code");C(this,"data");this.code=t.code,this.data=t.data,this.name="RpcError"}};var J=r=>{let e=new Map,t=_(),n=new Map,o=null,m="disconnected",u=(s,a,l)=>{o.send(JSON.stringify({jsonrpc:"2.0",id:s,method:a,params:l}))};function d(s){try{let a,l,p,v,S;if({id:a,result:l,error:p,params:v}=JSON.parse(s),a){let g=e.get(a);return g?(e.delete(a),p?g.onError(new T(p)):g.onSuccess(l,(H,k)=>(t.subscribe(H,k),()=>{t.unsubscribe(H)}))):void 0}if({subscription:S,result:l,error:p}=v,!S||!p&&!Object.hasOwn(v,"result"))throw 0;p?t.error(S,new T(p)):t.next(S,l)}catch(a){console.warn("Error parsing incomming message: "+s),console.error(a)}}function i(s){s==="connected"&&(n.forEach((a,l)=>{b(l,...a)}),n.clear()),m=s}let y=()=>{o=r(d,i),o.open()},c=()=>{o?.close(),o=null,e.clear(),n.clear(),t.errorAll(new Error("disconnected"))},b=(s,...a)=>{let[l,p,v]=a;v&&e.set(s,v),u(s,l,p)},f=1;return{request:(s,a,l)=>{if(!o)throw new Error("Not connected");let p=f++;return m==="connected"?b(p,s,a,l):n.set(p,[s,a,l]),()=>{if(n.has(p)){n.delete(p);return}e.delete(p)}},connect:y,disconnect:c}};var oe=r=>{let e=J(r);return e.connect(),{chainHead:V(e.request),transaction:M(e.request),_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,()=>{try{t(m?d.flat():d)}catch(s){n(s)}},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 U(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,j)=>a===null?(j.error(new S),g):(o.subscribe(F,j),()=>{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:U(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-587a50d366fe387ce869c46a060d184215af2f4e.1.0",
"version": "0.0.1-5a0915fac7774b8a002e2bd58e977d732739cbe0.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-587a50d366fe387ce869c46a060d184215af2f4e.1.0",
"@polkadot-api/utils": "0.0.1-587a50d366fe387ce869c46a060d184215af2f4e.1.0"
"@polkadot-api/json-rpc-provider": "0.0.1-5a0915fac7774b8a002e2bd58e977d732739cbe0.1.0",
"@polkadot-api/utils": "0.0.1-5a0915fac7774b8a002e2bd58e977d732739cbe0.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