@polkadot-api/substrate-client
Advanced tools
Comparing version 0.0.1-8167145a6504fc77f310715b5208be71992108b5.1.0 to 0.0.1-81aa776246f63e7c9d431e89d66d4a7f8651a0ae.1.0
@@ -1,3 +0,3 @@ | ||
import { GetProvider } from '@polkadot-api/json-rpc-provider'; | ||
export { GetProvider, Provider, ProviderStatus } from '@polkadot-api/json-rpc-provider'; | ||
import { ConnectProvider } from '@polkadot-api/json-rpc-provider'; | ||
export { ConnectProvider, Provider } from '@polkadot-api/json-rpc-provider'; | ||
@@ -27,3 +27,3 @@ interface IRpcError { | ||
type FollowSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type FollowSubscriptionCb<T> = (methodName: string, subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientRequestCb<T, TT> = { | ||
@@ -35,3 +35,2 @@ onSuccess: (result: T, followSubscription: FollowSubscriptionCb<TT>) => void; | ||
interface Client { | ||
connect: () => void; | ||
disconnect: () => void; | ||
@@ -41,2 +40,12 @@ request: ClientRequest<any, any>; | ||
declare class DestroyedError extends Error { | ||
constructor(); | ||
} | ||
type FollowInnerSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientInnerRequestCb<T, TT> = { | ||
onSuccess: (result: T, followSubscription: FollowInnerSubscriptionCb<TT>) => void; | ||
onError: (e: Error) => void; | ||
}; | ||
type ClientInnerRequest<T, TT> = (method: string, params: Array<any>, cb?: ClientInnerRequestCb<T, TT>) => UnsubscribeFn; | ||
interface StorageItemInput { | ||
@@ -62,3 +71,3 @@ key: string; | ||
type: "initialized"; | ||
finalizedBlockHash: string; | ||
finalizedBlockHashes: string[]; | ||
} | ||
@@ -107,3 +116,3 @@ type InitializedWithRuntime$1 = Initialized & { | ||
unpin: (hashes: Array<string>) => Promise<void>; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientInnerRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
} | ||
@@ -113,2 +122,3 @@ interface ChainHead { | ||
(withRuntime: true, cb: (event: FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
(withRuntime: boolean, cb: (event: FollowEventWithoutRuntime | FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
} | ||
@@ -140,6 +150,9 @@ | ||
} | ||
interface InitializedRpc { | ||
type InitializedRpc = { | ||
event: "initialized"; | ||
finalizedBlockHash: string; | ||
} | ||
} | { | ||
event: "initialized"; | ||
finalizedBlockHashes: string[]; | ||
}; | ||
type InitializedWithRuntime = InitializedRpc & { | ||
@@ -294,3 +307,3 @@ finalizedBlockRuntime: RuntimeRpc; | ||
} | ||
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => Transaction; | ||
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => (namespace: string, tx: string, next: (event: TxEvent) => void, error: (e: Error) => void) => () => void; | ||
@@ -301,6 +314,7 @@ interface SubstrateClient { | ||
destroy: UnsubscribeFn; | ||
request: <T>(method: string, params: any[], abortSignal?: AbortSignal) => Promise<T>; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
} | ||
declare const createClient: (provider: GetProvider) => SubstrateClient; | ||
declare const createClient: (provider: ConnectProvider) => SubstrateClient; | ||
export { AbortablePromiseFn, BestBlockChanged, ChainHead, Client, ClientRequest, ClientRequestCb, DisjointError, Finalized, FollowEventWithRuntime, FollowEventWithoutRuntime, FollowResponse, FollowSubscriptionCb, IRpcError, Initialized, InitializedWithRuntime$1 as InitializedWithRuntime, NewBlock, NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, Runtime, StopError, StorageItemInput, StorageItemResponse, StorageResult, SubstrateClient, Transaction, TransactionError, TxBestChainBlockIncluded, TxBroadcasted, TxDropped, TxError, TxEvent, TxFinalized, TxInvalid, TxValidated, UnsubscribeFn, createClient, getChainHead, getTransaction }; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientInnerRequest, type ClientInnerRequestCb, type ClientRequest, type ClientRequestCb, DestroyedError, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowInnerSubscriptionCb, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction }; |
@@ -24,2 +24,20 @@ "use strict"; | ||
}; | ||
var __accessCheck = (obj, member, msg) => { | ||
if (!member.has(obj)) | ||
throw TypeError("Cannot " + msg); | ||
}; | ||
var __privateGet = (obj, member, getter) => { | ||
__accessCheck(obj, member, "read from private field"); | ||
return getter ? getter.call(obj) : member.get(obj); | ||
}; | ||
var __privateAdd = (obj, member, value) => { | ||
if (member.has(obj)) | ||
throw TypeError("Cannot add the same private member more than once"); | ||
member instanceof WeakSet ? member.add(obj) : member.set(obj, value); | ||
}; | ||
var __privateSet = (obj, member, value, setter) => { | ||
__accessCheck(obj, member, "write to private field"); | ||
setter ? setter.call(obj, value) : member.set(obj, value); | ||
return value; | ||
}; | ||
@@ -29,2 +47,3 @@ // src/index.ts | ||
__export(src_exports, { | ||
DestroyedError: () => DestroyedError, | ||
DisjointError: () => DisjointError, | ||
@@ -42,22 +61,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]); | ||
}); | ||
@@ -79,6 +93,7 @@ | ||
// src/internal-utils/noop.ts | ||
var noop = () => { | ||
var noop2 = () => { | ||
}; | ||
// src/internal-utils/subscriptions-manager.ts | ||
var MAX_TIME = 2e3; | ||
var getSubscriptionsManager = () => { | ||
@@ -113,3 +128,152 @@ const subscriptions = /* @__PURE__ */ new Map(); | ||
}; | ||
var _messages, _token; | ||
var OrphanMessages = class { | ||
constructor() { | ||
__privateAdd(this, _messages, void 0); | ||
__privateAdd(this, _token, void 0); | ||
__privateSet(this, _messages, /* @__PURE__ */ new Map()); | ||
__privateSet(this, _token, null); | ||
} | ||
checkClear() { | ||
if (__privateGet(this, _messages).size > 0) | ||
return; | ||
clearInterval(__privateGet(this, _token)); | ||
__privateSet(this, _token, null); | ||
} | ||
set(key, message) { | ||
const messages = __privateGet(this, _messages).get(key)?.messages ?? []; | ||
messages.push(message); | ||
__privateGet(this, _messages).set(key, { expiry: Date.now() + MAX_TIME, messages }); | ||
__privateSet(this, _token, __privateGet(this, _token) || setInterval(() => { | ||
const now = Date.now(); | ||
[...__privateGet(this, _messages).entries()].forEach(([key2, entry]) => { | ||
if (entry.expiry > now) | ||
__privateGet(this, _messages).delete(key2); | ||
}); | ||
this.checkClear(); | ||
}, MAX_TIME)); | ||
} | ||
retrieve(key) { | ||
const result = __privateGet(this, _messages).get(key); | ||
if (!result) | ||
return []; | ||
__privateGet(this, _messages).delete(key); | ||
this.checkClear(); | ||
return result.messages; | ||
} | ||
clear() { | ||
__privateGet(this, _messages).clear(); | ||
this.checkClear(); | ||
} | ||
}; | ||
_messages = new WeakMap(); | ||
_token = new WeakMap(); | ||
// 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 createClient = (gProvider) => { | ||
const responses = /* @__PURE__ */ new Map(); | ||
const subscriptions = getSubscriptionsManager(); | ||
const orphans = new OrphanMessages(); | ||
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; | ||
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); | ||
const pending = orphans.retrieve(subscriptionId2); | ||
if (pending.length) { | ||
Promise.resolve().then(() => { | ||
pending.forEach((msg) => { | ||
subscriptions.next(subscriptionId2, msg); | ||
}); | ||
}); | ||
} | ||
return () => { | ||
subscriptions.unsubscribe(subscriptionId2); | ||
}; | ||
}); | ||
} | ||
; | ||
({ subscription, result, error } = params); | ||
if (!subscription || !error && !Object.hasOwn(params, "result")) | ||
throw 0; | ||
const subscriptionId = parsed.method + subscription; | ||
if (!subscriptions.has(subscriptionId)) { | ||
orphans.set(subscriptionId, message); | ||
} | ||
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); | ||
} | ||
} | ||
provider = gProvider(onMessage); | ||
const disconnect = () => { | ||
provider?.disconnect(); | ||
provider = null; | ||
subscriptions.errorAll(new DestroyedError()); | ||
responses.forEach((r) => r.onError(new DestroyedError())); | ||
responses.clear(); | ||
orphans.clear(); | ||
}; | ||
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/transaction/transaction.ts | ||
@@ -139,24 +303,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]); | ||
}; | ||
@@ -209,7 +378,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) => { | ||
@@ -283,7 +452,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; | ||
} | ||
@@ -327,3 +496,3 @@ let cancel = request( | ||
const _onError = (e) => { | ||
cancel = import_utils.noop; | ||
cancel = import_utils2.noop; | ||
doneListening(); | ||
@@ -333,3 +502,3 @@ onError(e); | ||
const _onDone = () => { | ||
cancel = import_utils.noop; | ||
cancel = import_utils2.noop; | ||
doneListening(); | ||
@@ -396,2 +565,3 @@ onDone(); | ||
const subscriptions = getSubscriptionsManager(); | ||
const orphans = new OrphanMessages(); | ||
const ongoingRequests = /* @__PURE__ */ new Set(); | ||
@@ -401,5 +571,16 @@ const deferredFollow = deferred(); | ||
const onAllFollowEventsNext = (event) => { | ||
if (isOperationEvent(event)) | ||
if (isOperationEvent(event)) { | ||
if (!subscriptions.has(event.operationId)) { | ||
orphans.set(event.operationId, 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 +594,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 +604,3 @@ error: onAllFollowEventsError | ||
followSubscription = null; | ||
unfollow = noop; | ||
unfollow = noop2; | ||
done(); | ||
@@ -432,2 +613,3 @@ sendUnfollow && request("chainHead_unstable_unfollow", [subscriptionId]); | ||
ongoingRequests.clear(); | ||
orphans.clear(); | ||
}; | ||
@@ -438,3 +620,7 @@ followSubscription = subscriptionId; | ||
const onFollowRequestError = (e) => { | ||
onFollowError(e); | ||
if (e instanceof DestroyedError) { | ||
unfollow(false); | ||
} else { | ||
onFollowError(e); | ||
} | ||
followSubscription = null; | ||
@@ -454,3 +640,3 @@ deferredFollow.res(e); | ||
disjoint(); | ||
return noop; | ||
return noop2; | ||
} | ||
@@ -464,5 +650,13 @@ const onSubscription = (subscription) => { | ||
subscriber.error(new DisjointError()); | ||
return noop; | ||
return noop2; | ||
} | ||
subscriptions.subscribe(operationId, subscriber); | ||
const pending = orphans.retrieve(operationId); | ||
if (pending.length) { | ||
Promise.resolve().then(() => { | ||
pending.forEach((msg) => { | ||
subscriptions.next(operationId, msg); | ||
}); | ||
}); | ||
} | ||
return () => { | ||
@@ -489,3 +683,3 @@ subscriptions.unsubscribe(operationId); | ||
return onSubscription(followSubscription); | ||
let onCancel = noop; | ||
let onCancel = noop2; | ||
followSubscription.then((x) => { | ||
@@ -517,135 +711,49 @@ if (x instanceof Error) | ||
// src/client/RpcError.ts | ||
var RpcError = class extends Error { | ||
constructor(e) { | ||
super(e.message); | ||
__publicField(this, "code"); | ||
__publicField(this, "data"); | ||
this.code = e.code; | ||
this.data = e.data; | ||
this.name = "RpcError"; | ||
} | ||
}; | ||
// src/client/createClient.ts | ||
var createClient = (gProvider) => { | ||
const responses = /* @__PURE__ */ new Map(); | ||
const subscriptions = getSubscriptionsManager(); | ||
const queuedRequests = /* @__PURE__ */ new Map(); | ||
let provider = null; | ||
let isConnecting = true; | ||
const send = (id, method, params) => { | ||
provider.send( | ||
JSON.stringify({ | ||
jsonrpc: "2.0", | ||
id, | ||
method, | ||
params | ||
}) | ||
); | ||
}; | ||
function onMessage(message) { | ||
try { | ||
let id, result, error, params, subscription; | ||
({ id, result, error, params } = JSON.parse(message)); | ||
if (id) { | ||
const cb = responses.get(id); | ||
if (!cb) | ||
return; | ||
responses.delete(id); | ||
return error ? cb.onError(new RpcError(error)) : cb.onSuccess(result, (subscriptionId, subscriber) => { | ||
subscriptions.subscribe(subscriptionId, subscriber); | ||
return () => { | ||
subscriptions.unsubscribe(subscriptionId); | ||
}; | ||
}); | ||
} | ||
; | ||
({ subscription, result, error } = params); | ||
if (!subscription || !error && !Object.hasOwn(params, "result")) | ||
throw 0; | ||
if (error) { | ||
subscriptions.error(subscription, new RpcError(error)); | ||
} else { | ||
subscriptions.next(subscription, result); | ||
} | ||
} catch (e) { | ||
console.warn("Error parsing incomming message: " + message); | ||
console.error(e); | ||
} | ||
} | ||
function onStatusChange(e) { | ||
if (e === "connected") { | ||
isConnecting = false; | ||
queuedRequests.forEach((args, id) => { | ||
process(id, ...args); | ||
}); | ||
queuedRequests.clear(); | ||
return; | ||
} | ||
if (isConnecting) { | ||
isConnecting = false; | ||
} else { | ||
provider = null; | ||
disconnect(); | ||
} | ||
} | ||
const connect = () => { | ||
provider = gProvider(onMessage, onStatusChange); | ||
provider.open(); | ||
}; | ||
const disconnect = () => { | ||
provider?.close(); | ||
provider = null; | ||
const disconnectError = new Error("disconnect"); | ||
[...queuedRequests.values()].forEach((request2) => { | ||
request2[2]?.onError(disconnectError); | ||
}); | ||
queuedRequests.clear(); | ||
[...responses.values()].forEach((response) => { | ||
response.onError(disconnectError); | ||
}); | ||
responses.clear(); | ||
subscriptions.errorAll(disconnectError); | ||
}; | ||
const process = (id, ...args) => { | ||
const [method, params, cb] = args; | ||
if (cb) | ||
responses.set(id, cb); | ||
send(id, method, params); | ||
}; | ||
let nextId = 1; | ||
const request = (method, params, cb) => { | ||
if (!provider && !isConnecting) | ||
throw new Error("Not connected"); | ||
const id = nextId++; | ||
if (isConnecting) | ||
queuedRequests.set(id, [method, params, cb]); | ||
else | ||
process(id, method, params, cb); | ||
return () => { | ||
if (queuedRequests.has(id)) { | ||
queuedRequests.delete(id); | ||
return; | ||
} | ||
responses.delete(id); | ||
}; | ||
}; | ||
return { | ||
request, | ||
connect, | ||
disconnect | ||
}; | ||
}; | ||
// src/index.ts | ||
var import_utils3 = require("@polkadot-api/utils"); | ||
var createClient2 = (provider) => { | ||
const client = createClient(provider); | ||
client.connect(); | ||
const request = abortablePromiseFn( | ||
(onSuccess, onError, method, params) => client.request(method, params, { onSuccess, onError }) | ||
); | ||
let rpcMethods = request("rpc_methods", []).then( | ||
(x) => rpcMethods = new Set(Array.isArray(x) ? x : x.methods) | ||
); | ||
rpcMethods.catch(import_utils3.noop); | ||
const getSubmitAndWatchNamespace = (input) => input.has("transaction_unstable_submitAndWatch") ? "transaction" : "transactionWatch"; | ||
const innerTransaction = getTransaction( | ||
client.request | ||
); | ||
return { | ||
chainHead: getChainHead(client.request), | ||
transaction: getTransaction(client.request), | ||
transaction: (tx, next, err) => { | ||
if (rpcMethods instanceof Promise) { | ||
let cleanup = import_utils3.noop; | ||
let isRunning = true; | ||
rpcMethods.then((result) => { | ||
if (!isRunning) | ||
return; | ||
cleanup = innerTransaction( | ||
getSubmitAndWatchNamespace(result), | ||
tx, | ||
next, | ||
err | ||
); | ||
}); | ||
return () => { | ||
isRunning = false; | ||
cleanup(); | ||
}; | ||
} | ||
return innerTransaction( | ||
getSubmitAndWatchNamespace(rpcMethods), | ||
tx, | ||
next, | ||
err | ||
); | ||
}, | ||
destroy: () => { | ||
client.disconnect(); | ||
}, | ||
request, | ||
_request: client.request | ||
@@ -652,0 +760,0 @@ }; |
@@ -1,3 +0,3 @@ | ||
import { GetProvider } from '@polkadot-api/json-rpc-provider'; | ||
export { GetProvider, Provider, ProviderStatus } from '@polkadot-api/json-rpc-provider'; | ||
import { ConnectProvider } from '@polkadot-api/json-rpc-provider'; | ||
export { ConnectProvider, Provider } from '@polkadot-api/json-rpc-provider'; | ||
@@ -27,3 +27,3 @@ interface IRpcError { | ||
type FollowSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type FollowSubscriptionCb<T> = (methodName: string, subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientRequestCb<T, TT> = { | ||
@@ -35,3 +35,2 @@ onSuccess: (result: T, followSubscription: FollowSubscriptionCb<TT>) => void; | ||
interface Client { | ||
connect: () => void; | ||
disconnect: () => void; | ||
@@ -41,2 +40,12 @@ request: ClientRequest<any, any>; | ||
declare class DestroyedError extends Error { | ||
constructor(); | ||
} | ||
type FollowInnerSubscriptionCb<T> = (subscriptionId: string, cb: Subscriber<T>) => UnsubscribeFn; | ||
type ClientInnerRequestCb<T, TT> = { | ||
onSuccess: (result: T, followSubscription: FollowInnerSubscriptionCb<TT>) => void; | ||
onError: (e: Error) => void; | ||
}; | ||
type ClientInnerRequest<T, TT> = (method: string, params: Array<any>, cb?: ClientInnerRequestCb<T, TT>) => UnsubscribeFn; | ||
interface StorageItemInput { | ||
@@ -62,3 +71,3 @@ key: string; | ||
type: "initialized"; | ||
finalizedBlockHash: string; | ||
finalizedBlockHashes: string[]; | ||
} | ||
@@ -107,3 +116,3 @@ type InitializedWithRuntime$1 = Initialized & { | ||
unpin: (hashes: Array<string>) => Promise<void>; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientInnerRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
} | ||
@@ -113,2 +122,3 @@ interface ChainHead { | ||
(withRuntime: true, cb: (event: FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
(withRuntime: boolean, cb: (event: FollowEventWithoutRuntime | FollowEventWithRuntime) => void, onError: (error: Error) => void): FollowResponse; | ||
} | ||
@@ -140,6 +150,9 @@ | ||
} | ||
interface InitializedRpc { | ||
type InitializedRpc = { | ||
event: "initialized"; | ||
finalizedBlockHash: string; | ||
} | ||
} | { | ||
event: "initialized"; | ||
finalizedBlockHashes: string[]; | ||
}; | ||
type InitializedWithRuntime = InitializedRpc & { | ||
@@ -294,3 +307,3 @@ finalizedBlockRuntime: RuntimeRpc; | ||
} | ||
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => Transaction; | ||
declare const getTransaction: (request: ClientRequest<string, TxEventRpc>) => (namespace: string, tx: string, next: (event: TxEvent) => void, error: (e: Error) => void) => () => void; | ||
@@ -301,6 +314,7 @@ interface SubstrateClient { | ||
destroy: UnsubscribeFn; | ||
request: <T>(method: string, params: any[], abortSignal?: AbortSignal) => Promise<T>; | ||
_request: <Reply, Notification>(method: string, params: any[], cb?: ClientRequestCb<Reply, Notification>) => UnsubscribeFn; | ||
} | ||
declare const createClient: (provider: GetProvider) => SubstrateClient; | ||
declare const createClient: (provider: ConnectProvider) => SubstrateClient; | ||
export { AbortablePromiseFn, BestBlockChanged, ChainHead, Client, ClientRequest, ClientRequestCb, DisjointError, Finalized, FollowEventWithRuntime, FollowEventWithoutRuntime, FollowResponse, FollowSubscriptionCb, IRpcError, Initialized, InitializedWithRuntime$1 as InitializedWithRuntime, NewBlock, NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, Runtime, StopError, StorageItemInput, StorageItemResponse, StorageResult, SubstrateClient, Transaction, TransactionError, TxBestChainBlockIncluded, TxBroadcasted, TxDropped, TxError, TxEvent, TxFinalized, TxInvalid, TxValidated, UnsubscribeFn, createClient, getChainHead, getTransaction }; | ||
export { type AbortablePromiseFn, type BestBlockChanged, type ChainHead, type Client, type ClientInnerRequest, type ClientInnerRequestCb, type ClientRequest, type ClientRequestCb, DestroyedError, DisjointError, type Finalized, type FollowEventWithRuntime, type FollowEventWithoutRuntime, type FollowInnerSubscriptionCb, type FollowResponse, type FollowSubscriptionCb, type IRpcError, type Initialized, type InitializedWithRuntime$1 as InitializedWithRuntime, type NewBlock, type NewBlockWithRuntime$1 as NewBlockWithRuntime, OperationError, OperationInaccessibleError, OperationLimitError, RpcError, type Runtime, StopError, type StorageItemInput, type StorageItemResponse, type StorageResult, type SubstrateClient, type Transaction, TransactionError, type TxBestChainBlockIncluded, type TxBroadcasted, type TxDropped, type TxError, type TxEvent, type TxFinalized, type TxInvalid, type TxValidated, type UnsubscribeFn, createClient, getChainHead, getTransaction }; |
@@ -1,2 +0,2 @@ | ||
"use strict";var _=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var Z=(r,e,t)=>e in r?_(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ee=(r,e)=>{for(var t in e)_(r,t,{get:e[t],enumerable:!0})},re=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of X(e))!Y.call(r,i)&&i!==t&&_(r,i,{get:()=>e[i],enumerable:!(n=V(e,i))||n.enumerable});return r};var te=r=>re(_({},"__esModule",{value:!0}),r);var F=(r,e,t)=>(Z(r,typeof e!="symbol"?e+"":e,t),t);var ce={};ee(ce,{DisjointError:()=>T,OperationError:()=>h,OperationInaccessibleError:()=>C,OperationLimitError:()=>y,RpcError:()=>w,StopError:()=>P,TransactionError:()=>q,createClient:()=>ae});module.exports=te(ce);var M=class extends Error{constructor(){super("Aborted by AbortSignal"),this.name="AbortError"}},A=r=>(...e)=>new Promise((t,n)=>{let[i,a]=e[e.length-1]instanceof AbortSignal?[e.slice(0,e.length-1),e[e.length-1]]:[e],b=()=>{l(),n(new M)};a?.addEventListener("abort",b,{once:!0});let p=d=>g=>{a?.removeEventListener("abort",b),d(g)},l=r(p(t),p(n),...i)});function N(){let r=()=>{},e=()=>{};return{promise:new Promise((n,i)=>{r=n,e=i}),res:r,rej:e}}var v=()=>{};var H=()=>{let r=new Map;return{has:r.has.bind(r),subscribe(e,t){r.set(e,t)},unsubscribe(e){r.delete(e)},next(e,t){r.get(e)?.next(t)},error(e,t){let n=r.get(e);n&&(r.delete(e),n.error(t))},errorAll(e){let t=[...r.values()];r.clear(),t.forEach(n=>{n.error(e)})}}};var oe=r=>{let{event:e,...t}=r;return{type:e,...t}},ne=new Set(["dropped","invalid","finalized","error"]);function ie(r){return ne.has(r.event)}var q=class extends Error{constructor(t){super(`TxError: ${t.event} - ${t.error}`);F(this,"type");F(this,"error");this.type=t.event,this.error=t.error,this.name="TransactionError"}},U=r=>(e,t,n)=>{let i=r("transaction_unstable_submitAndWatch",[e],{onSuccess:(a,b)=>{let p=b(a,{next:l=>{if(ie(l)&&(p(),i=v,l.event!=="finalized"))return n(new q(l));t(oe(l))},error(l){i(),i=v,n(l)}});i=()=>{p(),r("transaction_unstable_unwatch",[a])}},onError:n});return()=>{i()}};var P=class extends Error{constructor(){super("ChainHead stopped"),this.name="StopError"}},T=class extends Error{constructor(){super("ChainHead disjointed"),this.name="DisjointError"}},y=class extends Error{constructor(){super("ChainHead operations limit reached"),this.name="OperationLimitError"}},h=class extends Error{constructor(e){super(e),this.name="OperationError"}},C=class extends Error{constructor(){super("ChainHead operation inaccessible"),this.name="OperationInaccessibleError"}};var D=(r,e)=>t=>A((n,i,...a)=>{let[b,p]=e(...a),l=t(r,b,{onSuccess:(d,g)=>{if(d.result==="limitReached")return l=v,i(new y);let f=!0,m=v,R=s=>{f=!1,m(),n(s)},o=s=>{f=!1,m(),i(s)};m=g(d.operationId,{next:s=>{let c=s;c.event==="operationError"?i(new h(c.error)):c.event==="operationInaccessible"?i(new C):p(s,R,o)},error:o}),l=()=>{f&&(m(),t("chainHead_unstable_stopOperation",[d.operationId]))}},onError:i});return()=>{l()}});var z=D("chainHead_unstable_body",r=>[[r],(e,t)=>{t(e.value)}]);var B=D("chainHead_unstable_call",(r,e,t)=>[[r,e,t],(n,i)=>{i(n.output)}]);var J=r=>e=>new Promise((t,n)=>{r("chainHead_unstable_header",[e],{onSuccess:t,onError:n})});var W=require("@polkadot-api/utils");var L=r=>(e,t,n,i,a,b,p)=>{if(t.length===0)return b(),W.noop;let l=r("chainHead_unstable_storage",[e,t,n],{onSuccess:(d,g)=>{if(d.result==="limitReached"||d.discardedItems===t.length)return a(new y);let f=g(d.operationId,{next:o=>{switch(o.event){case"operationStorageItems":{i(o.items);break}case"operationStorageDone":{R();break}case"operationError":{m(new h(o.error));break}case"operationInaccessible":{m(new C);break}default:r("chainHead_unstable_continue",[])}},error:a});l=()=>{f(),r("chainHead_unstable_stopOperation",[d.operationId])};let m=o=>{l=W.noop,f(),a(o)},R=()=>{l=W.noop,f(),b()};p(d.discardedItems)},onError:a});return()=>{l()}};var $=r=>{let e=L(r);return A((t,n,i,a,b,p)=>{let l=a.startsWith("descendants"),d=l?[]:null,f=e(i,[{key:b,type:a}],p??null,l?m=>{d.push(...m)}:m=>{d=m[0]?.[a]},n,()=>{t(d)},m=>{m>0&&(f(),n(new y))});return f})};var K=r=>e=>new Promise((t,n)=>{r("chainHead_unstable_unpin",[e],{onSuccess(){t()},onError:n})});function se(r){return r.operationId!==void 0}function k(r){return(e,t,n)=>{let i=H(),a=new Set,b=N(),p=b.promise,l=o=>{if(se(o))return i.next(o.operationId,o);if(o.event!=="stop"){let{event:s,...c}=o;return t({type:s,...c})}n(new P),m(!1)},d=o=>{n(o),m()},m=r("chainHead_unstable_follow",[e],{onSuccess:(o,s)=>{let c=s(o,{next:l,error:d});m=(u=!0)=>{p=null,m=v,c(),u&&r("chainHead_unstable_unfollow",[o]),i.errorAll(new T),a.forEach(E=>{E()}),a.clear()},p=o,b.res(o)},onError:o=>{n(o),p=null,b.res(o)}}),R=(o,s,c)=>{let u=()=>{c?.onError(new T)};if(p===null)return u(),v;let E=x=>{if(!c)return r(o,[x,...s]);a.add(u);let I=(O,G)=>p===null?(G.error(new T),v):(i.subscribe(O,G),()=>{i.unsubscribe(O)}),j=r(o,[x,...s],{onSuccess:O=>{a.delete(u),c.onSuccess(O,I)},onError:O=>{a.delete(u),c.onError(O)}});return()=>{a.delete(u),j()}};if(typeof p=="string")return E(p);let S=v;return p.then(x=>{if(x instanceof Error)return u();p&&(S=E(x))}),()=>{S()}};return{unfollow(){m(),p=null},body:z(R),call:B(R),header:J(R),storage:$(R),storageSubscription:L(R),unpin:K(R),_request:R}}}var w=class extends Error{constructor(t){super(t.message);F(this,"code");F(this,"data");this.code=t.code,this.data=t.data,this.name="RpcError"}};var Q=r=>{let e=new Map,t=H(),n=new Map,i=null,a=!0,b=(o,s,c)=>{i.send(JSON.stringify({jsonrpc:"2.0",id:o,method:s,params:c}))};function p(o){try{let s,c,u,E,S;if({id:s,result:c,error:u,params:E}=JSON.parse(o),s){let x=e.get(s);return x?(e.delete(s),u?x.onError(new w(u)):x.onSuccess(c,(I,j)=>(t.subscribe(I,j),()=>{t.unsubscribe(I)}))):void 0}if({subscription:S,result:c,error:u}=E,!S||!u&&!Object.hasOwn(E,"result"))throw 0;u?t.error(S,new w(u)):t.next(S,c)}catch(s){console.warn("Error parsing incomming message: "+o),console.error(s)}}function l(o){if(o==="connected"){a=!1,n.forEach((s,c)=>{f(c,...s)}),n.clear();return}a?a=!1:(i=null,g())}let d=()=>{i=r(p,l),i.open()},g=()=>{i?.close(),i=null;let o=new Error("disconnect");[...n.values()].forEach(s=>{s[2]?.onError(o)}),n.clear(),[...e.values()].forEach(s=>{s.onError(o)}),e.clear(),t.errorAll(o)},f=(o,...s)=>{let[c,u,E]=s;E&&e.set(o,E),b(o,c,u)},m=1;return{request:(o,s,c)=>{if(!i&&!a)throw new Error("Not connected");let u=m++;return a?n.set(u,[o,s,c]):f(u,o,s,c),()=>{if(n.has(u)){n.delete(u);return}e.delete(u)}},connect:d,disconnect:g}};var ae=r=>{let e=Q(r);return e.connect(),{chainHead:k(e.request),transaction:U(e.request),destroy:()=>{e.disconnect()},_request:e.request}}; | ||
"use strict";var B=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var le=Object.prototype.hasOwnProperty;var ue=(r,e,t)=>e in r?B(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var me=(r,e)=>{for(var t in e)B(r,t,{get:e[t],enumerable:!0})},de=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pe(e))!le.call(r,o)&&o!==t&&B(r,o,{get:()=>e[o],enumerable:!(n=ce(e,o))||n.enumerable});return r};var fe=r=>de(B({},"__esModule",{value:!0}),r);var P=(r,e,t)=>(ue(r,typeof e!="symbol"?e+"":e,t),t),Z=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var y=(r,e,t)=>(Z(r,e,"read from private field"),t?t.call(r):e.get(r)),$=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)},W=(r,e,t,n)=>(Z(r,e,"write to private field"),n?n.call(r,t):e.set(r,t),t);var ve={};me(ve,{DestroyedError:()=>v,DisjointError:()=>S,OperationError:()=>O,OperationInaccessibleError:()=>F,OperationLimitError:()=>C,RpcError:()=>_,StopError:()=>k,TransactionError:()=>M,createClient:()=>Ee});module.exports=fe(ve);var z=require("@polkadot-api/utils"),H=r=>(...e)=>new Promise((t,n)=>{let o=z.noop,[p,a]=e[e.length-1]instanceof AbortSignal?[e.slice(0,e.length-1),e[e.length-1]]:[e],d=()=>{o(),n(new z.AbortError)};a?.addEventListener("abort",d,{once:!0});let s=c=>f=>{o=z.noop,a?.removeEventListener("abort",d),c(f)};o=r(s(t),s(n),...p)});function ee(){let r=()=>{},e=()=>{};return{promise:new Promise((n,o)=>{r=n,e=o}),res:r,rej:e}}var T=()=>{};var U=()=>{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)})}}},E,w,D=class{constructor(){$(this,E,void 0);$(this,w,void 0);W(this,E,new Map),W(this,w,null)}checkClear(){y(this,E).size>0||(clearInterval(y(this,w)),W(this,w,null))}set(e,t){let n=y(this,E).get(e)?.messages??[];n.push(t),y(this,E).set(e,{expiry:Date.now()+2e3,messages:n}),W(this,w,y(this,w)||setInterval(()=>{let o=Date.now();[...y(this,E).entries()].forEach(([p,a])=>{a.expiry>o&&y(this,E).delete(p)}),this.checkClear()},2e3))}retrieve(e){let t=y(this,E).get(e);return t?(y(this,E).delete(e),this.checkClear(),t.messages):[]}clear(){y(this,E).clear(),this.checkClear()}};E=new WeakMap,w=new WeakMap;var _=class extends Error{constructor(t){super(t.message);P(this,"code");P(this,"data");this.code=t.code,this.data=t.data,this.name="RpcError"}};var v=class extends Error{constructor(){super("Client destroyed"),this.name="DestroyedError"}};var re=r=>{let e=new Map,t=U(),n=new D,o=null,p=(f,l,u)=>{o.send(JSON.stringify({jsonrpc:"2.0",id:f,method:l,params:u}))};function a(f){try{let l,u,m,b,i,R=JSON.parse(f);if({id:l,result:u,error:m,params:b}=R,l){let h=e.get(l);return h?(e.delete(l),m?h.onError(new _(m)):h.onSuccess(u,(q,L,I)=>{let A=q+L;t.subscribe(A,I);let j=n.retrieve(A);return j.length&&Promise.resolve().then(()=>{j.forEach(x=>{t.next(A,x)})}),()=>{t.unsubscribe(A)}})):void 0}if({subscription:i,result:u,error:m}=b,!i||!m&&!Object.hasOwn(b,"result"))throw 0;let g=R.method+i;t.has(g)||n.set(g,f),m?t.error(g,new _(m)):t.next(g,u)}catch(l){console.warn("Error parsing incomming message: "+f),console.error(l)}}o=r(a);let d=()=>{o?.disconnect(),o=null,t.errorAll(new v),e.forEach(f=>f.onError(new v)),e.clear(),n.clear()},s=1;return{request:(f,l,u)=>{if(!o)throw new Error("Not connected");let m=s++;return u&&e.set(m,u),p(m,f,l),()=>{e.delete(m)}},disconnect:d}};var be=r=>{let{event:e,...t}=r;return{type:e,...t}},Re=new Set(["dropped","invalid","finalized","error"]);function ge(r){return Re.has(r.event)}var M=class extends Error{constructor(t){super(`TxError: ${t.event} - ${t.error}`);P(this,"type");P(this,"error");this.type=t.event,this.error=t.error,this.name="TransactionError"}},G=r=>(e,t,n,o)=>{let p=r(e+"_unstable_submitAndWatch",[t],{onSuccess:(a,d)=>{let s=d(e+"_unstable_watchEvent",a,{next:c=>{if(ge(c)&&(s(),p=T,c.event!=="finalized"))return o(new M(c));n(be(c))},error(c){c instanceof v||p(),p=T,o(c)}});p=()=>{s(),r(e+"_unstable_unwatch",[a])}},onError:o});return()=>{p()}};var k=class extends Error{constructor(){super("ChainHead stopped"),this.name="StopError"}},S=class extends Error{constructor(){super("ChainHead disjointed"),this.name="DisjointError"}},C=class extends Error{constructor(){super("ChainHead operations limit reached"),this.name="OperationLimitError"}},O=class extends Error{constructor(e){super(e),this.name="OperationError"}},F=class extends Error{constructor(){super("ChainHead operation inaccessible"),this.name="OperationInaccessibleError"}};var N=(r,e)=>t=>H((n,o,...p)=>{let[a,d]=e(...p),s=t(r,a,{onSuccess:(c,f)=>{if(c.result==="limitReached")return s=T,o(new C);let l=!0,u=T,m=i=>{l=!1,u(),n(i)},b=i=>{l=!1,u(),o(i)};u=f(c.operationId,{next:i=>{let R=i;R.event==="operationError"?o(new O(R.error)):R.event==="operationInaccessible"?o(new F):d(i,m,b)},error:b}),s=()=>{l&&(u(),t("chainHead_unstable_stopOperation",[c.operationId]))}},onError:o});return()=>{s()}});var te=N("chainHead_unstable_body",r=>[[r],(e,t)=>{t(e.value)}]);var ne=N("chainHead_unstable_call",(r,e,t)=>[[r,e,t],(n,o)=>{o(n.output)}]);var oe=r=>e=>new Promise((t,n)=>{r("chainHead_unstable_header",[e],{onSuccess:t,onError:n})});var X=require("@polkadot-api/utils");var J=r=>(e,t,n,o,p,a,d)=>{if(t.length===0)return a(),X.noop;let s=r("chainHead_unstable_storage",[e,t,n],{onSuccess:(c,f)=>{if(c.result==="limitReached"||c.discardedItems===t.length)return p(new C);let l=f(c.operationId,{next:b=>{switch(b.event){case"operationStorageItems":{o(b.items);break}case"operationStorageDone":{m();break}case"operationError":{u(new O(b.error));break}case"operationInaccessible":{u(new F);break}default:r("chainHead_unstable_continue",[])}},error:p});s=()=>{l(),r("chainHead_unstable_stopOperation",[c.operationId])};let u=b=>{s=X.noop,l(),p(b)},m=()=>{s=X.noop,l(),a()};d(c.discardedItems)},onError:p});return()=>{s()}};var ie=r=>{let e=J(r);return H((t,n,o,p,a,d)=>{let s=p.startsWith("descendants"),c=s?[]:null,l=e(o,[{key:a,type:p}],d??null,s?u=>{c.push(...u)}:u=>{c=u[0]?.[p]},n,()=>{t(c)},u=>{u>0&&(l(),n(new C))});return l})};var se=r=>e=>new Promise((t,n)=>{r("chainHead_unstable_unpin",[e],{onSuccess(){t()},onError:n})});function he(r){return r.operationId!==void 0}function K(r){return(e,t,n)=>{let o=U(),p=new D,a=new Set,d=ee(),s=d.promise,c=i=>{if(he(i))return o.has(i.operationId)||p.set(i.operationId,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:R,...g}=i;return t({type:R,...g})}n(new k),m(!1)},f=i=>{n(i),m(!(i instanceof v))},m=r("chainHead_unstable_follow",[e],{onSuccess:(i,R)=>{let g=R("chainHead_unstable_followEvent",i,{next:c,error:f});m=(h=!0)=>{s=null,m=T,g(),h&&r("chainHead_unstable_unfollow",[i]),o.errorAll(new S),a.forEach(q=>{q()}),a.clear(),p.clear()},s=i,d.res(i)},onError:i=>{i instanceof v?m(!1):n(i),s=null,d.res(i)}}),b=(i,R,g)=>{let h=()=>{g?.onError(new S)};if(s===null)return h(),T;let q=I=>{if(!g)return r(i,[I,...R]);a.add(h);let A=(x,V)=>{if(s===null)return V.error(new S),T;o.subscribe(x,V);let Y=p.retrieve(x);return Y.length&&Promise.resolve().then(()=>{Y.forEach(ae=>{o.next(x,ae)})}),()=>{o.unsubscribe(x)}},j=r(i,[I,...R],{onSuccess:x=>{a.delete(h),g.onSuccess(x,A)},onError:x=>{a.delete(h),g.onError(x)}});return()=>{a.delete(h),j()}};if(typeof s=="string")return q(s);let L=T;return s.then(I=>{if(I instanceof Error)return h();s&&(L=q(I))}),()=>{L()}};return{unfollow(){m(),s=null},body:te(b),call:ne(b),header:oe(b),storage:ie(b),storageSubscription:J(b),unpin:se(b),_request:b}}}var Q=require("@polkadot-api/utils");var Ee=r=>{let e=re(r),t=H((a,d,s,c)=>e.request(s,c,{onSuccess:a,onError:d})),n=t("rpc_methods",[]).then(a=>n=new Set(Array.isArray(a)?a:a.methods));n.catch(Q.noop);let o=a=>a.has("transaction_unstable_submitAndWatch")?"transaction":"transactionWatch",p=G(e.request);return{chainHead:K(e.request),transaction:(a,d,s)=>{if(n instanceof Promise){let c=Q.noop,f=!0;return n.then(l=>{f&&(c=p(o(l),a,d,s))}),()=>{f=!1,c()}}return p(o(n),a,d,s)},destroy:()=>{e.disconnect()},request:t,_request:e.request}}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@polkadot-api/substrate-client", | ||
"version": "0.0.1-8167145a6504fc77f310715b5208be71992108b5.1.0", | ||
"version": "0.0.1-81aa776246f63e7c9d431e89d66d4a7f8651a0ae.1.0", | ||
"author": "Josep M Sobrepere (https://github.com/josepot)", | ||
@@ -44,4 +44,4 @@ "repository": { | ||
"@vitest/coverage-v8": "^0.34.3", | ||
"@polkadot-api/json-rpc-provider": "0.0.1-8167145a6504fc77f310715b5208be71992108b5.1.0", | ||
"@polkadot-api/utils": "0.0.1-8167145a6504fc77f310715b5208be71992108b5.1.0" | ||
"@polkadot-api/json-rpc-provider": "0.0.1-81aa776246f63e7c9d431e89d66d4a7f8651a0ae.1.0", | ||
"@polkadot-api/utils": "0.0.1-81aa776246f63e7c9d431e89d66d4a7f8651a0ae.1.0" | ||
}, | ||
@@ -48,0 +48,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
222491
212
12
2057