@tari-project/ootle-indexer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2023, The Tari Developer Community
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @tari-project/ootle-indexer
2
+
3
+ Indexer REST `Provider` for the Tari Ootle network — reads chain state, submits
4
+ transactions, and watches for finality via SSE.
5
+
6
+ ## Runtime support
7
+
8
+ | Package | Browser | Node ≥ 22 | Notes |
9
+ | ----------------------------- | ------- | --------- | ---------------------------- |
10
+ | `@tari-project/ootle-indexer` | ✓ | ✓ | `fetch` + SSE native in both |
11
+
12
+ This package has no DOM-specific code. `fetch` and SSE
13
+ (`response.body.getReader()` + `TextDecoder`) are native in both browsers and
14
+ Node ≥ 22, so the same artifact runs in either environment.
15
+
16
+ > **Node note:** Node ≥ 22 currently requires
17
+ > `NODE_OPTIONS=--experimental-wasm-modules` when running under `tsx` or plain
18
+ > `node` because `@tari-project/ootle` (a peer in the SDK) loads
19
+ > `@tari-project/ootle-wasm` as an ES module. See
20
+ > [`examples/node/README.md`](../../examples/node/README.md) for the rationale
21
+ > and forward plan.
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ pnpm add @tari-project/ootle-indexer
27
+ ```
28
+
29
+ ## Hello world
30
+
31
+ Connect to the Esmeralda testnet and read a substate:
32
+
33
+ ```ts
34
+ import { ProviderBuilder, Network } from "@tari-project/ootle-indexer";
35
+
36
+ const provider = await ProviderBuilder.new().withNetwork(Network.Esmeralda).connect();
37
+
38
+ const substate = await provider.getSubstate("component_0x…");
39
+ console.log(substate);
40
+ ```
41
+
42
+ For LocalNet, pass `Network.LocalNet`; the builder falls back to
43
+ `defaultIndexerUrl(Network.LocalNet)` (`http://localhost:12500`) when no URL is
44
+ configured.
45
+
46
+ ## Deep dive
47
+
48
+ For `ProviderBuilder`, `IndexerProvider`, `TransactionWatcher` /
49
+ `PendingTransaction`, and the lazy `WantInput` / `resolveWantInputs` flow, see
50
+ the [root README's "`@tari-project/ootle-indexer`" section](../../README.md#tari-projectootle-indexer).
51
+
52
+ ## Examples
53
+
54
+ Runnable browser apps and Node scripts live under
55
+ [`examples/`](../../examples/README.md) — the
56
+ [`indexer-explorer/`](../../examples/indexer-explorer/) React app browses
57
+ substates, transactions, and templates via this provider, and
58
+ [`examples/node/`](../../examples/node/README.md) drives it from headless
59
+ TypeScript.
@@ -0,0 +1,269 @@
1
+ import { CommitOutcome } from '@tari-project/ootle';
2
+ import { GetSubstatesResponse } from '@tari-project/ootle-ts-bindings';
3
+ import { GetTemplateDefinitionResponse } from '@tari-project/ootle-ts-bindings';
4
+ import { IndexerClient } from '@tari-project/indexer-client';
5
+ import { IndexerGetSubstateResponse } from '@tari-project/ootle-ts-bindings';
6
+ import { IndexerGetTransactionResultResponse } from '@tari-project/ootle-ts-bindings';
7
+ import { IndexerSubmitTransactionResponse } from '@tari-project/ootle-ts-bindings';
8
+ import { ListRecentTransactionsRequest } from '@tari-project/ootle-ts-bindings';
9
+ import { ListRecentTransactionsResponse } from '@tari-project/ootle-ts-bindings';
10
+ import { Network } from '@tari-project/ootle';
11
+ import { Provider } from '@tari-project/ootle';
12
+ import { SubstateId } from '@tari-project/ootle-ts-bindings';
13
+ import { SubstateRequirement } from '@tari-project/ootle-ts-bindings';
14
+ import { TemplateMetadata } from '@tari-project/ootle-ts-bindings';
15
+ import { TransactionEntry } from '@tari-project/ootle-ts-bindings';
16
+ import { TransactionEnvelope } from '@tari-project/ootle-ts-bindings';
17
+ import { transports } from '@tari-project/indexer-client';
18
+
19
+ export { IndexerClient }
20
+
21
+ export declare class IndexerProvider implements Provider {
22
+ private readonly client;
23
+ private readonly _network;
24
+ private readonly _url;
25
+ private _watcher;
26
+ readonly defaultTransactionTimeoutMs: number;
27
+ private constructor();
28
+ /**
29
+ * Creates an IndexerProvider and verifies connectivity by fetching the indexer identity.
30
+ */
31
+ static connect(options: IndexerProviderOptions): Promise<IndexerProvider>;
32
+ /** Exposes the underlying IndexerClient for advanced use (e.g. resolveWantInputs). */
33
+ getClient(): IndexerClient;
34
+ /**
35
+ * Returns a `PendingTransaction` that resolves via SSE when the network
36
+ * finalises the transaction, falling back to REST polling on timeout.
37
+ *
38
+ * The `TransactionWatcher` SSE loop is created lazily on the first call
39
+ * and reused for all subsequent calls on this provider instance.
40
+ */
41
+ watchTransactionSSE(txId: string, timeoutMs?: number): PendingTransaction;
42
+ /**
43
+ * Stops the SSE `TransactionWatcher` if one is running.
44
+ * Call this when the provider is no longer needed to release the connection.
45
+ */
46
+ stopWatcher(): void;
47
+ network(): Network;
48
+ getSubstate(substateId: string, version?: number | null): Promise<IndexerGetSubstateResponse>;
49
+ getStealthUtxo(resourceAddress: string, commitment: Uint8Array): Promise<IndexerGetSubstateResponse | null>;
50
+ fetchSubstates(requests: SubstateId[]): Promise<GetSubstatesResponse>;
51
+ getTemplateDefinition(templateAddress: string): Promise<GetTemplateDefinitionResponse>;
52
+ submitTransaction(envelope: TransactionEnvelope): Promise<IndexerSubmitTransactionResponse>;
53
+ getTransactionResult(transactionId: string): Promise<IndexerGetTransactionResultResponse>;
54
+ resolveInputs(inputs: SubstateRequirement[]): Promise<SubstateRequirement[]>;
55
+ listRecentTransactions(params: ListRecentTransactionsRequest): Promise<ListRecentTransactionsResponse>;
56
+ }
57
+
58
+ export declare interface IndexerProviderOptions {
59
+ /** Base URL of the indexer REST API, e.g. "http://localhost:18300" */
60
+ url: string;
61
+ network: Network;
62
+ /** Default timeout for `watchTransaction`, in milliseconds. Defaults to 60000ms. */
63
+ defaultTransactionTimeoutMs?: number;
64
+ }
65
+
66
+ /**
67
+ * A parsed SSE event from the indexer.
68
+ * The `type` field comes from the `event:` line; `data` is the parsed JSON payload.
69
+ */
70
+ export declare interface IndexerSseEvent {
71
+ type: string;
72
+ data: unknown;
73
+ }
74
+
75
+ /**
76
+ * Opens a persistent SSE connection to `url` using `fetch` and yields
77
+ * parsed events as an async generator.
78
+ *
79
+ * Works in browsers (Fetch + ReadableStream) and Node.js ≥ 18.
80
+ * Automatically reconnects after errors with a 5 s back-off.
81
+ * Stops when `signal` is aborted.
82
+ *
83
+ * Mirrors the `EventStream` / `into_stream()` pattern from the Rust ootle-rs crate.
84
+ *
85
+ * @throws {IndexerClientError} (caught + logged by the retry loop) if the SSE
86
+ * endpoint returns a non-success status.
87
+ */
88
+ export declare function openEventStream(url: string, signal: AbortSignal): AsyncGenerator<IndexerSseEvent>;
89
+
90
+ /**
91
+ * Parses a partial SSE buffer into discrete events, returning any unparsed
92
+ * remainder that should be carried forward to the next chunk.
93
+ */
94
+ export declare function parseSseChunk(buffer: string): {
95
+ events: IndexerSseEvent[];
96
+ remainder: string;
97
+ };
98
+
99
+ /**
100
+ * A handle for a submitted transaction.
101
+ *
102
+ * Mirrors `PendingTransaction` from the Rust ootle-rs crate.
103
+ *
104
+ * @example
105
+ * ```ts
106
+ * const pending = watcher.watch(txId, client);
107
+ * try {
108
+ * await pending.watch(); // SSE-driven, throws on non-Commit / timeout
109
+ * } catch (err) {
110
+ * if (err instanceof TransactionRejectedError) { ... }
111
+ * }
112
+ * const receipt = await pending.getReceipt(); // full receipt if needed
113
+ * ```
114
+ */
115
+ export declare class PendingTransaction {
116
+ private readonly txId;
117
+ private readonly watcher;
118
+ private readonly client;
119
+ private readonly timeoutMs;
120
+ private cancellation;
121
+ constructor(txId: string, watcher: TransactionWatcher, client: IndexerClient, timeoutMs: number);
122
+ /**
123
+ * Waits for the transaction to finalise via SSE, with REST as the verdict
124
+ * source when SSE is ambiguous. `Commit` resolves directly; `Abort` fetches
125
+ * the receipt once to distinguish `Reject` from `FeeIntentCommit`;
126
+ * `Indeterminate` or SSE silence falls back to REST polling within `timeoutMs`.
127
+ *
128
+ * @throws {TransactionRejectedError} on Reject or FeeIntentCommit (FIC's
129
+ * `.reason` is prefixed `"FeeIntentCommit: "`).
130
+ * @throws {TransactionTimeoutError} when neither SSE nor REST sees finality in time.
131
+ * @throws {OperationCancelledError} when `cancel()` was called.
132
+ */
133
+ watch(): Promise<CommitOutcome>;
134
+ private throwFromReceipt;
135
+ private restPollUntilFinal;
136
+ /** Sleep `ms`, waking early if `signal` aborts (so cancellation isn't delayed a full interval). */
137
+ private delay;
138
+ /**
139
+ * Cancels an in-flight `watch()`. The watch promise rejects with
140
+ * `OperationCancelledError`. Idempotent; a no-op when no watch is active.
141
+ */
142
+ cancel(): void;
143
+ /**
144
+ * Polls the indexer once for the current transaction result and returns
145
+ * the raw response. Useful for fetching full receipt data after `watch()`.
146
+ */
147
+ getReceipt(): Promise<IndexerGetTransactionResultResponse>;
148
+ }
149
+
150
+ /**
151
+ * Fluent builder for constructing an `IndexerProvider`.
152
+ * Mirrors `ProviderBuilder` from the Rust ootle-rs crate.
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * const provider = await ProviderBuilder.new()
157
+ * .withNetwork(Network.Esmeralda)
158
+ * .connect();
159
+ * ```
160
+ */
161
+ export declare class ProviderBuilder {
162
+ private _network;
163
+ private _url;
164
+ private _transactionTimeoutMs;
165
+ static new(): ProviderBuilder;
166
+ withNetwork(network: Network): this;
167
+ withUrl(url: string): this;
168
+ /**
169
+ * Sets the maximum time `watchTransaction` will wait for finalization.
170
+ * Mirrors `connect_with_transaction_timeout` from ootle-rs.
171
+ */
172
+ withTransactionTimeoutMs(ms: number): this;
173
+ /**
174
+ * Connects to the indexer. If no URL was set, falls back to `defaultIndexerUrl`
175
+ * for the configured network.
176
+ */
177
+ connect(): Promise<IndexerProvider>;
178
+ }
179
+
180
+ /**
181
+ * Resolves a list of `WantInput` descriptors by querying the indexer, returning
182
+ * fully-versioned `SubstateRequirement` objects ready to attach to a transaction.
183
+ *
184
+ * Mirrors `TransactionInputResolver` from the Rust ootle-rs crate.
185
+ *
186
+ * @throws {WalletError} when a `VaultForResource` query finds no matching vault for
187
+ * the given resource address (an account-shape problem on the caller's side).
188
+ */
189
+ export declare function resolveWantInputs(client: IndexerClient, wants: WantInput[]): Promise<SubstateRequirement[]>;
190
+
191
+ /**
192
+ * SSE-side decision before `PendingTransaction` maps it to a `TransactionOutcome`.
193
+ * `Indeterminate` covers the LocalNet quirk where a `TransactionFinalized` event
194
+ * arrives without `final_decision` — the REST receipt has the verdict.
195
+ */
196
+ declare type SseFinalizedDecision = {
197
+ decision: "Commit";
198
+ } | {
199
+ decision: "Reject";
200
+ reason: string;
201
+ } | {
202
+ decision: "Indeterminate";
203
+ };
204
+
205
+ export { TemplateMetadata }
206
+
207
+ export { TransactionEntry }
208
+
209
+ /**
210
+ * Subscribes to the indexer's SSE `/events` stream and routes
211
+ * `TransactionFinalized` events to waiting callers.
212
+ *
213
+ * The stream is paused (abort + reconnect deferred) when no transactions are
214
+ * being watched, and resumed on the first new `watch()` call.
215
+ * Mirrors `TransactionWatcher` from the Rust ootle-rs crate.
216
+ *
217
+ * Lifecycle: call `start()` once (idempotent), then obtain
218
+ * `PendingTransaction` handles via `watch()`. Call `stop()` to shut down.
219
+ */
220
+ export declare class TransactionWatcher {
221
+ private readonly baseUrl;
222
+ private pending;
223
+ private abortController;
224
+ private loopPromise;
225
+ constructor(baseUrl: string);
226
+ /**
227
+ * Starts the background SSE loop (idempotent — safe to call multiple times).
228
+ */
229
+ start(): void;
230
+ /**
231
+ * Stops the background loop and rejects any still-parked waiters with
232
+ * `IndexerClientError("TransactionWatcher stopped")`. In normal use
233
+ * `PendingTransaction` self-unregisters, so a hit here means a leaked handle.
234
+ */
235
+ stop(): void;
236
+ /**
237
+ * Returns a `PendingTransaction` that resolves when the network finalises
238
+ * the given transaction ID, throwing on Reject / FeeIntentCommit / timeout.
239
+ *
240
+ * Automatically starts the watcher loop if it isn't running yet.
241
+ */
242
+ watch(txId: string, client: IndexerClient, timeoutMs?: number): PendingTransaction;
243
+ /** Internal: register a waiter for a transaction ID. */
244
+ register(txId: string): Promise<SseFinalizedDecision>;
245
+ /** Internal: remove a pending waiter. */
246
+ unregister(txId: string): void;
247
+ private run;
248
+ }
249
+
250
+ export { transports }
251
+
252
+ /**
253
+ * Lazily describes an input the transaction needs, resolved by querying the indexer.
254
+ * Mirrors `WantInput` from the Rust ootle-rs crate.
255
+ *
256
+ * - `VaultForResource` — find the vault component that holds the given resource address.
257
+ * - `SpecificSubstate` — resolve a specific substate by ID (same as `resolveInputs` but
258
+ * deferred until `resolveWantInputs` is called).
259
+ */
260
+ export declare type WantInput = {
261
+ type: "VaultForResource";
262
+ resourceAddress: string;
263
+ } | {
264
+ type: "SpecificSubstate";
265
+ substateId: string;
266
+ version?: number | null;
267
+ };
268
+
269
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,513 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ import { IndexerClientError as e, Network as t, OperationCancelledError as n, TransactionRejectedError as r, TransactionTimeoutError as i, WalletError as a, classifyOutcome as o, defaultIndexerUrl as s, stealthUtxoSubstateId as c } from "@tari-project/ootle";
5
+ var l = Object.defineProperty, u = (e5, t3) => {
6
+ let n2 = {};
7
+ for (var r2 in e5) l(n2, r2, {
8
+ get: e5[r2],
9
+ enumerable: true
10
+ });
11
+ return t3 || l(n2, Symbol.toStringTag, { value: "Module" }), n2;
12
+ }, d = class e2 {
13
+ constructor(e5) {
14
+ __publicField(this, "url");
15
+ this.url = e5;
16
+ }
17
+ static new(t3) {
18
+ if (!t3.startsWith("http://") && !t3.startsWith("https://")) throw Error("URL must start with http:// or https://");
19
+ return t3.endsWith("/") && (t3 = t3.slice(0, -1)), new e2(t3);
20
+ }
21
+ sendGet(e5, t3, n2) {
22
+ return this.sendRequest(e5, {
23
+ method: "GET",
24
+ params: t3
25
+ }, n2);
26
+ }
27
+ sendHead(e5, t3, n2) {
28
+ return this.sendRequest(e5, {
29
+ method: "HEAD",
30
+ params: t3
31
+ }, n2);
32
+ }
33
+ sendPost(e5, t3, n2) {
34
+ return this.sendRequest(e5, {
35
+ method: "POST",
36
+ body: t3
37
+ }, n2);
38
+ }
39
+ sendPut(e5, t3, n2) {
40
+ return this.sendRequest(e5, {
41
+ method: "PUT",
42
+ body: t3
43
+ }, n2);
44
+ }
45
+ sendDelete(e5, t3, n2) {
46
+ return this.sendRequest(e5, {
47
+ method: "DELETE",
48
+ body: t3
49
+ }, n2);
50
+ }
51
+ async sendRequest(e5, t3, n2) {
52
+ let r2 = new AbortController(), i2 = r2.signal, a2 = (n2 == null ? void 0 : n2.timeout_millis) ? setTimeout(() => {
53
+ r2.abort("Timeout");
54
+ }, n2.timeout_millis) : null;
55
+ e5.startsWith("/") && (e5 = e5.slice(1));
56
+ let o2 = null;
57
+ if (typeof t3.params == "object" && t3.params !== null) {
58
+ let e6 = new URLSearchParams();
59
+ for (let [n3, r3] of Object.entries(t3.params)) r3 != null && e6.append(n3, r3.toString());
60
+ o2 = e6;
61
+ }
62
+ typeof t3.body == "object" && t3.body !== null && (t3.headers || (t3.headers = {}), t3.headers["Content-Type"] = "application/json", t3.body = JSON.stringify(t3.body));
63
+ let s2 = `${this.url}/${e5}`;
64
+ o2 && o2.toString().length > 0 && (s2 += `?${o2.toString()}`);
65
+ let c2 = await fetch(s2, {
66
+ signal: i2,
67
+ ...t3
68
+ });
69
+ if (a2 && clearTimeout(a2), !c2.ok) {
70
+ let e6 = await c2.text();
71
+ throw Error(`HTTP ${c2.status}: ${c2.statusText}${e6 ? ` - ${e6}` : ""}`);
72
+ }
73
+ let l2 = await c2.json();
74
+ if (l2.error) throw Error(`${l2.error.code}: ${l2.error.message}`);
75
+ return l2;
76
+ }
77
+ }, f = /* @__PURE__ */ u({ FetchTransport: () => d }), p = class e3 {
78
+ constructor(e5) {
79
+ __publicField(this, "transport");
80
+ __publicField(this, "p");
81
+ this.transport = e5;
82
+ }
83
+ static new(t3) {
84
+ return new e3(t3);
85
+ }
86
+ static usingFetchTransport(t3) {
87
+ return e3.new(d.new(t3));
88
+ }
89
+ getTransport() {
90
+ return this.transport;
91
+ }
92
+ identityGet() {
93
+ return this.transport.sendGet("identity", {});
94
+ }
95
+ waitUntilReady() {
96
+ return this.transport.sendGet("wait-until-ready", {});
97
+ }
98
+ epochManagerStats() {
99
+ return this.transport.sendGet("epoch-manager/stats", {});
100
+ }
101
+ networkInfo() {
102
+ return this.transport.sendGet("network", {});
103
+ }
104
+ networkStats() {
105
+ return this.transport.sendGet("network/stats", {});
106
+ }
107
+ getConnections() {
108
+ return this.transport.sendGet("network/connections", {});
109
+ }
110
+ getNonFungibles(e5) {
111
+ return this.transport.sendGet("non-fungibles", e5);
112
+ }
113
+ substatesGet(e5, t3) {
114
+ return this.transport.sendGet(`substates/${encodeURIComponent(e5)}`, t3);
115
+ }
116
+ fetchSubstates(e5) {
117
+ return this.transport.sendPost("substates/fetch", e5);
118
+ }
119
+ submitTransaction(e5) {
120
+ return this.transport.sendPost("transactions", e5);
121
+ }
122
+ getTransactionResult(e5) {
123
+ return this.transport.sendGet(`transactions/${encodeURIComponent(e5)}/result`, {});
124
+ }
125
+ listRecentTransactions(e5) {
126
+ return this.transport.sendGet("transactions/recent", e5);
127
+ }
128
+ queryTransactionEvents(e5) {
129
+ return this.transport.sendGet("transactions/events", e5);
130
+ }
131
+ listTransactionReceipts(e5) {
132
+ return this.transport.sendGet("transaction-receipts", e5);
133
+ }
134
+ getTransactionReceipt(e5) {
135
+ return this.transport.sendGet(`transaction-receipts/${e5}`, {});
136
+ }
137
+ templatesGet(e5) {
138
+ return this.transport.sendGet(`templates/${encodeURIComponent(e5)}`, {});
139
+ }
140
+ templatesList(e5 = 0) {
141
+ return this.transport.sendGet("templates", { limit: e5 });
142
+ }
143
+ templatesListAuthored(e5) {
144
+ return this.transport.sendPost("templates", e5);
145
+ }
146
+ resourcesGet(e5) {
147
+ return this.transport.sendGet(`resources/${encodeURIComponent(e5)}`, {});
148
+ }
149
+ };
150
+ function m(e5) {
151
+ let t3 = [], n2 = e5.split(/\n\n|\r\n\r\n/), r2 = n2.pop() ?? "";
152
+ for (let e6 of n2) {
153
+ if (!e6.trim()) continue;
154
+ let n3 = "message", r3 = [];
155
+ for (let t4 of e6.split(/\n|\r\n/)) t4.startsWith("event:") ? n3 = t4.slice(6).trim() : t4.startsWith("data:") && r3.push(t4.slice(5).trim());
156
+ if (r3.length === 0) continue;
157
+ let i2 = r3.join("\n"), a2 = i2;
158
+ try {
159
+ a2 = JSON.parse(i2);
160
+ } catch {
161
+ }
162
+ t3.push({
163
+ type: n3,
164
+ data: a2
165
+ });
166
+ }
167
+ return {
168
+ events: t3,
169
+ remainder: r2
170
+ };
171
+ }
172
+ async function* h(t3, n2) {
173
+ for (; !n2.aborted; ) {
174
+ let r2 = new AbortController(), i2 = () => r2.abort();
175
+ n2.addEventListener("abort", i2, { once: true });
176
+ try {
177
+ let i3 = await fetch(t3, {
178
+ signal: r2.signal,
179
+ headers: {
180
+ Accept: "text/event-stream",
181
+ "Cache-Control": "no-cache"
182
+ }
183
+ });
184
+ if (!i3.ok || !i3.body) {
185
+ let n3 = Number.isFinite(i3.status) ? i3.status : void 0;
186
+ throw new e(`SSE connection failed: HTTP ${i3.status}`, {
187
+ status: n3,
188
+ url: t3
189
+ });
190
+ }
191
+ let a2 = i3.body.getReader(), o2 = new TextDecoder(), s2 = "";
192
+ try {
193
+ for (; !n2.aborted; ) {
194
+ let { done: e5, value: t4 } = await a2.read();
195
+ if (e5) break;
196
+ s2 += o2.decode(t4, { stream: true });
197
+ let { events: n3, remainder: r3 } = m(s2);
198
+ s2 = r3;
199
+ for (let e6 of n3) yield e6;
200
+ }
201
+ } finally {
202
+ a2.cancel();
203
+ }
204
+ } catch (e5) {
205
+ if (n2.aborted || e5.name === "AbortError") return;
206
+ console.warn("[ootle-indexer] SSE stream error, retrying in 5 s:", e5.message), await new Promise((e6) => {
207
+ let t4 = setTimeout(e6, 5e3);
208
+ n2.addEventListener("abort", () => {
209
+ clearTimeout(t4), e6();
210
+ }, { once: true });
211
+ });
212
+ } finally {
213
+ n2.removeEventListener("abort", i2);
214
+ }
215
+ }
216
+ }
217
+ var g = 500, _ = 3e3, v = class {
218
+ constructor(e5) {
219
+ __publicField(this, "baseUrl");
220
+ __publicField(this, "pending", /* @__PURE__ */ new Map());
221
+ __publicField(this, "abortController", null);
222
+ __publicField(this, "loopPromise", null);
223
+ this.baseUrl = e5.endsWith("/") ? e5.slice(0, -1) : e5;
224
+ }
225
+ start() {
226
+ this.abortController && !this.abortController.signal.aborted || (this.abortController = new AbortController(), this.loopPromise = this.run(this.abortController.signal));
227
+ }
228
+ stop() {
229
+ var _a;
230
+ (_a = this.abortController) == null ? void 0 : _a.abort();
231
+ let t3 = new e("TransactionWatcher stopped", { url: this.baseUrl });
232
+ for (let e5 of this.pending.values()) e5.reject(t3);
233
+ this.pending.clear();
234
+ }
235
+ watch(e5, t3, n2 = 32e3) {
236
+ return this.start(), new y(e5, this, t3, n2);
237
+ }
238
+ register(e5) {
239
+ return new Promise((t3, n2) => {
240
+ this.pending.set(e5, {
241
+ resolve: t3,
242
+ reject: n2
243
+ });
244
+ });
245
+ }
246
+ unregister(e5) {
247
+ this.pending.delete(e5);
248
+ }
249
+ async run(e5) {
250
+ let t3 = `${this.baseUrl}/events`;
251
+ for await (let n2 of h(t3, e5)) {
252
+ if (n2.type !== "TransactionFinalized") continue;
253
+ let e6 = n2.data, t4 = this.pending.get(e6.transaction_id);
254
+ if (!t4) continue;
255
+ this.pending.delete(e6.transaction_id);
256
+ let r2 = e6.final_decision;
257
+ if (r2 === "Commit") t4.resolve({ decision: "Commit" });
258
+ else if (typeof r2 == "object" && r2 && "Abort" in r2) {
259
+ let n3 = e6.abort_details ?? JSON.stringify(r2.Abort);
260
+ t4.resolve({
261
+ decision: "Reject",
262
+ reason: n3
263
+ });
264
+ } else t4.resolve({ decision: "Indeterminate" });
265
+ }
266
+ }
267
+ }, y = class {
268
+ constructor(e5, t3, n2, r2) {
269
+ __publicField(this, "txId");
270
+ __publicField(this, "watcher");
271
+ __publicField(this, "client");
272
+ __publicField(this, "timeoutMs");
273
+ __publicField(this, "cancellation", null);
274
+ this.txId = e5, this.watcher = t3, this.client = n2, this.timeoutMs = r2;
275
+ }
276
+ async watch() {
277
+ let e5 = this.watcher.register(this.txId), t3 = Date.now() + this.timeoutMs, n2 = null, r2 = new Promise((e6) => {
278
+ n2 = setTimeout(() => e6("sse-timeout"), this.timeoutMs);
279
+ }), i2 = () => {
280
+ }, a2 = new Promise((e6, t4) => {
281
+ i2 = t4;
282
+ }), o2 = new AbortController();
283
+ this.cancellation = {
284
+ promise: a2,
285
+ reject: i2,
286
+ abort: o2
287
+ };
288
+ try {
289
+ let i3 = await Promise.race([
290
+ e5,
291
+ r2,
292
+ this.cancellation.promise
293
+ ]);
294
+ if (n2 !== null && clearTimeout(n2), i3 === "sse-timeout") return await Promise.race([this.restPollUntilFinal(Date.now() + _, o2.signal, _), a2]);
295
+ if (i3.decision === "Indeterminate") return await Promise.race([this.restPollUntilFinal(t3, o2.signal, 0), a2]);
296
+ if (i3.decision === "Commit") return { outcome: "Commit" };
297
+ let s2 = await this.client.getTransactionResult(this.txId);
298
+ return this.throwFromReceipt(s2, i3.reason);
299
+ } finally {
300
+ this.watcher.unregister(this.txId), n2 !== null && clearTimeout(n2), this.cancellation = null;
301
+ }
302
+ }
303
+ throwFromReceipt(e5, t3) {
304
+ let n2 = o(e5.result);
305
+ if ((n2 == null ? void 0 : n2.outcome) === "FeeIntentCommit") throw new r(`Transaction ${this.txId} only committed fees (execution aborted): ${n2.reason ?? t3}`, {
306
+ txId: this.txId,
307
+ reason: `FeeIntentCommit: ${n2.reason ?? t3}`
308
+ });
309
+ let i2 = (n2 == null ? void 0 : n2.reason) ?? t3;
310
+ throw new r(`Transaction ${this.txId} was rejected: ${i2}`, {
311
+ txId: this.txId,
312
+ reason: i2
313
+ });
314
+ }
315
+ async restPollUntilFinal(e5, t3, r2) {
316
+ let a2;
317
+ do {
318
+ if (t3.aborted) throw new n(`Wait for transaction ${this.txId} was cancelled`);
319
+ let r3 = null;
320
+ try {
321
+ r3 = await this.client.getTransactionResult(this.txId), a2 = null;
322
+ } catch (e6) {
323
+ a2 = e6;
324
+ }
325
+ if (r3) {
326
+ let e6 = o(r3.result);
327
+ if (e6) return e6.outcome === "Commit" ? { outcome: "Commit" } : this.throwFromReceipt(r3, e6.reason ?? "");
328
+ }
329
+ if (Date.now() >= e5) break;
330
+ await this.delay(g, t3);
331
+ } while (Date.now() < e5 && !t3.aborted);
332
+ if (t3.aborted) throw new n(`Wait for transaction ${this.txId} was cancelled`);
333
+ let s2 = this.timeoutMs + r2, c2 = r2 > 0 ? ` (incl. ${r2}ms grace)` : "";
334
+ throw new i(`Transaction ${this.txId} did not finalise within ${s2}ms${c2}`, {
335
+ txId: this.txId,
336
+ ...a2 == null ? {} : { cause: a2 }
337
+ });
338
+ }
339
+ delay(e5, t3) {
340
+ return new Promise((n2) => {
341
+ if (t3.aborted) {
342
+ n2();
343
+ return;
344
+ }
345
+ let r2 = () => {
346
+ clearTimeout(i2), n2();
347
+ }, i2 = setTimeout(() => {
348
+ t3.removeEventListener("abort", r2), n2();
349
+ }, e5);
350
+ t3.addEventListener("abort", r2, { once: true });
351
+ });
352
+ }
353
+ cancel() {
354
+ var _a, _b;
355
+ this.watcher.unregister(this.txId), (_a = this.cancellation) == null ? void 0 : _a.abort.abort(), (_b = this.cancellation) == null ? void 0 : _b.reject(new n(`Wait for transaction ${this.txId} was cancelled`));
356
+ }
357
+ async getReceipt() {
358
+ return this.client.getTransactionResult(this.txId);
359
+ }
360
+ };
361
+ function b(e5) {
362
+ let t3 = e5 instanceof Error ? e5.message : String(e5);
363
+ return /not found/i.test(t3) || t3.includes("404");
364
+ }
365
+ var x = class t2 {
366
+ constructor(e5, t3, n2, r2) {
367
+ __publicField(this, "client");
368
+ __publicField(this, "_network");
369
+ __publicField(this, "_url");
370
+ __publicField(this, "_watcher", null);
371
+ __publicField(this, "defaultTransactionTimeoutMs");
372
+ this.client = e5, this._network = t3, this._url = n2, this.defaultTransactionTimeoutMs = r2;
373
+ }
374
+ static async connect(e5) {
375
+ let n2 = p.usingFetchTransport(e5.url);
376
+ return await n2.identityGet(), new t2(n2, e5.network, e5.url, e5.defaultTransactionTimeoutMs ?? 6e4);
377
+ }
378
+ getClient() {
379
+ return this.client;
380
+ }
381
+ watchTransactionSSE(e5, t3) {
382
+ return this._watcher || (this._watcher = new v(this._url), this._watcher.start()), this._watcher.watch(e5, this.client, t3 ?? this.defaultTransactionTimeoutMs);
383
+ }
384
+ stopWatcher() {
385
+ var _a;
386
+ (_a = this._watcher) == null ? void 0 : _a.stop(), this._watcher = null;
387
+ }
388
+ network() {
389
+ return this._network;
390
+ }
391
+ async getSubstate(e5, t3 = null) {
392
+ return this.client.substatesGet(e5, {
393
+ version: t3,
394
+ local_search_only: false
395
+ });
396
+ }
397
+ async getStealthUtxo(e5, t3) {
398
+ let n2 = c(e5, t3);
399
+ try {
400
+ return await this.getSubstate(n2);
401
+ } catch (e6) {
402
+ if (b(e6)) return null;
403
+ throw e6;
404
+ }
405
+ }
406
+ async fetchSubstates(e5) {
407
+ return this.client.fetchSubstates({
408
+ requests: e5,
409
+ cached_only: false
410
+ });
411
+ }
412
+ async getTemplateDefinition(e5) {
413
+ return this.client.templatesGet(e5);
414
+ }
415
+ async submitTransaction(e5) {
416
+ return this.client.getTransport().sendPost("transactions", { transaction: e5 });
417
+ }
418
+ async getTransactionResult(e5) {
419
+ return this.client.getTransactionResult(e5);
420
+ }
421
+ async resolveInputs(t3) {
422
+ return await Promise.all(t3.map(async (t4) => {
423
+ if (t4.version !== null) return t4;
424
+ try {
425
+ let e5 = await this.client.substatesGet(t4.substate_id, {
426
+ version: null,
427
+ local_search_only: false
428
+ });
429
+ return {
430
+ substate_id: t4.substate_id,
431
+ version: e5.version
432
+ };
433
+ } catch (n2) {
434
+ let r2 = n2 instanceof Error ? n2.message : String(n2);
435
+ throw b(n2) ? new e(`Failed to find input "${t4.substate_id}": ${r2}. Verify the substate id is correct (typo? wrong network?) or wait for the producing transaction to finalize.`, {
436
+ cause: n2,
437
+ url: this._url
438
+ }) : new e(`Failed to resolve input "${t4.substate_id}": ${r2}. Check the indexer URL points at the same network as the substate.`, {
439
+ cause: n2,
440
+ url: this._url
441
+ });
442
+ }
443
+ }));
444
+ }
445
+ async listRecentTransactions(e5) {
446
+ return await this.client.listRecentTransactions(e5);
447
+ }
448
+ }, S = class e4 {
449
+ constructor() {
450
+ __publicField(this, "_network", t.LocalNet);
451
+ __publicField(this, "_url", null);
452
+ __publicField(this, "_transactionTimeoutMs", 6e4);
453
+ }
454
+ static new() {
455
+ return new e4();
456
+ }
457
+ withNetwork(e5) {
458
+ return this._network = e5, this;
459
+ }
460
+ withUrl(e5) {
461
+ return this._url = e5, this;
462
+ }
463
+ withTransactionTimeoutMs(e5) {
464
+ return this._transactionTimeoutMs = e5, this;
465
+ }
466
+ async connect() {
467
+ let e5 = {
468
+ url: this._url ?? s(this._network),
469
+ network: this._network,
470
+ defaultTransactionTimeoutMs: this._transactionTimeoutMs
471
+ };
472
+ return x.connect(e5);
473
+ }
474
+ };
475
+ async function C(e5, t3) {
476
+ return Promise.all(t3.map(async (t4) => {
477
+ if (t4.type === "SpecificSubstate") {
478
+ if (t4.version != null) return {
479
+ substate_id: t4.substateId,
480
+ version: t4.version
481
+ };
482
+ let n3 = await e5.substatesGet(t4.substateId, {
483
+ version: null,
484
+ local_search_only: false
485
+ });
486
+ return {
487
+ substate_id: t4.substateId,
488
+ version: n3.version
489
+ };
490
+ }
491
+ let n2 = {
492
+ filter_by_template: t4.resourceAddress,
493
+ filter_by_type: "Vault",
494
+ limit: 1
495
+ }, r2 = (await e5.getTransport().sendGet("substates", n2)).substates.find((e6) => e6.template_address === t4.resourceAddress || e6.substate_id === t4.resourceAddress);
496
+ if (!r2) throw new a(`Could not find a vault for resource address: ${t4.resourceAddress}`);
497
+ return {
498
+ substate_id: r2.substate_id,
499
+ version: r2.version
500
+ };
501
+ }));
502
+ }
503
+ export {
504
+ p as IndexerClient,
505
+ x as IndexerProvider,
506
+ y as PendingTransaction,
507
+ S as ProviderBuilder,
508
+ v as TransactionWatcher,
509
+ h as openEventStream,
510
+ m as parseSseChunk,
511
+ C as resolveWantInputs,
512
+ f as transports
513
+ };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@tari-project/ootle-indexer",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "browser": "./dist/index.js",
14
+ "node": "./dist/index.js",
15
+ "import": "./dist/index.js",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "@tari-project/indexer-client": "^1.2.1",
21
+ "@tari-project/ootle-ts-bindings": "^1.30.0",
22
+ "@tari-project/ootle": "0.1.0"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^25.5.0",
26
+ "@microsoft/api-extractor": "^7.57.7",
27
+ "typescript": "^5.9.3",
28
+ "unplugin-dts": "^1.0.0-beta.6",
29
+ "vitest": "^4.1.0",
30
+ "vite": "^8.0.1",
31
+ "vite-plugin-top-level-await": "^1.6.0",
32
+ "vite-plugin-wasm": "^3.6.0"
33
+ },
34
+ "scripts": {
35
+ "build": "tsc -b && vite build",
36
+ "test": "vitest run --passWithNoTests"
37
+ }
38
+ }