@polkadot-api/substrate-client
Advanced tools
Comparing version 0.0.1-b93545aad989f8c380fb1d4764731b59fd1d692d.1.0 to 0.0.1-b95115e314039199595018979c6d5c177dd28c00.1.0
@@ -1,3 +0,2 @@ | ||
import { ConnectProvider } from '@polkadot-api/json-rpc-provider'; | ||
export { ConnectProvider, Provider } from '@polkadot-api/json-rpc-provider'; | ||
import { JsonRpcProvider } from '@polkadot-api/json-rpc-provider'; | ||
@@ -27,3 +26,3 @@ interface IRpcError { | ||
type FollowSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type FollowSubscriptionCb<T> = (methodName: string, subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientRequestCb<T, TT> = { | ||
@@ -39,2 +38,12 @@ onSuccess: (result: T, followSubscription: FollowSubscriptionCb<TT>) => void; | ||
declare class DestroyedError extends Error { | ||
constructor(); | ||
} | ||
type FollowInnerSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientInnerRequestCb<T, TT> = { | ||
onSuccess: (result: T, followSubscription: FollowInnerSubscriptionCb<TT>) => void; | ||
onError: (e: Error) => void; | ||
}; | ||
type ClientInnerRequest<T, TT> = (method: string, params: Array<any>, cb?: ClientInnerRequestCb<T, TT>) => UnsubscribeFn; | ||
interface StorageItemInput { | ||
@@ -60,3 +69,3 @@ key: string; | ||
type: "initialized"; | ||
finalizedBlockHash: string; | ||
finalizedBlockHashes: string[]; | ||
} | ||
@@ -105,3 +114,3 @@ type InitializedWithRuntime$1 = Initialized & { | ||
unpin: (hashes: Array<string>) => Promise<void>; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientInnerRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
} | ||
@@ -111,2 +120,3 @@ interface ChainHead { | ||
(withRuntime: true, cb: (event: FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
(withRuntime: boolean, cb: (event: FollowEventWithoutRuntime | FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
} | ||
@@ -138,6 +148,9 @@ | ||
} | ||
interface InitializedRpc { | ||
type InitializedRpc = { | ||
event: "initialized"; | ||
finalizedBlockHash: string; | ||
} | ||
} | { | ||
event: "initialized"; | ||
finalizedBlockHashes: string[]; | ||
}; | ||
type InitializedWithRuntime = InitializedRpc & { | ||
@@ -292,3 +305,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; | ||
@@ -299,6 +312,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: ConnectProvider) => SubstrateClient; | ||
declare const createClient: (provider: JsonRpcProvider) => SubstrateClient; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientRequest, type ClientRequestCb, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction }; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientInnerRequest, type ClientInnerRequestCb, type ClientRequest, type ClientRequestCb, DestroyedError, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowInnerSubscriptionCb, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, 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,91 +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(); | ||
let provider = null; | ||
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); | ||
} | ||
} | ||
provider = gProvider(onMessage); | ||
const disconnect = () => { | ||
provider?.disconnect(); | ||
provider = null; | ||
}; | ||
let nextId = 1; | ||
const request = (method, params, cb) => { | ||
if (!provider) | ||
throw new Error("Not connected"); | ||
const id = nextId++; | ||
if (cb) | ||
responses.set(id, cb); | ||
send(id, method, params); | ||
return () => { | ||
responses.delete(id); | ||
}; | ||
}; | ||
return { | ||
request, | ||
disconnect | ||
}; | ||
}; | ||
// src/index.ts | ||
var import_utils3 = require("@polkadot-api/utils"); | ||
var createClient2 = (provider) => { | ||
const client = createClient(provider); | ||
const request = abortablePromiseFn( | ||
(onSuccess, onError, method, params) => client.request(method, params, { onSuccess, onError }) | ||
); | ||
let rpcMethods = request("rpc_methods", []).then( | ||
(x) => rpcMethods = new Set(Array.isArray(x) ? x : x.methods) | ||
); | ||
rpcMethods.catch(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 | ||
@@ -607,0 +676,0 @@ }; |
@@ -1,3 +0,2 @@ | ||
import { ConnectProvider } from '@polkadot-api/json-rpc-provider'; | ||
export { ConnectProvider, Provider } from '@polkadot-api/json-rpc-provider'; | ||
import { JsonRpcProvider } from '@polkadot-api/json-rpc-provider'; | ||
@@ -27,3 +26,3 @@ interface IRpcError { | ||
type FollowSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type FollowSubscriptionCb<T> = (methodName: string, subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientRequestCb<T, TT> = { | ||
@@ -39,2 +38,12 @@ onSuccess: (result: T, followSubscription: FollowSubscriptionCb<TT>) => void; | ||
declare class DestroyedError extends Error { | ||
constructor(); | ||
} | ||
type FollowInnerSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientInnerRequestCb<T, TT> = { | ||
onSuccess: (result: T, followSubscription: FollowInnerSubscriptionCb<TT>) => void; | ||
onError: (e: Error) => void; | ||
}; | ||
type ClientInnerRequest<T, TT> = (method: string, params: Array<any>, cb?: ClientInnerRequestCb<T, TT>) => UnsubscribeFn; | ||
interface StorageItemInput { | ||
@@ -60,3 +69,3 @@ key: string; | ||
type: "initialized"; | ||
finalizedBlockHash: string; | ||
finalizedBlockHashes: string[]; | ||
} | ||
@@ -105,3 +114,3 @@ type InitializedWithRuntime$1 = Initialized & { | ||
unpin: (hashes: Array<string>) => Promise<void>; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientInnerRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
} | ||
@@ -111,2 +120,3 @@ interface ChainHead { | ||
(withRuntime: true, cb: (event: FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
(withRuntime: boolean, cb: (event: FollowEventWithoutRuntime | FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
} | ||
@@ -138,6 +148,9 @@ | ||
} | ||
interface InitializedRpc { | ||
type InitializedRpc = { | ||
event: "initialized"; | ||
finalizedBlockHash: string; | ||
} | ||
} | { | ||
event: "initialized"; | ||
finalizedBlockHashes: string[]; | ||
}; | ||
type InitializedWithRuntime = InitializedRpc & { | ||
@@ -292,3 +305,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; | ||
@@ -299,6 +312,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: ConnectProvider) => SubstrateClient; | ||
declare const createClient: (provider: JsonRpcProvider) => SubstrateClient; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientRequest, type ClientRequestCb, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction }; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientInnerRequest, type ClientInnerRequestCb, type ClientRequest, type ClientRequestCb, DestroyedError, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowInnerSubscriptionCb, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, 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 I=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var Z=(r,e,t)=>e in r?I(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ee=(r,e)=>{for(var t in e)I(r,t,{get:e[t],enumerable:!0})},re=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of X(e))!Y.call(r,n)&&n!==t&&I(r,n,{get:()=>e[n],enumerable:!(o=V(e,n))||o.enumerable});return r};var te=r=>re(I({},"__esModule",{value:!0}),r);var S=(r,e,t)=>(Z(r,typeof e!="symbol"?e+"":e,t),t);var ce={};ee(ce,{DisjointError:()=>y,OperationError:()=>x,OperationInaccessibleError:()=>T,OperationLimitError:()=>g,RpcError:()=>C,StopError:()=>O,TransactionError:()=>w,createClient:()=>ae});module.exports=te(ce);var W=class extends Error{constructor(){super("Aborted by AbortSignal"),this.name="AbortError"}},_=r=>(...e)=>new Promise((t,o)=>{let[n,a]=e[e.length-1]instanceof AbortSignal?[e.slice(0,e.length-1),e[e.length-1]]:[e],d=()=>{l(),o(new W)};a?.addEventListener("abort",d,{once:!0});let c=p=>m=>{a?.removeEventListener("abort",d),p(m)},l=r(c(t),c(o),...n)});function k(){let r=()=>{},e=()=>{};return{promise:new Promise((o,n)=>{r=o,e=n}),res:r,rej:e}}var E=()=>{};var A=()=>{let r=new Map;return{has:r.has.bind(r),subscribe(e,t){r.set(e,t)},unsubscribe(e){r.delete(e)},next(e,t){r.get(e)?.next(t)},error(e,t){let o=r.get(e);o&&(r.delete(e),o.error(t))},errorAll(e){let t=[...r.values()];r.clear(),t.forEach(o=>{o.error(e)})}}};var oe=r=>{let{event:e,...t}=r;return{type:e,...t}},ne=new Set(["dropped","invalid","finalized","error"]);function ie(r){return ne.has(r.event)}var w=class extends Error{constructor(t){super(`TxError: ${t.event} - ${t.error}`);S(this,"type");S(this,"error");this.type=t.event,this.error=t.error,this.name="TransactionError"}},L=r=>(e,t,o)=>{let n=r("transaction_unstable_submitAndWatch",[e],{onSuccess:(a,d)=>{let c=d(a,{next:l=>{if(ie(l)&&(c(),n=E,l.event!=="finalized"))return o(new w(l));t(oe(l))},error(l){n(),n=E,o(l)}});n=()=>{c(),r("transaction_unstable_unwatch",[a])}},onError:o});return()=>{n()}};var O=class extends Error{constructor(){super("ChainHead stopped"),this.name="StopError"}},y=class extends Error{constructor(){super("ChainHead disjointed"),this.name="DisjointError"}},g=class extends Error{constructor(){super("ChainHead operations limit reached"),this.name="OperationLimitError"}},x=class extends Error{constructor(e){super(e),this.name="OperationError"}},T=class extends Error{constructor(){super("ChainHead operation inaccessible"),this.name="OperationInaccessibleError"}};var P=(r,e)=>t=>_((o,n,...a)=>{let[d,c]=e(...a),l=t(r,d,{onSuccess:(p,m)=>{if(p.result==="limitReached")return l=E,n(new g);let u=!0,s=E,R=b=>{u=!1,s(),o(b)},i=b=>{u=!1,s(),n(b)};s=m(p.operationId,{next:b=>{let f=b;f.event==="operationError"?n(new x(f.error)):f.event==="operationInaccessible"?n(new T):c(b,R,i)},error:i}),l=()=>{u&&(s(),t("chainHead_unstable_stopOperation",[p.operationId]))}},onError:n});return()=>{l()}});var N=P("chainHead_unstable_body",r=>[[r],(e,t)=>{t(e.value)}]);var z=P("chainHead_unstable_call",(r,e,t)=>[[r,e,t],(o,n)=>{n(o.output)}]);var B=r=>e=>new Promise((t,o)=>{r("chainHead_unstable_header",[e],{onSuccess:t,onError:o})});var H=require("@polkadot-api/utils");var D=r=>(e,t,o,n,a,d,c)=>{if(t.length===0)return d(),H.noop;let l=r("chainHead_unstable_storage",[e,t,o],{onSuccess:(p,m)=>{if(p.result==="limitReached"||p.discardedItems===t.length)return a(new g);let u=m(p.operationId,{next:i=>{switch(i.event){case"operationStorageItems":{n(i.items);break}case"operationStorageDone":{R();break}case"operationError":{s(new x(i.error));break}case"operationInaccessible":{s(new T);break}default:r("chainHead_unstable_continue",[])}},error:a});l=()=>{u(),r("chainHead_unstable_stopOperation",[p.operationId])};let s=i=>{l=H.noop,u(),a(i)},R=()=>{l=H.noop,u(),d()};c(p.discardedItems)},onError:a});return()=>{l()}};var J=r=>{let e=D(r);return _((t,o,n,a,d,c)=>{let l=a.startsWith("descendants"),p=l?[]:null,u=e(n,[{key:d,type:a}],c??null,l?s=>{p.push(...s)}:s=>{p=s[0]?.[a]},o,()=>{t(p)},s=>{s>0&&(u(),o(new g))});return u})};var $=r=>e=>new Promise((t,o)=>{r("chainHead_unstable_unpin",[e],{onSuccess(){t()},onError:o})});function se(r){return r.operationId!==void 0}function j(r){return(e,t,o)=>{let n=A(),a=new Set,d=k(),c=d.promise,l=i=>{if(se(i))return n.next(i.operationId,i);if(i.event!=="stop"){let{event:b,...f}=i;return t({type:b,...f})}o(new O),s(!1)},p=i=>{o(i),s()},s=r("chainHead_unstable_follow",[e],{onSuccess:(i,b)=>{let f=b(i,{next:l,error:p});s=(v=!0)=>{c=null,s=E,f(),v&&r("chainHead_unstable_unfollow",[i]),n.errorAll(new y),a.forEach(q=>{q()}),a.clear()},c=i,d.res(i)},onError:i=>{o(i),c=null,d.res(i)}}),R=(i,b,f)=>{let v=()=>{f?.onError(new y)};if(c===null)return v(),E;let q=F=>{if(!f)return r(i,[F,...b]);a.add(v);let K=(h,M)=>c===null?(M.error(new y),E):(n.subscribe(h,M),()=>{n.unsubscribe(h)}),Q=r(i,[F,...b],{onSuccess:h=>{a.delete(v),f.onSuccess(h,K)},onError:h=>{a.delete(v),f.onError(h)}});return()=>{a.delete(v),Q()}};if(typeof c=="string")return q(c);let U=E;return c.then(F=>{if(F instanceof Error)return v();c&&(U=q(F))}),()=>{U()}};return{unfollow(){s(),c=null},body:N(R),call:z(R),header:B(R),storage:J(R),storageSubscription:D(R),unpin:$(R),_request:R}}}var C=class extends Error{constructor(t){super(t.message);S(this,"code");S(this,"data");this.code=t.code,this.data=t.data,this.name="RpcError"}};var G=r=>{let e=new Map,t=A(),o=null,n=(p,m,u)=>{o.send(JSON.stringify({jsonrpc:"2.0",id:p,method:m,params:u}))};function a(p){try{let m,u,s,R,i;if({id:m,result:u,error:s,params:R}=JSON.parse(p),m){let b=e.get(m);return b?(e.delete(m),s?b.onError(new C(s)):b.onSuccess(u,(f,v)=>(t.subscribe(f,v),()=>{t.unsubscribe(f)}))):void 0}if({subscription:i,result:u,error:s}=R,!i||!s&&!Object.hasOwn(R,"result"))throw 0;s?t.error(i,new C(s)):t.next(i,u)}catch(m){console.warn("Error parsing incomming message: "+p),console.error(m)}}o=r(a);let d=()=>{o?.disconnect(),o=null},c=1;return{request:(p,m,u)=>{if(!o)throw new Error("Not connected");let s=c++;return u&&e.set(s,u),n(s,p,m),()=>{e.delete(s)}},disconnect:d}};var ae=r=>{let e=G(r);return{chainHead:j(e.request),transaction:L(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-b93545aad989f8c380fb1d4764731b59fd1d692d.1.0", | ||
"version": "0.0.1-b95115e314039199595018979c6d5c177dd28c00.1.0", | ||
"author": "Josep M Sobrepere (https://github.com/josepot)", | ||
@@ -43,5 +43,4 @@ "repository": { | ||
"devDependencies": { | ||
"@vitest/coverage-v8": "^0.34.3", | ||
"@polkadot-api/json-rpc-provider": "0.0.1-b93545aad989f8c380fb1d4764731b59fd1d692d.1.0", | ||
"@polkadot-api/utils": "0.0.1-b93545aad989f8c380fb1d4764731b59fd1d692d.1.0" | ||
"@polkadot-api/utils": "0.0.1-b95115e314039199595018979c6d5c177dd28c00.1.0", | ||
"@polkadot-api/json-rpc-provider": "0.0.1-b95115e314039199595018979c6d5c177dd28c00.1.0" | ||
}, | ||
@@ -48,0 +47,0 @@ "scripts": { |
210
README.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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
205606
2
1884
212