@polkadot-api/substrate-client
Advanced tools
Comparing version 0.0.1-c9489f3d99902b9f2fb0c041d6742c10ba614f0e.1.0 to 0.0.1-c9bb2ce3de90b7b5745189b6e3258c7cd945bb40.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 & { | ||
@@ -209,87 +222,6 @@ finalizedBlockRuntime: RuntimeRpc; | ||
interface TxValidated { | ||
type: "validated"; | ||
} | ||
interface TxBroadcasted { | ||
type: "broadcasted"; | ||
numPeers: number; | ||
} | ||
interface TxBestChainBlockIncluded { | ||
type: "bestChainBlockIncluded"; | ||
block: { | ||
hash: string; | ||
index: number; | ||
} | null; | ||
} | ||
interface TxFinalized { | ||
type: "finalized"; | ||
block: { | ||
hash: string; | ||
index: number; | ||
}; | ||
} | ||
interface TxInvalid { | ||
type: "invalid"; | ||
error: string; | ||
} | ||
interface TxDropped { | ||
type: "dropped"; | ||
broadcasted: boolean; | ||
error: string; | ||
} | ||
interface TxError { | ||
type: "error"; | ||
error: string; | ||
} | ||
type TxEvent = TxValidated | TxBroadcasted | TxBestChainBlockIncluded | TxFinalized | TxInvalid | TxDropped | TxError; | ||
type Transaction = (tx: string, next: (event: TxEvent) => void, error: (e: Error) => void) => UnsubscribeFn; | ||
type Transaction = (tx: string, error: (e: Error) => void) => UnsubscribeFn; | ||
interface TxValidatedRpc { | ||
event: "validated"; | ||
} | ||
interface TxBroadcastedRpc { | ||
event: "broadcasted"; | ||
numPeers: number; | ||
} | ||
interface TxBestChainBlockIncludedRpc { | ||
event: "bestChainBlockIncluded"; | ||
block: { | ||
hash: string; | ||
index: number; | ||
} | null; | ||
} | ||
interface TxFinalizedRpc { | ||
event: "finalized"; | ||
block: { | ||
hash: string; | ||
index: number; | ||
}; | ||
} | ||
interface TxInvalidRpc { | ||
event: "invalid"; | ||
error: string; | ||
} | ||
interface TxDroppedRpc { | ||
event: "dropped"; | ||
broadcasted: boolean; | ||
error: string; | ||
} | ||
interface TxErrorRpc { | ||
event: "error"; | ||
error: string; | ||
} | ||
type TxEventRpc = TxValidatedRpc | TxBroadcastedRpc | TxBestChainBlockIncludedRpc | TxFinalizedRpc | TxInvalidRpc | TxDroppedRpc | TxErrorRpc; | ||
declare const getTransaction: (request: ClientRequest<string, any>, rpcMethods: Promise<Set<string>> | Set<string>) => (tx: string, error: (e: Error) => void) => () => void; | ||
type ErrorEvents = TxDroppedRpc | TxInvalidRpc | TxErrorRpc; | ||
interface ITxError { | ||
type: ErrorEvents["event"]; | ||
error: string; | ||
} | ||
declare class TransactionError extends Error implements ITxError { | ||
type: "error" | "invalid" | "dropped"; | ||
error: string; | ||
constructor(e: ErrorEvents); | ||
} | ||
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => Transaction; | ||
interface SubstrateClient { | ||
@@ -299,6 +231,7 @@ chainHead: ChainHead; | ||
destroy: UnsubscribeFn; | ||
request: <T>(method: string, params: any[], abortSignal?: AbortSignal) => Promise<T>; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
} | ||
declare const createClient: (provider: ConnectProvider) => SubstrateClient; | ||
declare const createClient: (provider: JsonRpcProvider) => SubstrateClient; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientRequest, type ClientRequestCb, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction }; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientInnerRequest, type ClientInnerRequestCb, type ClientRequest, type ClientRequestCb, DestroyedError, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowInnerSubscriptionCb, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, type UnsubscribeFn, createClient, getChainHead, getTransaction }; |
@@ -28,2 +28,3 @@ "use strict"; | ||
__export(src_exports, { | ||
DestroyedError: () => DestroyedError, | ||
DisjointError: () => DisjointError, | ||
@@ -35,3 +36,2 @@ OperationError: () => OperationError, | ||
StopError: () => StopError, | ||
TransactionError: () => TransactionError, | ||
createClient: () => createClient2 | ||
@@ -42,22 +42,17 @@ }); | ||
// src/internal-utils/abortablePromiseFn.ts | ||
var AbortError = class extends Error { | ||
constructor() { | ||
super("Aborted by AbortSignal"); | ||
this.name = "AbortError"; | ||
} | ||
}; | ||
var import_utils = require("@polkadot-api/utils"); | ||
var abortablePromiseFn = (fn) => (...args) => new Promise((res, rej) => { | ||
let cancel = import_utils.noop; | ||
const [actualArgs, abortSignal] = args[args.length - 1] instanceof AbortSignal ? [args.slice(0, args.length - 1), args[args.length - 1]] : [args]; | ||
const onAbort = () => { | ||
cancel(); | ||
rej(new AbortError()); | ||
rej(new import_utils.AbortError()); | ||
}; | ||
abortSignal?.addEventListener("abort", onAbort, { once: true }); | ||
const removeAbortListener = (fn2) => (x) => { | ||
const withCleanup = (fn2) => (x) => { | ||
cancel = import_utils.noop; | ||
abortSignal?.removeEventListener("abort", onAbort); | ||
fn2(x); | ||
}; | ||
const cancel = fn( | ||
...[removeAbortListener(res), removeAbortListener(rej), ...actualArgs] | ||
); | ||
cancel = fn(...[withCleanup(res), withCleanup(rej), ...actualArgs]); | ||
}); | ||
@@ -79,3 +74,3 @@ | ||
// src/internal-utils/noop.ts | ||
var noop = () => { | ||
var noop2 = () => { | ||
}; | ||
@@ -115,51 +110,38 @@ | ||
// src/transaction/transaction.ts | ||
var eventToType = (input) => { | ||
const { event: type, ...rest } = input; | ||
return { type, ...rest }; | ||
var getTxBroadcastNames = (input) => { | ||
if (input.has("transaction_v1_broadcast")) | ||
return ["transaction_v1_broadcast", "transaction_v1_stop"]; | ||
if (input.has("transactionWatch_unstable_submitAndWatch")) | ||
return [ | ||
"transactionWatch_unstable_submitAndWatch", | ||
"transactionWatch_unstable_unwatch" | ||
]; | ||
return ["transaction_unstable_submitAndWatch", "transaction_unstable_unwatch"]; | ||
}; | ||
var terminalEvents = /* @__PURE__ */ new Set([ | ||
"dropped", | ||
"invalid", | ||
"finalized", | ||
"error" | ||
]); | ||
function isTerminalEvent(event) { | ||
return terminalEvents.has(event.event); | ||
} | ||
var TransactionError = class extends Error { | ||
constructor(e) { | ||
super(`TxError: ${e.event} - ${e.error}`); | ||
__publicField(this, "type"); | ||
__publicField(this, "error"); | ||
this.type = e.event; | ||
this.error = e.error; | ||
this.name = "TransactionError"; | ||
} | ||
}; | ||
var getTransaction = (request) => (tx, next, error) => { | ||
let cancel = request("transaction_unstable_submitAndWatch", [tx], { | ||
onSuccess: (subscriptionId, follow) => { | ||
const done = follow(subscriptionId, { | ||
next: (event) => { | ||
if (isTerminalEvent(event)) { | ||
done(); | ||
cancel = noop; | ||
if (event.event !== "finalized") | ||
return error(new TransactionError(event)); | ||
} | ||
next(eventToType(event)); | ||
}, | ||
error(e) { | ||
cancel(); | ||
cancel = noop; | ||
error(e); | ||
} | ||
}); | ||
cancel = () => { | ||
done(); | ||
request("transaction_unstable_unwatch", [subscriptionId]); | ||
var getTransaction = (request, rpcMethods) => (tx, error) => { | ||
const broadcast = (tx2, broadcastFn, cancelBroadcastFn) => request(broadcastFn, [tx2], { | ||
onSuccess: (subscriptionId) => { | ||
cancel = subscriptionId === null ? noop2 : () => { | ||
request(cancelBroadcastFn, [subscriptionId]); | ||
}; | ||
if (subscriptionId === null) { | ||
error( | ||
new Error("Max # of broadcasted transactions has been reached") | ||
); | ||
} | ||
}, | ||
onError: error | ||
}); | ||
let isActive = true; | ||
let cancel = () => { | ||
isActive = false; | ||
}; | ||
if (rpcMethods instanceof Promise) { | ||
rpcMethods.then(getTxBroadcastNames).then((names) => { | ||
if (!isActive) | ||
return; | ||
cancel = broadcast(tx, ...names); | ||
}); | ||
} else | ||
cancel = broadcast(tx, ...getTxBroadcastNames(rpcMethods)); | ||
return () => { | ||
@@ -208,7 +190,7 @@ cancel(); | ||
if (response.result === "limitReached") { | ||
cancel = noop; | ||
cancel = noop2; | ||
return rej(new OperationLimitError()); | ||
} | ||
let isOperationGoing = true; | ||
let done = noop; | ||
let done = noop2; | ||
const _res = (x) => { | ||
@@ -282,7 +264,7 @@ isOperationGoing = false; | ||
// src/chainhead/storage-subscription.ts | ||
var import_utils = require("@polkadot-api/utils"); | ||
var import_utils2 = require("@polkadot-api/utils"); | ||
var createStorageCb = (request) => (hash, inputs, childTrie, onItems, onError, onDone, onDiscardedItems) => { | ||
if (inputs.length === 0) { | ||
onDone(); | ||
return import_utils.noop; | ||
return import_utils2.noop; | ||
} | ||
@@ -326,3 +308,3 @@ let cancel = request( | ||
const _onError = (e) => { | ||
cancel = import_utils.noop; | ||
cancel = import_utils2.noop; | ||
doneListening(); | ||
@@ -332,3 +314,3 @@ onError(e); | ||
const _onDone = () => { | ||
cancel = import_utils.noop; | ||
cancel = import_utils2.noop; | ||
doneListening(); | ||
@@ -354,3 +336,3 @@ onDone(); | ||
const onItems = isDescendants ? (items) => { | ||
result.push(...items); | ||
result.push(items); | ||
} : (items) => { | ||
@@ -366,3 +348,7 @@ result = items[0]?.[type]; | ||
() => { | ||
resolve(result); | ||
try { | ||
resolve(isDescendants ? result.flat() : result); | ||
} catch (e) { | ||
reject(e); | ||
} | ||
}, | ||
@@ -381,3 +367,3 @@ (nDiscarded) => { | ||
// 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], { | ||
@@ -389,4 +375,12 @@ onSuccess() { | ||
}); | ||
}); | ||
}) : Promise.resolve(); | ||
// src/client/DestroyedError.ts | ||
var DestroyedError = class extends Error { | ||
constructor() { | ||
super("Client destroyed"); | ||
this.name = "DestroyedError"; | ||
} | ||
}; | ||
// src/chainhead/chainhead.ts | ||
@@ -403,5 +397,15 @@ 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") { | ||
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; | ||
@@ -415,6 +419,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, | ||
@@ -425,3 +429,3 @@ error: onAllFollowEventsError | ||
followSubscription = null; | ||
unfollow = noop; | ||
unfollow = noop2; | ||
done(); | ||
@@ -439,3 +443,7 @@ sendUnfollow && request("chainHead_unstable_unfollow", [subscriptionId]); | ||
const onFollowRequestError = (e) => { | ||
onFollowError(e); | ||
if (e instanceof DestroyedError) { | ||
unfollow(false); | ||
} else { | ||
onFollowError(e); | ||
} | ||
followSubscription = null; | ||
@@ -455,3 +463,3 @@ deferredFollow.res(e); | ||
disjoint(); | ||
return noop; | ||
return noop2; | ||
} | ||
@@ -465,3 +473,3 @@ const onSubscription = (subscription) => { | ||
subscriber.error(new DisjointError()); | ||
return noop; | ||
return noop2; | ||
} | ||
@@ -490,3 +498,3 @@ subscriptions.subscribe(operationId, subscriber); | ||
return onSubscription(followSubscription); | ||
let onCancel = noop; | ||
let onCancel = noop2; | ||
followSubscription.then((x) => { | ||
@@ -531,8 +539,10 @@ if (x instanceof Error) | ||
// src/client/createClient.ts | ||
var nextClientId = 1; | ||
var createClient = (gProvider) => { | ||
let clientId = nextClientId++; | ||
const responses = /* @__PURE__ */ new Map(); | ||
const subscriptions = getSubscriptionsManager(); | ||
let provider = null; | ||
let connection = null; | ||
const send = (id, method, params) => { | ||
provider.send( | ||
connection.send( | ||
JSON.stringify({ | ||
@@ -549,3 +559,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) { | ||
@@ -556,6 +567,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); | ||
}; | ||
@@ -568,6 +580,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); | ||
} | ||
@@ -579,12 +592,15 @@ } catch (e) { | ||
} | ||
provider = gProvider(onMessage); | ||
connection = gProvider(onMessage); | ||
const disconnect = () => { | ||
provider?.disconnect(); | ||
provider = null; | ||
connection?.disconnect(); | ||
connection = null; | ||
subscriptions.errorAll(new DestroyedError()); | ||
responses.forEach((r) => r.onError(new DestroyedError())); | ||
responses.clear(); | ||
}; | ||
let nextId = 1; | ||
const request = (method, params, cb) => { | ||
if (!provider) | ||
if (!connection) | ||
throw new Error("Not connected"); | ||
const id = nextId++; | ||
const id = `${clientId}-${nextId++}`; | ||
if (cb) | ||
@@ -606,8 +622,19 @@ responses.set(id, cb); | ||
const client = createClient(provider); | ||
const request = abortablePromiseFn( | ||
(onSuccess, onError, method, params) => client.request(method, params, { onSuccess, onError }) | ||
); | ||
let rpcMethods = request("rpc_methods", []).then( | ||
(x) => rpcMethods = new Set(Array.isArray(x) ? x : x.methods) | ||
); | ||
rpcMethods.catch(noop2); | ||
return { | ||
chainHead: getChainHead(client.request), | ||
transaction: getTransaction(client.request), | ||
transaction: getTransaction( | ||
client.request, | ||
rpcMethods | ||
), | ||
destroy: () => { | ||
client.disconnect(); | ||
}, | ||
request, | ||
_request: client.request | ||
@@ -614,0 +641,0 @@ }; |
@@ -1,3 +0,2 @@ | ||
import { ConnectProvider } from '@polkadot-api/json-rpc-provider'; | ||
export { ConnectProvider, Provider } from '@polkadot-api/json-rpc-provider'; | ||
import { JsonRpcProvider } from '@polkadot-api/json-rpc-provider'; | ||
@@ -27,3 +26,3 @@ interface IRpcError { | ||
type FollowSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type FollowSubscriptionCb<T> = (methodName: string, subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientRequestCb<T, TT> = { | ||
@@ -39,2 +38,12 @@ onSuccess: (result: T, followSubscription: FollowSubscriptionCb<TT>) => void; | ||
declare class DestroyedError extends Error { | ||
constructor(); | ||
} | ||
type FollowInnerSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientInnerRequestCb<T, TT> = { | ||
onSuccess: (result: T, followSubscription: FollowInnerSubscriptionCb<TT>) => void; | ||
onError: (e: Error) => void; | ||
}; | ||
type ClientInnerRequest<T, TT> = (method: string, params: Array<any>, cb?: ClientInnerRequestCb<T, TT>) => UnsubscribeFn; | ||
interface StorageItemInput { | ||
@@ -60,3 +69,3 @@ key: string; | ||
type: "initialized"; | ||
finalizedBlockHash: string; | ||
finalizedBlockHashes: string[]; | ||
} | ||
@@ -105,3 +114,3 @@ type InitializedWithRuntime$1 = Initialized & { | ||
unpin: (hashes: Array<string>) => Promise<void>; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientInnerRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
} | ||
@@ -111,2 +120,3 @@ interface ChainHead { | ||
(withRuntime: true, cb: (event: FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
(withRuntime: boolean, cb: (event: FollowEventWithoutRuntime | FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
} | ||
@@ -138,6 +148,9 @@ | ||
} | ||
interface InitializedRpc { | ||
type InitializedRpc = { | ||
event: "initialized"; | ||
finalizedBlockHash: string; | ||
} | ||
} | { | ||
event: "initialized"; | ||
finalizedBlockHashes: string[]; | ||
}; | ||
type InitializedWithRuntime = InitializedRpc & { | ||
@@ -209,87 +222,6 @@ finalizedBlockRuntime: RuntimeRpc; | ||
interface TxValidated { | ||
type: "validated"; | ||
} | ||
interface TxBroadcasted { | ||
type: "broadcasted"; | ||
numPeers: number; | ||
} | ||
interface TxBestChainBlockIncluded { | ||
type: "bestChainBlockIncluded"; | ||
block: { | ||
hash: string; | ||
index: number; | ||
} | null; | ||
} | ||
interface TxFinalized { | ||
type: "finalized"; | ||
block: { | ||
hash: string; | ||
index: number; | ||
}; | ||
} | ||
interface TxInvalid { | ||
type: "invalid"; | ||
error: string; | ||
} | ||
interface TxDropped { | ||
type: "dropped"; | ||
broadcasted: boolean; | ||
error: string; | ||
} | ||
interface TxError { | ||
type: "error"; | ||
error: string; | ||
} | ||
type TxEvent = TxValidated | TxBroadcasted | TxBestChainBlockIncluded | TxFinalized | TxInvalid | TxDropped | TxError; | ||
type Transaction = (tx: string, next: (event: TxEvent) => void, error: (e: Error) => void) => UnsubscribeFn; | ||
type Transaction = (tx: string, error: (e: Error) => void) => UnsubscribeFn; | ||
interface TxValidatedRpc { | ||
event: "validated"; | ||
} | ||
interface TxBroadcastedRpc { | ||
event: "broadcasted"; | ||
numPeers: number; | ||
} | ||
interface TxBestChainBlockIncludedRpc { | ||
event: "bestChainBlockIncluded"; | ||
block: { | ||
hash: string; | ||
index: number; | ||
} | null; | ||
} | ||
interface TxFinalizedRpc { | ||
event: "finalized"; | ||
block: { | ||
hash: string; | ||
index: number; | ||
}; | ||
} | ||
interface TxInvalidRpc { | ||
event: "invalid"; | ||
error: string; | ||
} | ||
interface TxDroppedRpc { | ||
event: "dropped"; | ||
broadcasted: boolean; | ||
error: string; | ||
} | ||
interface TxErrorRpc { | ||
event: "error"; | ||
error: string; | ||
} | ||
type TxEventRpc = TxValidatedRpc | TxBroadcastedRpc | TxBestChainBlockIncludedRpc | TxFinalizedRpc | TxInvalidRpc | TxDroppedRpc | TxErrorRpc; | ||
declare const getTransaction: (request: ClientRequest<string, any>, rpcMethods: Promise<Set<string>> | Set<string>) => (tx: string, error: (e: Error) => void) => () => void; | ||
type ErrorEvents = TxDroppedRpc | TxInvalidRpc | TxErrorRpc; | ||
interface ITxError { | ||
type: ErrorEvents["event"]; | ||
error: string; | ||
} | ||
declare class TransactionError extends Error implements ITxError { | ||
type: "error" | "invalid" | "dropped"; | ||
error: string; | ||
constructor(e: ErrorEvents); | ||
} | ||
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => Transaction; | ||
interface SubstrateClient { | ||
@@ -299,6 +231,7 @@ chainHead: ChainHead; | ||
destroy: UnsubscribeFn; | ||
request: <T>(method: string, params: any[], abortSignal?: AbortSignal) => Promise<T>; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
} | ||
declare const createClient: (provider: ConnectProvider) => SubstrateClient; | ||
declare const createClient: (provider: JsonRpcProvider) => SubstrateClient; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientRequest, type ClientRequestCb, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction }; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientInnerRequest, type ClientInnerRequestCb, type ClientRequest, type ClientRequestCb, DestroyedError, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowInnerSubscriptionCb, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, type UnsubscribeFn, createClient, getChainHead, getTransaction }; |
@@ -1,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 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-c9489f3d99902b9f2fb0c041d6742c10ba614f0e.1.0", | ||
"version": "0.0.1-c9bb2ce3de90b7b5745189b6e3258c7cd945bb40.1.0", | ||
"author": "Josep M Sobrepere (https://github.com/josepot)", | ||
"repository": { | ||
"type": "git", | ||
"url": "git+https://github.com/paritytech/polkadot-api.git" | ||
"url": "git+https://github.com/polkadot-api/polkadot-api.git" | ||
}, | ||
@@ -43,5 +43,4 @@ "license": "MIT", | ||
"devDependencies": { | ||
"@vitest/coverage-v8": "^0.34.3", | ||
"@polkadot-api/utils": "0.0.1-c9489f3d99902b9f2fb0c041d6742c10ba614f0e.1.0", | ||
"@polkadot-api/json-rpc-provider": "0.0.1-c9489f3d99902b9f2fb0c041d6742c10ba614f0e.1.0" | ||
"@polkadot-api/json-rpc-provider": "0.0.1-c9bb2ce3de90b7b5745189b6e3258c7cd945bb40.1.0", | ||
"@polkadot-api/utils": "0.0.1-c9bb2ce3de90b7b5745189b6e3258c7cd945bb40.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
191076
2
212
1637