@hergmes/sdk 0.0.0-stage → 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/README.md +281 -2
- package/dist/index.d.ts +536 -0
- package/dist/index.js +1215 -0
- package/package.json +48 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1215 @@
|
|
|
1
|
+
import { ensureUTxOBigInt } from "@fleet-sdk/common";
|
|
2
|
+
import { serializeTransaction } from "@fleet-sdk/serializer";
|
|
3
|
+
// src/error.ts
|
|
4
|
+
/**
|
|
5
|
+
* A response other than 2xx. `code` and `reason` are absent when the body is not the relay's
|
|
6
|
+
* error, as with an unknown route or a proxy's own page. `retryAfter` is in seconds, from the
|
|
7
|
+
* `Retry-After` header, and is set on every 503 the relay sends.
|
|
8
|
+
*/
|
|
9
|
+
var RelayError = class RelayError extends Error {
|
|
10
|
+
name = "RelayError";
|
|
11
|
+
status;
|
|
12
|
+
code;
|
|
13
|
+
reason;
|
|
14
|
+
retryAfter;
|
|
15
|
+
constructor(status, message, fields = {}) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.code = fields.code;
|
|
19
|
+
this.reason = fields.reason;
|
|
20
|
+
this.retryAfter = fields.retryAfter;
|
|
21
|
+
}
|
|
22
|
+
/** Reads a failed response: the relay's `{ error, reason?, message }`, or anything else. */
|
|
23
|
+
static async from(response) {
|
|
24
|
+
const retryAfter = seconds(response.headers.get("retry-after"));
|
|
25
|
+
const text = await response.text().catch(() => "");
|
|
26
|
+
const body = parse(text);
|
|
27
|
+
if (body) return new RelayError(response.status, body.message, {
|
|
28
|
+
code: body.error,
|
|
29
|
+
...body.reason === void 0 ? {} : { reason: body.reason },
|
|
30
|
+
...retryAfter === void 0 ? {} : { retryAfter }
|
|
31
|
+
});
|
|
32
|
+
const message = text.trim() === "" ? `HTTP ${String(response.status)}` : text.trim();
|
|
33
|
+
return new RelayError(response.status, message, retryAfter === void 0 ? {} : { retryAfter });
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
function parse(text) {
|
|
37
|
+
let value;
|
|
38
|
+
try {
|
|
39
|
+
value = JSON.parse(text);
|
|
40
|
+
} catch {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
44
|
+
const { error, reason, message } = value;
|
|
45
|
+
if (typeof error !== "string" || typeof message !== "string") return void 0;
|
|
46
|
+
if (reason !== void 0 && typeof reason !== "string") return void 0;
|
|
47
|
+
return reason === void 0 ? {
|
|
48
|
+
error,
|
|
49
|
+
message
|
|
50
|
+
} : {
|
|
51
|
+
error,
|
|
52
|
+
reason,
|
|
53
|
+
message
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** `Retry-After` in seconds. The relay sends whole seconds; an HTTP date is read too. */
|
|
57
|
+
function seconds(header) {
|
|
58
|
+
if (header === null) return void 0;
|
|
59
|
+
const trimmed = header.trim();
|
|
60
|
+
if (/^\d+$/.test(trimmed)) return Number(trimmed);
|
|
61
|
+
const date = Date.parse(trimmed);
|
|
62
|
+
if (Number.isNaN(date)) return void 0;
|
|
63
|
+
return Math.max(0, Math.ceil((date - Date.now()) / 1e3));
|
|
64
|
+
}
|
|
65
|
+
// src/call.ts
|
|
66
|
+
/**
|
|
67
|
+
* Calls an app's function. What it throws is the app's: rethrown on a task of its own, where
|
|
68
|
+
* it surfaces as any uncaught error does, so the SDK's own work and the other listeners carry
|
|
69
|
+
* on.
|
|
70
|
+
*/
|
|
71
|
+
function call(listener, value) {
|
|
72
|
+
try {
|
|
73
|
+
listener?.(value);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
setTimeout(() => {
|
|
76
|
+
throw error;
|
|
77
|
+
}, 0);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* A Svelte store's `subscribe` over a handle's state and the listeners its batched calls go
|
|
82
|
+
* to: `listener` gets the current state at once, then each change, never the same state twice
|
|
83
|
+
* in a row (a change made before the batched call would otherwise come again).
|
|
84
|
+
*/
|
|
85
|
+
function store(current, listeners, listener) {
|
|
86
|
+
let last = current;
|
|
87
|
+
call(listener, last);
|
|
88
|
+
const changed = (state) => {
|
|
89
|
+
if (state === last) return;
|
|
90
|
+
last = state;
|
|
91
|
+
listener(state);
|
|
92
|
+
};
|
|
93
|
+
listeners.add(changed);
|
|
94
|
+
return () => {
|
|
95
|
+
listeners.delete(changed);
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
// src/machine.ts
|
|
99
|
+
/**
|
|
100
|
+
* One key's subscription as a state machine, with no socket and no timer: it takes the
|
|
101
|
+
* relay's messages and the snapshot's result, and answers what to send or fetch. A box
|
|
102
|
+
* subscription goes snapshot → catching up → live, and back to a snapshot whenever its view
|
|
103
|
+
* can't be trusted: the relay asks (`resync_required`), a block does not chain, or a message
|
|
104
|
+
* names boxes the view does not hold as it says. It survives the socket: after a reconnect it
|
|
105
|
+
* subscribes from the key's last change, and a failure that is for now waits and starts
|
|
106
|
+
* again.
|
|
107
|
+
*
|
|
108
|
+
* The relay sends a key only the blocks that change it, each naming the key's change before
|
|
109
|
+
* it (`prev`), and its overlays and balances name the key's last change. So the view follows
|
|
110
|
+
* the key's chain of changes, and a skipped one shows as a message that names a change the
|
|
111
|
+
* view does not have.
|
|
112
|
+
*/
|
|
113
|
+
/**
|
|
114
|
+
* Codes a refusal or a failed read carries when it is for now: no answer, an answer that is not
|
|
115
|
+
* the relay's (a proxy's page), and over the socket, which has no status, the 5xx codes. A 5xx
|
|
116
|
+
* status with any code is for now too.
|
|
117
|
+
*/
|
|
118
|
+
const TRANSIENT = /* @__PURE__ */ new Set([
|
|
119
|
+
"network",
|
|
120
|
+
"bad_response",
|
|
121
|
+
"node_error",
|
|
122
|
+
"internal_error",
|
|
123
|
+
"node_unavailable",
|
|
124
|
+
"not_ready"
|
|
125
|
+
]);
|
|
126
|
+
/** Statuses below 500 that are for now: a timeout and a rate limit, as a proxy may answer. */
|
|
127
|
+
const TRANSIENT_STATUS = /* @__PURE__ */ new Set([408, 429]);
|
|
128
|
+
/** Whether a failure is for now: it has a `retryAfter`, or it is a network error or a 5xx. */
|
|
129
|
+
function transient(error) {
|
|
130
|
+
return error.retryAfter !== void 0 || (error.status ?? 0) >= 500 || error.status !== void 0 && TRANSIENT_STATUS.has(error.status) || error.status === void 0 && TRANSIENT.has(error.code);
|
|
131
|
+
}
|
|
132
|
+
/** A failed REST read as a {@link SubscriptionError}. */
|
|
133
|
+
function failure(e) {
|
|
134
|
+
if (e instanceof RelayError) return {
|
|
135
|
+
code: e.code ?? `http_${String(e.status)}`,
|
|
136
|
+
message: e.message,
|
|
137
|
+
status: e.status,
|
|
138
|
+
...e.retryAfter === void 0 ? {} : { retryAfter: e.retryAfter }
|
|
139
|
+
};
|
|
140
|
+
return {
|
|
141
|
+
code: e instanceof TypeError ? "network" : "bad_response",
|
|
142
|
+
message: String(e)
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
var KeyMachine = class {
|
|
146
|
+
key;
|
|
147
|
+
/** Whether the subscription follows boxes; otherwise only an address's balance. */
|
|
148
|
+
boxes;
|
|
149
|
+
#state;
|
|
150
|
+
#context;
|
|
151
|
+
/** Whether a subscribe can be sent now; otherwise it waits for {@link connected}. */
|
|
152
|
+
#online;
|
|
153
|
+
/** The id of the subscribe whose answer is awaited; the key's other messages are dropped. */
|
|
154
|
+
#awaiting;
|
|
155
|
+
/** Bumped whenever a snapshot read or a retry in flight stops being the current one. */
|
|
156
|
+
#generation = 0;
|
|
157
|
+
#working;
|
|
158
|
+
/** Retries since the key was last live. */
|
|
159
|
+
#attempt = 0;
|
|
160
|
+
/** Ended for good: nothing resumes it. */
|
|
161
|
+
#ended = false;
|
|
162
|
+
/**
|
|
163
|
+
* `online` says whether the socket is open or opening. `previous` is the state of the
|
|
164
|
+
* subscription this one replaces, if any: its last boxes and balance stay visible until this
|
|
165
|
+
* one has its own, as while recovering.
|
|
166
|
+
*/
|
|
167
|
+
constructor(key, boxes, context, online = true, previous) {
|
|
168
|
+
this.key = key;
|
|
169
|
+
this.boxes = boxes;
|
|
170
|
+
this.#context = context;
|
|
171
|
+
this.#online = online;
|
|
172
|
+
const phase = boxes ? "snapshot" : "catching_up";
|
|
173
|
+
const view = boxes ? previous?.boxes : void 0;
|
|
174
|
+
const balance = previous?.balance;
|
|
175
|
+
this.#state = Object.freeze({
|
|
176
|
+
key,
|
|
177
|
+
phase,
|
|
178
|
+
boxes: view,
|
|
179
|
+
balance,
|
|
180
|
+
error: void 0
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
get state() {
|
|
184
|
+
return this.#state;
|
|
185
|
+
}
|
|
186
|
+
/** The first actions: a snapshot, or a balance-only subscribe. */
|
|
187
|
+
start() {
|
|
188
|
+
return this.boxes ? this.#snapshot() : this.#subscribe(void 0);
|
|
189
|
+
}
|
|
190
|
+
/** A retry's wait ended. Stale generations are ignored. */
|
|
191
|
+
retry(generation) {
|
|
192
|
+
if (generation !== this.#generation || this.#state.phase !== "waiting") return [];
|
|
193
|
+
return this.start();
|
|
194
|
+
}
|
|
195
|
+
/** The snapshot read: its block and every box at it. Stale generations are ignored. */
|
|
196
|
+
snapshotLoaded(generation, asOf, boxes) {
|
|
197
|
+
if (generation !== this.#generation || this.#state.phase !== "snapshot") return [];
|
|
198
|
+
this.#working = {
|
|
199
|
+
last: void 0,
|
|
200
|
+
knownAt: asOf,
|
|
201
|
+
boxes: new Map(boxes.map((box) => [box.boxId, ensureUTxOBigInt(box)])),
|
|
202
|
+
pending: [],
|
|
203
|
+
confirmed: void 0,
|
|
204
|
+
spendable: void 0
|
|
205
|
+
};
|
|
206
|
+
return this.#subscribe(asOf);
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* The snapshot failed. An expired cursor starts it again; a failure for now waits and starts
|
|
210
|
+
* again; anything else is a refusal.
|
|
211
|
+
*/
|
|
212
|
+
snapshotFailed(generation, error) {
|
|
213
|
+
if (generation !== this.#generation || this.#state.phase !== "snapshot") return [];
|
|
214
|
+
if (error.code === "cursor_expired") {
|
|
215
|
+
this.#context.onResync({
|
|
216
|
+
key: this.key,
|
|
217
|
+
by: "relay",
|
|
218
|
+
reason: "cursor_expired"
|
|
219
|
+
});
|
|
220
|
+
return this.#snapshot();
|
|
221
|
+
}
|
|
222
|
+
return this.#fail(error);
|
|
223
|
+
}
|
|
224
|
+
/** A message for this key. */
|
|
225
|
+
receive(message) {
|
|
226
|
+
const phase = this.#state.phase;
|
|
227
|
+
if (phase !== "catching_up" && phase !== "live") return [];
|
|
228
|
+
if (this.#awaiting !== void 0) {
|
|
229
|
+
if (!(message.type === "subscribed" || message.type === "rejected" || message.type === "resync_required") || message.id !== this.#awaiting) return [];
|
|
230
|
+
this.#awaiting = void 0;
|
|
231
|
+
}
|
|
232
|
+
switch (message.type) {
|
|
233
|
+
case "subscribed": return [];
|
|
234
|
+
case "rejected": {
|
|
235
|
+
const error = {
|
|
236
|
+
code: message.reason,
|
|
237
|
+
message: message.reason
|
|
238
|
+
};
|
|
239
|
+
if (message.retryAfter !== void 0) error.retryAfter = message.retryAfter;
|
|
240
|
+
return this.#fail(error);
|
|
241
|
+
}
|
|
242
|
+
case "resync_required": return this.#resync(message.reason, "relay");
|
|
243
|
+
case "block": return this.#block(message);
|
|
244
|
+
case "rollback": return this.#rollback(message);
|
|
245
|
+
case "mempool": return this.#mempool(message);
|
|
246
|
+
case "balance": return this.#balance(message);
|
|
247
|
+
case "tip": return [];
|
|
248
|
+
}
|
|
249
|
+
return [];
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* The socket closed: nothing more comes for the subscription it carried. The working view
|
|
253
|
+
* stays, to resume from; a snapshot read carries on, and a retry still waits.
|
|
254
|
+
*/
|
|
255
|
+
disconnected() {
|
|
256
|
+
this.#online = false;
|
|
257
|
+
this.#awaiting = void 0;
|
|
258
|
+
const phase = this.#state.phase;
|
|
259
|
+
if (phase === "catching_up" || phase === "live") this.#set({ phase: "disconnected" });
|
|
260
|
+
return [];
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* A socket is open or opening again: a subscription the cut ended subscribes from the key's
|
|
264
|
+
* last change, or, balance-only, subscribes again.
|
|
265
|
+
*/
|
|
266
|
+
connected() {
|
|
267
|
+
this.#online = true;
|
|
268
|
+
if (this.#ended || this.#state.phase !== "disconnected") return [];
|
|
269
|
+
if (!this.boxes) return this.#subscribe(void 0);
|
|
270
|
+
const w = this.#working;
|
|
271
|
+
if (!w) return this.#snapshot();
|
|
272
|
+
const from = w.last ?? w.knownAt;
|
|
273
|
+
w.knownAt = from;
|
|
274
|
+
w.last = void 0;
|
|
275
|
+
return this.#subscribe(from);
|
|
276
|
+
}
|
|
277
|
+
/** The subscription is over (the relay closed): nothing more is read, sent or retried. */
|
|
278
|
+
end() {
|
|
279
|
+
this.#ended = true;
|
|
280
|
+
this.#online = false;
|
|
281
|
+
this.#awaiting = void 0;
|
|
282
|
+
this.#working = void 0;
|
|
283
|
+
this.#generation++;
|
|
284
|
+
this.#set({ phase: "disconnected" });
|
|
285
|
+
return [];
|
|
286
|
+
}
|
|
287
|
+
/** The app is done with the key. */
|
|
288
|
+
stop() {
|
|
289
|
+
return [...this.end(), {
|
|
290
|
+
kind: "send",
|
|
291
|
+
message: {
|
|
292
|
+
op: "unsubscribe",
|
|
293
|
+
key: this.key
|
|
294
|
+
}
|
|
295
|
+
}];
|
|
296
|
+
}
|
|
297
|
+
#set(changes) {
|
|
298
|
+
this.#state = Object.freeze({
|
|
299
|
+
...this.#state,
|
|
300
|
+
...changes
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
#snapshot() {
|
|
304
|
+
this.#awaiting = void 0;
|
|
305
|
+
this.#working = void 0;
|
|
306
|
+
this.#generation++;
|
|
307
|
+
this.#set({
|
|
308
|
+
phase: "snapshot",
|
|
309
|
+
error: void 0
|
|
310
|
+
});
|
|
311
|
+
return [{
|
|
312
|
+
kind: "snapshot",
|
|
313
|
+
generation: this.#generation
|
|
314
|
+
}];
|
|
315
|
+
}
|
|
316
|
+
/** Subscribes, or waits for the socket as `disconnected` when it is not open. */
|
|
317
|
+
#subscribe(from) {
|
|
318
|
+
this.#awaiting = void 0;
|
|
319
|
+
if (!this.#online) {
|
|
320
|
+
this.#set({
|
|
321
|
+
phase: "disconnected",
|
|
322
|
+
error: void 0
|
|
323
|
+
});
|
|
324
|
+
return [];
|
|
325
|
+
}
|
|
326
|
+
const id = this.#context.nextId();
|
|
327
|
+
this.#awaiting = id;
|
|
328
|
+
this.#set({
|
|
329
|
+
phase: "catching_up",
|
|
330
|
+
error: void 0
|
|
331
|
+
});
|
|
332
|
+
return [{
|
|
333
|
+
kind: "send",
|
|
334
|
+
message: from ? {
|
|
335
|
+
op: "subscribe",
|
|
336
|
+
key: this.key,
|
|
337
|
+
from,
|
|
338
|
+
id
|
|
339
|
+
} : {
|
|
340
|
+
op: "subscribe",
|
|
341
|
+
key: this.key,
|
|
342
|
+
id
|
|
343
|
+
}
|
|
344
|
+
}];
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* A refusal or a failed snapshot read. With a `retryAfter`, or when it is for now (a network
|
|
348
|
+
* error, a 5xx), the key waits and starts again; otherwise it is rejected for good.
|
|
349
|
+
*/
|
|
350
|
+
#fail(error) {
|
|
351
|
+
this.#awaiting = void 0;
|
|
352
|
+
this.#working = void 0;
|
|
353
|
+
this.#generation++;
|
|
354
|
+
if (!transient(error)) {
|
|
355
|
+
this.#set({
|
|
356
|
+
phase: "rejected",
|
|
357
|
+
error
|
|
358
|
+
});
|
|
359
|
+
return [];
|
|
360
|
+
}
|
|
361
|
+
const ms = error.retryAfter === void 0 ? this.#context.backoff(this.#attempt++) : error.retryAfter * 1e3;
|
|
362
|
+
this.#set({
|
|
363
|
+
phase: "waiting",
|
|
364
|
+
error: {
|
|
365
|
+
...error,
|
|
366
|
+
retryAfter: ms / 1e3
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
return [{
|
|
370
|
+
kind: "retry",
|
|
371
|
+
generation: this.#generation,
|
|
372
|
+
ms
|
|
373
|
+
}];
|
|
374
|
+
}
|
|
375
|
+
/** A new snapshot for a box subscription; a balance-only one just subscribes again. */
|
|
376
|
+
#resync(reason, by = "sdk") {
|
|
377
|
+
this.#context.onResync({
|
|
378
|
+
key: this.key,
|
|
379
|
+
by,
|
|
380
|
+
reason
|
|
381
|
+
});
|
|
382
|
+
return this.boxes ? this.#snapshot() : this.#subscribe(void 0);
|
|
383
|
+
}
|
|
384
|
+
#block(m) {
|
|
385
|
+
const w = this.#working;
|
|
386
|
+
if (!w) return this.#resync("block_without_view");
|
|
387
|
+
if (!chains(w, m.prev) || m.prev.height >= m.height) return this.#resync("block_does_not_chain");
|
|
388
|
+
if (!m.spent.every((s) => w.boxes.has(s.boxId))) return this.#resync("spends_unknown_box");
|
|
389
|
+
if (!m.created.every((b) => !w.boxes.has(b.boxId) && b.inclusionHeight === m.height)) return this.#resync("creates_held_box");
|
|
390
|
+
const spent = new Set(m.spent.map((s) => s.boxId));
|
|
391
|
+
for (const id of spent) w.boxes.delete(id);
|
|
392
|
+
const confirmed = m.created.map((b) => ensureUTxOBigInt(b));
|
|
393
|
+
for (const b of confirmed) w.boxes.set(b.boxId, b);
|
|
394
|
+
w.confirmed = w.confirmed && [...w.confirmed.filter((b) => !spent.has(b.boxId)), ...confirmed.sort(keysetOrder)];
|
|
395
|
+
w.spendable = void 0;
|
|
396
|
+
w.last = {
|
|
397
|
+
height: m.height,
|
|
398
|
+
headerId: m.headerId
|
|
399
|
+
};
|
|
400
|
+
this.#publish();
|
|
401
|
+
return [];
|
|
402
|
+
}
|
|
403
|
+
#rollback(m) {
|
|
404
|
+
const w = this.#working;
|
|
405
|
+
if (!w) return this.#resync("rollback_without_view");
|
|
406
|
+
if (!chains(w, {
|
|
407
|
+
height: m.height,
|
|
408
|
+
headerId: m.headerId
|
|
409
|
+
}) || m.prev.height >= m.height) return this.#resync("rollback_of_another_block");
|
|
410
|
+
if (!m.spent.every((s) => w.boxes.has(s.boxId))) return this.#resync("undoes_unknown_box");
|
|
411
|
+
if (!m.created.every((b) => !w.boxes.has(b.boxId) && b.inclusionHeight < m.height)) return this.#resync("restores_held_box");
|
|
412
|
+
for (const s of m.spent) w.boxes.delete(s.boxId);
|
|
413
|
+
for (const b of m.created) w.boxes.set(b.boxId, ensureUTxOBigInt(b));
|
|
414
|
+
w.confirmed = void 0;
|
|
415
|
+
w.spendable = void 0;
|
|
416
|
+
w.last = m.prev;
|
|
417
|
+
this.#publish();
|
|
418
|
+
return [];
|
|
419
|
+
}
|
|
420
|
+
#mempool(m) {
|
|
421
|
+
const w = this.#working;
|
|
422
|
+
if (!w) return this.#resync("mempool_without_view");
|
|
423
|
+
if (!m.lastChange || !chains(w, m.lastChange)) return this.#resync("mempool_at_another_change");
|
|
424
|
+
w.pending = m.pending.map((tx) => ({
|
|
425
|
+
txId: tx.txId,
|
|
426
|
+
created: tx.created.map((b) => ensureUTxOBigInt(b)),
|
|
427
|
+
spent: tx.spent
|
|
428
|
+
}));
|
|
429
|
+
w.spendable = void 0;
|
|
430
|
+
this.#publish("live");
|
|
431
|
+
return [];
|
|
432
|
+
}
|
|
433
|
+
#balance(m) {
|
|
434
|
+
const balance = {
|
|
435
|
+
asOf: m.asOf,
|
|
436
|
+
confirmed: assets(m.confirmed),
|
|
437
|
+
pending: assets(m.pending)
|
|
438
|
+
};
|
|
439
|
+
if (this.boxes) {
|
|
440
|
+
const w = this.#working;
|
|
441
|
+
if (!w || !m.lastChange || !chains(w, m.lastChange)) return this.#resync("balance_at_another_change");
|
|
442
|
+
this.#set({ balance });
|
|
443
|
+
return [];
|
|
444
|
+
}
|
|
445
|
+
this.#attempt = 0;
|
|
446
|
+
this.#set({
|
|
447
|
+
balance,
|
|
448
|
+
phase: "live"
|
|
449
|
+
});
|
|
450
|
+
return [];
|
|
451
|
+
}
|
|
452
|
+
/** Publishes the working view, once the catch-up is done or as `phase` makes it. */
|
|
453
|
+
#publish(phase) {
|
|
454
|
+
const w = this.#working;
|
|
455
|
+
if (!w?.last) return;
|
|
456
|
+
const next = phase ?? this.#state.phase;
|
|
457
|
+
if (next !== "live") return;
|
|
458
|
+
this.#attempt = 0;
|
|
459
|
+
const confirmed = w.confirmed ??= [...w.boxes.values()].sort(keysetOrder);
|
|
460
|
+
w.spendable ??= spendableNow(confirmed, w.boxes, w.pending);
|
|
461
|
+
const view = {
|
|
462
|
+
lastChange: w.last,
|
|
463
|
+
confirmed,
|
|
464
|
+
pending: w.pending,
|
|
465
|
+
spendable: w.spendable
|
|
466
|
+
};
|
|
467
|
+
this.#set({
|
|
468
|
+
phase: next,
|
|
469
|
+
boxes: Object.freeze(view)
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
/**
|
|
474
|
+
* Whether a message naming `named` as the key's last change fits the view: it is the view's
|
|
475
|
+
* last change, or, before any message named one, below where the boxes are known, or that
|
|
476
|
+
* block itself. Then it is the view's last change.
|
|
477
|
+
*/
|
|
478
|
+
function chains(w, named) {
|
|
479
|
+
if (w.last) return named.height === w.last.height && named.headerId === w.last.headerId;
|
|
480
|
+
if (named.height > w.knownAt.height) return false;
|
|
481
|
+
if (named.height === w.knownAt.height && named.headerId !== w.knownAt.headerId) return false;
|
|
482
|
+
w.last = named;
|
|
483
|
+
return true;
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* The confirmed boxes and pending outputs no pending tx spends, confirmed first. A pending
|
|
487
|
+
* output already confirmed (a block mined its tx ahead of the next overlay) is listed once.
|
|
488
|
+
*/
|
|
489
|
+
function spendableNow(confirmed, held, pending) {
|
|
490
|
+
const spent = new Set(pending.flatMap((tx) => tx.spent));
|
|
491
|
+
const boxes = confirmed.filter((b) => !spent.has(b.boxId));
|
|
492
|
+
for (const tx of pending) for (const b of tx.created) if (!spent.has(b.boxId) && !held.has(b.boxId)) boxes.push(b);
|
|
493
|
+
return boxes;
|
|
494
|
+
}
|
|
495
|
+
function keysetOrder(a, b) {
|
|
496
|
+
if (a.inclusionHeight !== b.inclusionHeight) return a.inclusionHeight - b.inclusionHeight;
|
|
497
|
+
return a.boxId < b.boxId ? -1 : a.boxId > b.boxId ? 1 : 0;
|
|
498
|
+
}
|
|
499
|
+
/** Wire amounts, as `bigint`. */
|
|
500
|
+
function assets(wire) {
|
|
501
|
+
return {
|
|
502
|
+
nanoErgs: BigInt(wire.nanoErgs),
|
|
503
|
+
tokens: new Map(wire.tokens.map((t) => [t.tokenId, BigInt(t.amount)]))
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Reads one at a time: a balance during a read makes one more read of the first page after
|
|
508
|
+
* it, however many arrived. A first page that fails for now is read again after its
|
|
509
|
+
* `retryAfter` or the relay's backoff, since nothing else may ask for it soon; an older page is
|
|
510
|
+
* read again only when the app asks.
|
|
511
|
+
*/
|
|
512
|
+
var HistoryFeed = class {
|
|
513
|
+
address;
|
|
514
|
+
#context;
|
|
515
|
+
#limit;
|
|
516
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
517
|
+
#state;
|
|
518
|
+
/** The state the listeners were last called with. */
|
|
519
|
+
#notified;
|
|
520
|
+
#notifying;
|
|
521
|
+
/** The oldest page's `nextCursor`: `null` at the end, `undefined` before a first page. */
|
|
522
|
+
#cursor;
|
|
523
|
+
/** `items` hold older pages below the first. */
|
|
524
|
+
#scrolled = false;
|
|
525
|
+
/** The read in flight, and what cancels it. */
|
|
526
|
+
#read;
|
|
527
|
+
#abort;
|
|
528
|
+
/** A first page is to be read once the read in flight is done. */
|
|
529
|
+
#due = false;
|
|
530
|
+
/** The next first page replaces the list whatever it holds: an older page's cursor expired. */
|
|
531
|
+
#resetting = false;
|
|
532
|
+
#retry;
|
|
533
|
+
/** First-page failures since one last succeeded, for the backoff. */
|
|
534
|
+
#attempt = 0;
|
|
535
|
+
/** The address's balance the last read was asked for. */
|
|
536
|
+
#seen;
|
|
537
|
+
/** The first read waits for the hold's subscription to settle. */
|
|
538
|
+
#deferred = false;
|
|
539
|
+
/** Why the last first-page read failed, until one succeeds: an older page's success keeps it. */
|
|
540
|
+
#topError;
|
|
541
|
+
#unlisten;
|
|
542
|
+
#closed = false;
|
|
543
|
+
constructor(address, limit, context) {
|
|
544
|
+
this.address = address;
|
|
545
|
+
this.#limit = limit;
|
|
546
|
+
this.#context = context;
|
|
547
|
+
this.#state = Object.freeze({
|
|
548
|
+
address,
|
|
549
|
+
items: [],
|
|
550
|
+
end: false,
|
|
551
|
+
loading: false,
|
|
552
|
+
error: void 0,
|
|
553
|
+
resets: 0
|
|
554
|
+
});
|
|
555
|
+
this.#notified = this.#state;
|
|
556
|
+
const hold = context.hold;
|
|
557
|
+
if (hold) {
|
|
558
|
+
this.#deferred = settling(hold.state);
|
|
559
|
+
this.#seen = hold.state.balance;
|
|
560
|
+
this.#unlisten = hold.subscribe((state) => {
|
|
561
|
+
if (this.#deferred) {
|
|
562
|
+
if (settling(state)) return;
|
|
563
|
+
this.#deferred = false;
|
|
564
|
+
} else if (state.balance === void 0 || state.balance === this.#seen) return;
|
|
565
|
+
this.#seen = state.balance;
|
|
566
|
+
this.#refresh();
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
if (!this.#deferred) this.#start("first");
|
|
570
|
+
}
|
|
571
|
+
get state() {
|
|
572
|
+
return this.#state;
|
|
573
|
+
}
|
|
574
|
+
more() {
|
|
575
|
+
if (this.#closed) return Promise.resolve();
|
|
576
|
+
if (this.#read) return this.#read;
|
|
577
|
+
if (this.#cursor === null) return Promise.resolve();
|
|
578
|
+
if (this.#cursor === void 0) {
|
|
579
|
+
clearTimeout(this.#retry);
|
|
580
|
+
this.#retry = void 0;
|
|
581
|
+
return this.#start("first");
|
|
582
|
+
}
|
|
583
|
+
return this.#start("next");
|
|
584
|
+
}
|
|
585
|
+
subscribe(listener) {
|
|
586
|
+
return store(this.#state, this.#listeners, listener);
|
|
587
|
+
}
|
|
588
|
+
close() {
|
|
589
|
+
if (this.#closed) return;
|
|
590
|
+
this.#closed = true;
|
|
591
|
+
this.#abort?.abort();
|
|
592
|
+
this.#read = void 0;
|
|
593
|
+
clearTimeout(this.#retry);
|
|
594
|
+
clearTimeout(this.#notifying);
|
|
595
|
+
this.#unlisten?.();
|
|
596
|
+
this.#context.hold?.close();
|
|
597
|
+
this.#context.closed(this);
|
|
598
|
+
}
|
|
599
|
+
/** The address changed: reads the first page now, or after the read in flight. */
|
|
600
|
+
#refresh() {
|
|
601
|
+
if (this.#closed) return;
|
|
602
|
+
clearTimeout(this.#retry);
|
|
603
|
+
this.#retry = void 0;
|
|
604
|
+
if (this.#read) this.#due = true;
|
|
605
|
+
else this.#start("first");
|
|
606
|
+
}
|
|
607
|
+
#start(kind) {
|
|
608
|
+
const abort = new AbortController();
|
|
609
|
+
this.#abort = abort;
|
|
610
|
+
if (!this.#state.loading) this.#set({ loading: true });
|
|
611
|
+
const read = this.#run(kind, abort.signal).then(() => {
|
|
612
|
+
if (this.#read !== read) return;
|
|
613
|
+
this.#read = void 0;
|
|
614
|
+
this.#abort = void 0;
|
|
615
|
+
if (this.#due) {
|
|
616
|
+
this.#due = false;
|
|
617
|
+
clearTimeout(this.#retry);
|
|
618
|
+
this.#retry = void 0;
|
|
619
|
+
this.#start("first");
|
|
620
|
+
} else this.#set({ loading: false });
|
|
621
|
+
});
|
|
622
|
+
this.#read = read;
|
|
623
|
+
return read;
|
|
624
|
+
}
|
|
625
|
+
async #run(kind, signal) {
|
|
626
|
+
const rest = this.#context.rest;
|
|
627
|
+
const limit = this.#limit === void 0 ? {} : { limit: this.#limit };
|
|
628
|
+
try {
|
|
629
|
+
if (kind === "first") {
|
|
630
|
+
const page = await rest.history(this.address, {
|
|
631
|
+
...limit,
|
|
632
|
+
signal
|
|
633
|
+
});
|
|
634
|
+
if (signal.aborted) return;
|
|
635
|
+
this.#first(page);
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
for (let empty = 1;; empty++) {
|
|
639
|
+
const cursor = this.#cursor ?? void 0;
|
|
640
|
+
const at = cursor === void 0 ? {} : { cursor };
|
|
641
|
+
const page = await rest.history(this.address, {
|
|
642
|
+
...at,
|
|
643
|
+
...limit,
|
|
644
|
+
signal
|
|
645
|
+
});
|
|
646
|
+
if (signal.aborted) return;
|
|
647
|
+
if (page.items.length > 0 || page.nextCursor === null || empty === 3) {
|
|
648
|
+
this.#next(page, page.items.length === 0 && page.nextCursor !== null);
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
this.#cursor = page.nextCursor;
|
|
652
|
+
}
|
|
653
|
+
} catch (e) {
|
|
654
|
+
if (signal.aborted) return;
|
|
655
|
+
const error = failure(e);
|
|
656
|
+
if (kind === "next" && error.code === "cursor_expired") {
|
|
657
|
+
this.#resetting = true;
|
|
658
|
+
await this.#run("first", signal);
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
if (kind === "next") {
|
|
662
|
+
this.#set({ error });
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
if (!transient(error)) {
|
|
666
|
+
this.#topError = error;
|
|
667
|
+
this.#set({ error });
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
const ms = error.retryAfter === void 0 ? this.#context.backoff(this.#attempt++) : error.retryAfter * 1e3;
|
|
671
|
+
this.#topError = {
|
|
672
|
+
...error,
|
|
673
|
+
retryAfter: ms / 1e3
|
|
674
|
+
};
|
|
675
|
+
this.#set({ error: this.#topError });
|
|
676
|
+
this.#retry = setTimeout(() => {
|
|
677
|
+
this.#retry = void 0;
|
|
678
|
+
this.#refresh();
|
|
679
|
+
}, ms);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* A first page: on top of the older pages if it joins them, in place of the list if not.
|
|
684
|
+
* It joins at its oldest tx, found below with the same height: the txs below it follow it on
|
|
685
|
+
* the address's list unless a reorg rewrote them, and a reorg that did would have dropped
|
|
686
|
+
* it too, or put back some of the page's txs below it.
|
|
687
|
+
*/
|
|
688
|
+
#first(page) {
|
|
689
|
+
if (this.#closed) return;
|
|
690
|
+
this.#attempt = 0;
|
|
691
|
+
this.#topError = void 0;
|
|
692
|
+
clearTimeout(this.#retry);
|
|
693
|
+
this.#retry = void 0;
|
|
694
|
+
const fresh = page.items.map(item);
|
|
695
|
+
const resetting = this.#resetting;
|
|
696
|
+
this.#resetting = false;
|
|
697
|
+
let joined;
|
|
698
|
+
if (!resetting && this.#scrolled && page.nextCursor !== null) {
|
|
699
|
+
const oldest = fresh.at(-1);
|
|
700
|
+
const at = this.#state.items.findIndex((i) => oldest?.height !== void 0 && i.txId === oldest.txId && i.height === oldest.height);
|
|
701
|
+
const tail = at < 0 ? [] : this.#state.items.slice(at + 1);
|
|
702
|
+
const ids = new Set(fresh.map((i) => i.txId));
|
|
703
|
+
if (at >= 0 && !tail.some((i) => ids.has(i.txId))) joined = [...fresh, ...tail];
|
|
704
|
+
}
|
|
705
|
+
if (joined) {
|
|
706
|
+
this.#set({
|
|
707
|
+
items: joined,
|
|
708
|
+
error: void 0
|
|
709
|
+
});
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
const reset = this.#scrolled && (resetting || page.nextCursor !== null);
|
|
713
|
+
this.#cursor = page.nextCursor;
|
|
714
|
+
this.#scrolled = false;
|
|
715
|
+
this.#set({
|
|
716
|
+
items: fresh,
|
|
717
|
+
end: page.nextCursor === null,
|
|
718
|
+
error: void 0,
|
|
719
|
+
resets: this.#state.resets + (reset ? 1 : 0)
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
/** An older page, appended; `empty` when it ends a run of empty pages, an error. */
|
|
723
|
+
#next(page, empty) {
|
|
724
|
+
if (this.#closed) return;
|
|
725
|
+
this.#cursor = page.nextCursor;
|
|
726
|
+
if (empty) {
|
|
727
|
+
const message = `${String(3)} empty pages in a row`;
|
|
728
|
+
this.#set({ error: {
|
|
729
|
+
code: "empty_pages",
|
|
730
|
+
message
|
|
731
|
+
} });
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
this.#scrolled = true;
|
|
735
|
+
this.#set({
|
|
736
|
+
items: [...this.#state.items, ...page.items.map(item)],
|
|
737
|
+
end: page.nextCursor === null,
|
|
738
|
+
error: this.#topError
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
#set(changes) {
|
|
742
|
+
if (this.#closed) return;
|
|
743
|
+
this.#state = Object.freeze({
|
|
744
|
+
...this.#state,
|
|
745
|
+
...changes
|
|
746
|
+
});
|
|
747
|
+
this.#notifying ??= setTimeout(() => {
|
|
748
|
+
this.#notify();
|
|
749
|
+
}, 0);
|
|
750
|
+
}
|
|
751
|
+
#notify() {
|
|
752
|
+
this.#notifying = void 0;
|
|
753
|
+
const state = this.#state;
|
|
754
|
+
if (state === this.#notified) return;
|
|
755
|
+
this.#notified = state;
|
|
756
|
+
for (const listener of this.#listeners) call(listener, state);
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
/** A subscription still loading, which settles with a balance or a failure. */
|
|
760
|
+
function settling(state) {
|
|
761
|
+
return state.phase === "snapshot" || state.phase === "catching_up";
|
|
762
|
+
}
|
|
763
|
+
function item(wire) {
|
|
764
|
+
const { txId, height, timestamp } = wire;
|
|
765
|
+
return Object.freeze({
|
|
766
|
+
txId,
|
|
767
|
+
...height === void 0 ? {} : { height },
|
|
768
|
+
...timestamp === void 0 ? {} : { timestamp },
|
|
769
|
+
delta: assets(wire.delta)
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
// src/protocol.ts
|
|
773
|
+
/** A key's name for routing: its kind and the spelling sent, which the relay echoes. */
|
|
774
|
+
function keyName(key) {
|
|
775
|
+
if ("address" in key) return `a:${key.address}`;
|
|
776
|
+
return "tokenId" in key ? `t:${key.tokenId}` : `p:${key.template}`;
|
|
777
|
+
}
|
|
778
|
+
// src/rest.ts
|
|
779
|
+
/** The most token ids the relay takes in one request. */
|
|
780
|
+
const MAX_TOKEN_IDS = 100;
|
|
781
|
+
/** Attempts in all for a `503` unless set: the first, and two retries. */
|
|
782
|
+
const MAX_ATTEMPTS = 3;
|
|
783
|
+
/** The wait before retrying a `503` with no `Retry-After`, about one relay tick. */
|
|
784
|
+
const DEFAULT_RETRY_SECONDS = 1;
|
|
785
|
+
/**
|
|
786
|
+
* The relay's REST API. Each method answers the route's JSON as it came, and throws a
|
|
787
|
+
* {@link RelayError} for any other status. A `503` is retried after its `Retry-After`, however
|
|
788
|
+
* long, up to `maxAttempts` in all; the last error is thrown. `capacity_exceeded` is not: it
|
|
789
|
+
* frees up only as keys go idle, a minute at the soonest, too long to hold a call.
|
|
790
|
+
*/
|
|
791
|
+
var RestClient = class {
|
|
792
|
+
#base;
|
|
793
|
+
#fetch;
|
|
794
|
+
#maxAttempts;
|
|
795
|
+
/** `url` is the relay's root, under which `/v1` is served; it may have a path. */
|
|
796
|
+
constructor(url, options = {}) {
|
|
797
|
+
const base = new URL(url);
|
|
798
|
+
if (!base.pathname.endsWith("/")) base.pathname += "/";
|
|
799
|
+
this.#base = base;
|
|
800
|
+
this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
801
|
+
this.#maxAttempts = Math.max(1, options.maxAttempts ?? MAX_ATTEMPTS);
|
|
802
|
+
}
|
|
803
|
+
/** The root the routes are resolved against, its path ending in `/`. */
|
|
804
|
+
get root() {
|
|
805
|
+
return new URL(this.#base);
|
|
806
|
+
}
|
|
807
|
+
/** The relay's version, network, tip, and whether it is ready. */
|
|
808
|
+
status(options = {}) {
|
|
809
|
+
return this.#get("v1/status", {}, options);
|
|
810
|
+
}
|
|
811
|
+
/** A page of a key's unspent boxes, in `(inclusionHeight, boxId)` order. */
|
|
812
|
+
boxes(key, options = {}) {
|
|
813
|
+
const query = {
|
|
814
|
+
cursor: options.cursor,
|
|
815
|
+
limit: options.limit
|
|
816
|
+
};
|
|
817
|
+
return this.#get(`${keyPath(key)}/boxes`, query, options);
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* What a tx can spend now from an address, in one response: its confirmed boxes and the
|
|
821
|
+
* pool's outputs to it, less what pool txs spend. `boxes.spendable` on a subscription keeps
|
|
822
|
+
* it live.
|
|
823
|
+
*/
|
|
824
|
+
spendable(address, options = {}) {
|
|
825
|
+
return this.#get(`${keyPath({ address })}/boxes/spendable`, {}, options);
|
|
826
|
+
}
|
|
827
|
+
/** An address's balance, confirmed and pending. */
|
|
828
|
+
balance(address, options = {}) {
|
|
829
|
+
return this.#get(`${keyPath({ address })}/balance`, {}, options);
|
|
830
|
+
}
|
|
831
|
+
/** A page of an address's txs, newest first, pending on top. */
|
|
832
|
+
history(address, options = {}) {
|
|
833
|
+
const query = {
|
|
834
|
+
cursor: options.cursor,
|
|
835
|
+
limit: options.limit
|
|
836
|
+
};
|
|
837
|
+
return this.#get(`${keyPath({ address })}/transactions`, query, options);
|
|
838
|
+
}
|
|
839
|
+
/** The last headers up to the relay's tip, newest first. */
|
|
840
|
+
headers(options = {}) {
|
|
841
|
+
return this.#get("v1/headers", { limit: options.limit }, options);
|
|
842
|
+
}
|
|
843
|
+
/** A box a tx can spend now: confirmed, or a mempool output. */
|
|
844
|
+
box(boxId, options = {}) {
|
|
845
|
+
return this.#get(`v1/boxes/${encodeURIComponent(boxId)}`, {}, options);
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* The metadata of the tokens among `ids` the relay's node knows, in their order and each
|
|
849
|
+
* once in any case; unknown ids are left out. Over 100 ids are asked 100 per request, one
|
|
850
|
+
* request after another, and answered as one list. No ids make no request.
|
|
851
|
+
*/
|
|
852
|
+
async tokens(ids, options = {}) {
|
|
853
|
+
const unique = [...new Set(ids.map((id) => id.toLowerCase()))];
|
|
854
|
+
const items = [];
|
|
855
|
+
for (let i = 0; i < unique.length; i += MAX_TOKEN_IDS) {
|
|
856
|
+
const chunk = unique.slice(i, i + MAX_TOKEN_IDS).join(",");
|
|
857
|
+
const list = await this.#get("v1/tokens/metadata", { ids: chunk }, options);
|
|
858
|
+
items.push(...list.items);
|
|
859
|
+
}
|
|
860
|
+
return { items };
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Sends a signed tx, serialized in hex or as Fleet's JSON, or with `broadcast: false` only
|
|
864
|
+
* checks it. The JSON is serialized here, since the relay takes the bytes only.
|
|
865
|
+
*/
|
|
866
|
+
submitTransaction(tx, options = {}) {
|
|
867
|
+
const body = typeof tx === "string" ? tx : toHex(serializeTransaction(tx).toBytes());
|
|
868
|
+
const query = { broadcast: options.broadcast === false ? "false" : void 0 };
|
|
869
|
+
const init = {
|
|
870
|
+
method: "POST",
|
|
871
|
+
body,
|
|
872
|
+
headers: { "content-type": "text/plain" }
|
|
873
|
+
};
|
|
874
|
+
return this.#request("v1/transactions", query, init, options);
|
|
875
|
+
}
|
|
876
|
+
#get(path, query, options) {
|
|
877
|
+
return this.#request(path, query, { method: "GET" }, options);
|
|
878
|
+
}
|
|
879
|
+
async #request(path, query, init, { signal }) {
|
|
880
|
+
const url = new URL(path, this.#base);
|
|
881
|
+
for (const [name, value] of Object.entries(query)) if (value !== void 0) url.searchParams.set(name, String(value));
|
|
882
|
+
for (let attempt = 1;; attempt++) {
|
|
883
|
+
const response = await this.#fetch(url, signal ? {
|
|
884
|
+
...init,
|
|
885
|
+
signal
|
|
886
|
+
} : init);
|
|
887
|
+
if (response.ok) return await response.json();
|
|
888
|
+
const error = await RelayError.from(response);
|
|
889
|
+
if (!(response.status === 503 && error.code !== "capacity_exceeded") || attempt >= this.#maxAttempts) throw error;
|
|
890
|
+
await sleep((error.retryAfter ?? DEFAULT_RETRY_SECONDS) * 1e3, signal);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
function keyPath(key) {
|
|
895
|
+
if ("address" in key) return `v1/addresses/${encodeURIComponent(key.address)}`;
|
|
896
|
+
return "tokenId" in key ? `v1/tokens/${encodeURIComponent(key.tokenId)}` : `v1/templates/${encodeURIComponent(key.template)}`;
|
|
897
|
+
}
|
|
898
|
+
function sleep(ms, signal) {
|
|
899
|
+
return new Promise((resolve, reject) => {
|
|
900
|
+
signal?.throwIfAborted();
|
|
901
|
+
const onAbort = () => {
|
|
902
|
+
clearTimeout(timer);
|
|
903
|
+
reject(signal?.reason);
|
|
904
|
+
};
|
|
905
|
+
const timer = setTimeout(() => {
|
|
906
|
+
signal?.removeEventListener("abort", onAbort);
|
|
907
|
+
resolve();
|
|
908
|
+
}, ms);
|
|
909
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
function toHex(bytes) {
|
|
913
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
914
|
+
}
|
|
915
|
+
// src/relay.ts
|
|
916
|
+
const PAGE_SIZE = 1e3;
|
|
917
|
+
/**
|
|
918
|
+
* A relay: its REST API, its tip, and subscriptions to keys over one WebSocket, opened on the
|
|
919
|
+
* first subscribe. A key is subscribed once however many holds it has. When the socket closes,
|
|
920
|
+
* for whatever reason, it opens again after a backoff while any key is held, and each key
|
|
921
|
+
* resumes from the block it had reached.
|
|
922
|
+
*/
|
|
923
|
+
var Relay = class {
|
|
924
|
+
rest;
|
|
925
|
+
#wsUrl;
|
|
926
|
+
#WebSocket;
|
|
927
|
+
#pageSize;
|
|
928
|
+
#debug;
|
|
929
|
+
#entries = /* @__PURE__ */ new Map();
|
|
930
|
+
#histories = /* @__PURE__ */ new Set();
|
|
931
|
+
#tipListeners = /* @__PURE__ */ new Set();
|
|
932
|
+
#backoff;
|
|
933
|
+
#context;
|
|
934
|
+
#socket;
|
|
935
|
+
#queue = [];
|
|
936
|
+
/** The wait before the socket opens again; no socket is opened meanwhile. */
|
|
937
|
+
#reconnect;
|
|
938
|
+
/** Reconnects since a key last went live. */
|
|
939
|
+
#attempt = 0;
|
|
940
|
+
#tip;
|
|
941
|
+
#ids = 0;
|
|
942
|
+
/** Keys whose state changed since their listeners were last called. */
|
|
943
|
+
#changed = /* @__PURE__ */ new Set();
|
|
944
|
+
#notifying;
|
|
945
|
+
/** `url` is the relay's root, under which `/v1` is served; it may have a path. */
|
|
946
|
+
constructor(url, options = {}) {
|
|
947
|
+
this.rest = new RestClient(url, options);
|
|
948
|
+
const ws = new URL("v1/ws", this.rest.root);
|
|
949
|
+
ws.protocol = ws.protocol === "https:" ? "wss:" : "ws:";
|
|
950
|
+
this.#wsUrl = ws.href;
|
|
951
|
+
this.#WebSocket = options.WebSocket ?? globalThis.WebSocket;
|
|
952
|
+
this.#pageSize = Math.min(PAGE_SIZE, Math.max(1, options.pageSize ?? PAGE_SIZE));
|
|
953
|
+
this.#debug = options.debug;
|
|
954
|
+
this.#backoff = backoff(options.backoff?.firstMs ?? 1e3, options.backoff?.maxMs ?? 3e4);
|
|
955
|
+
this.#context = {
|
|
956
|
+
nextId: () => this.#ids++ % 2 ** 32,
|
|
957
|
+
onResync: (resync) => {
|
|
958
|
+
call(this.#debug, { resync });
|
|
959
|
+
},
|
|
960
|
+
backoff: this.#backoff
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
/** The relay's tip, the block every box and balance it serves is at, once known. */
|
|
964
|
+
get tip() {
|
|
965
|
+
return this.#tip;
|
|
966
|
+
}
|
|
967
|
+
/** Calls `listener` on every new tip; answers a function that removes it. */
|
|
968
|
+
onTip(listener) {
|
|
969
|
+
this.#tipListeners.add(listener);
|
|
970
|
+
return () => this.#tipListeners.delete(listener);
|
|
971
|
+
}
|
|
972
|
+
subscribe(key, options = {}) {
|
|
973
|
+
const boxes = !("address" in key) || options.boxes !== false;
|
|
974
|
+
const name = keyName(key);
|
|
975
|
+
let entry = this.#entries.get(name);
|
|
976
|
+
if (!entry) {
|
|
977
|
+
const machine = this.#machine(key, boxes);
|
|
978
|
+
entry = {
|
|
979
|
+
machine,
|
|
980
|
+
holds: 0,
|
|
981
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
982
|
+
notified: machine.state,
|
|
983
|
+
retry: void 0,
|
|
984
|
+
reading: void 0
|
|
985
|
+
};
|
|
986
|
+
this.#entries.set(name, entry);
|
|
987
|
+
const created = entry;
|
|
988
|
+
this.#change(created, () => created.machine.start());
|
|
989
|
+
} else if (entry.machine.state.phase === "rejected" || boxes && !entry.machine.boxes) {
|
|
990
|
+
const replaced = entry;
|
|
991
|
+
const following = boxes || replaced.machine.boxes;
|
|
992
|
+
forget(replaced);
|
|
993
|
+
this.#change(replaced, () => {
|
|
994
|
+
replaced.machine = this.#machine(key, following, replaced.machine.state);
|
|
995
|
+
return replaced.machine.start();
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
entry.holds++;
|
|
999
|
+
const held = entry;
|
|
1000
|
+
let open = true;
|
|
1001
|
+
return {
|
|
1002
|
+
key,
|
|
1003
|
+
get state() {
|
|
1004
|
+
return held.machine.state;
|
|
1005
|
+
},
|
|
1006
|
+
subscribe(listener) {
|
|
1007
|
+
return store(held.machine.state, held.listeners, listener);
|
|
1008
|
+
},
|
|
1009
|
+
close: () => {
|
|
1010
|
+
if (!open) return;
|
|
1011
|
+
open = false;
|
|
1012
|
+
if (this.#entries.get(name) !== held) return;
|
|
1013
|
+
if (--held.holds > 0) return;
|
|
1014
|
+
this.#entries.delete(name);
|
|
1015
|
+
forget(held);
|
|
1016
|
+
this.#change(held, () => held.machine.stop());
|
|
1017
|
+
if (this.#entries.size === 0) this.#stopReconnecting();
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* An address's tx history, newest first, pending txs on top: its first page is read now,
|
|
1023
|
+
* and older pages as the app asks. See {@link HistoryOptions.refresh} to keep the first
|
|
1024
|
+
* page current.
|
|
1025
|
+
*/
|
|
1026
|
+
history(address, options = {}) {
|
|
1027
|
+
const history = new HistoryFeed(address, options.limit, {
|
|
1028
|
+
rest: this.rest,
|
|
1029
|
+
backoff: this.#backoff,
|
|
1030
|
+
hold: options.refresh ? this.subscribe({ address }, { boxes: false }) : void 0,
|
|
1031
|
+
closed: (h) => this.#histories.delete(h)
|
|
1032
|
+
});
|
|
1033
|
+
this.#histories.add(history);
|
|
1034
|
+
return history;
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Closes the socket, ends every subscription and stops every history. A later subscribe
|
|
1038
|
+
* opens a new socket.
|
|
1039
|
+
*/
|
|
1040
|
+
close() {
|
|
1041
|
+
const socket = this.#socket;
|
|
1042
|
+
this.#socket = void 0;
|
|
1043
|
+
this.#queue = [];
|
|
1044
|
+
this.#tip = void 0;
|
|
1045
|
+
this.#stopReconnecting();
|
|
1046
|
+
socket?.close(1e3);
|
|
1047
|
+
for (const history of this.#histories) history.close();
|
|
1048
|
+
for (const entry of this.#entries.values()) {
|
|
1049
|
+
forget(entry);
|
|
1050
|
+
this.#change(entry, () => entry.machine.end());
|
|
1051
|
+
}
|
|
1052
|
+
this.#entries.clear();
|
|
1053
|
+
}
|
|
1054
|
+
#machine(key, boxes, previous) {
|
|
1055
|
+
return new KeyMachine(key, boxes, this.#context, this.#online(), previous);
|
|
1056
|
+
}
|
|
1057
|
+
/** Whether a subscribe can go out now: the socket is open or opening, or may be opened. */
|
|
1058
|
+
#online() {
|
|
1059
|
+
return this.#socket !== void 0 || this.#reconnect === void 0;
|
|
1060
|
+
}
|
|
1061
|
+
#stopReconnecting() {
|
|
1062
|
+
clearTimeout(this.#reconnect);
|
|
1063
|
+
this.#reconnect = void 0;
|
|
1064
|
+
this.#attempt = 0;
|
|
1065
|
+
}
|
|
1066
|
+
/** Does what a machine asked, then has the key's listeners called if its state changed. */
|
|
1067
|
+
#run(entry, actions, before) {
|
|
1068
|
+
for (const action of actions) if (action.kind === "send") this.#send(action.message);
|
|
1069
|
+
else if (action.kind === "snapshot") this.#snapshot(entry, entry.machine, action.generation);
|
|
1070
|
+
else this.#retry(entry, entry.machine, action.generation, action.ms);
|
|
1071
|
+
if (entry.machine.state === before) return;
|
|
1072
|
+
if (entry.machine.state.phase === "live" && before.phase !== "live") this.#attempt = 0;
|
|
1073
|
+
this.#changed.add(entry);
|
|
1074
|
+
if (this.#notifying === void 0) this.#notifying = setTimeout(() => {
|
|
1075
|
+
this.#notify();
|
|
1076
|
+
}, 0);
|
|
1077
|
+
}
|
|
1078
|
+
/** Calls the listeners of every key that changed, once each, with its latest state. */
|
|
1079
|
+
#notify() {
|
|
1080
|
+
this.#notifying = void 0;
|
|
1081
|
+
const changed = [...this.#changed];
|
|
1082
|
+
this.#changed.clear();
|
|
1083
|
+
for (const entry of changed) {
|
|
1084
|
+
const state = entry.machine.state;
|
|
1085
|
+
if (state === entry.notified) continue;
|
|
1086
|
+
entry.notified = state;
|
|
1087
|
+
for (const listener of entry.listeners) call(listener, state);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
#change(entry, step) {
|
|
1091
|
+
const before = entry.machine.state;
|
|
1092
|
+
this.#run(entry, step(), before);
|
|
1093
|
+
}
|
|
1094
|
+
#retry(entry, machine, generation, ms) {
|
|
1095
|
+
clearTimeout(entry.retry);
|
|
1096
|
+
entry.retry = setTimeout(() => {
|
|
1097
|
+
entry.retry = void 0;
|
|
1098
|
+
if (entry.machine !== machine) return;
|
|
1099
|
+
this.#change(entry, () => machine.retry(generation));
|
|
1100
|
+
}, ms);
|
|
1101
|
+
}
|
|
1102
|
+
async #snapshot(entry, machine, generation) {
|
|
1103
|
+
entry.reading?.abort();
|
|
1104
|
+
const reading = new AbortController();
|
|
1105
|
+
entry.reading = reading;
|
|
1106
|
+
let read;
|
|
1107
|
+
try {
|
|
1108
|
+
read = await this.#read(machine.key, reading.signal);
|
|
1109
|
+
} catch (e) {
|
|
1110
|
+
if (entry.machine !== machine || reading.signal.aborted) return;
|
|
1111
|
+
this.#change(entry, () => machine.snapshotFailed(generation, failure(e)));
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
1114
|
+
if (entry.machine !== machine) return;
|
|
1115
|
+
this.#change(entry, () => machine.snapshotLoaded(generation, read.asOf, read.boxes));
|
|
1116
|
+
}
|
|
1117
|
+
/** Every page of a key's boxes, pinned to the first page's block. */
|
|
1118
|
+
async #read(key, signal) {
|
|
1119
|
+
const first = await this.rest.boxes(key, {
|
|
1120
|
+
limit: this.#pageSize,
|
|
1121
|
+
signal
|
|
1122
|
+
});
|
|
1123
|
+
const boxes = [...first.items];
|
|
1124
|
+
let cursor = first.nextCursor;
|
|
1125
|
+
while (cursor !== null) {
|
|
1126
|
+
const page = await this.rest.boxes(key, {
|
|
1127
|
+
limit: this.#pageSize,
|
|
1128
|
+
cursor,
|
|
1129
|
+
signal
|
|
1130
|
+
});
|
|
1131
|
+
boxes.push(...page.items);
|
|
1132
|
+
cursor = page.nextCursor;
|
|
1133
|
+
}
|
|
1134
|
+
return {
|
|
1135
|
+
asOf: first.asOf,
|
|
1136
|
+
boxes
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
#send(message) {
|
|
1140
|
+
if (message.op === "unsubscribe" && !this.#socket) return;
|
|
1141
|
+
if (!this.#online()) return;
|
|
1142
|
+
const text = JSON.stringify(message);
|
|
1143
|
+
const socket = this.#connect();
|
|
1144
|
+
if (socket.readyState === this.#WebSocket.OPEN) socket.send(text);
|
|
1145
|
+
else this.#queue.push(text);
|
|
1146
|
+
}
|
|
1147
|
+
#connect() {
|
|
1148
|
+
if (this.#socket) return this.#socket;
|
|
1149
|
+
const socket = new this.#WebSocket(this.#wsUrl);
|
|
1150
|
+
this.#socket = socket;
|
|
1151
|
+
socket.addEventListener("open", () => {
|
|
1152
|
+
for (const text of this.#queue) socket.send(text);
|
|
1153
|
+
this.#queue = [];
|
|
1154
|
+
});
|
|
1155
|
+
socket.addEventListener("message", (event) => {
|
|
1156
|
+
if (this.#socket !== socket) return;
|
|
1157
|
+
if (typeof event.data === "string") this.#receive(event.data);
|
|
1158
|
+
});
|
|
1159
|
+
socket.addEventListener("close", () => {
|
|
1160
|
+
if (this.#socket !== socket) return;
|
|
1161
|
+
this.#socket = void 0;
|
|
1162
|
+
this.#queue = [];
|
|
1163
|
+
if (this.#entries.size > 0) this.#reconnect = setTimeout(() => {
|
|
1164
|
+
this.#reconnected();
|
|
1165
|
+
}, this.#backoff(this.#attempt++));
|
|
1166
|
+
for (const entry of this.#entries.values()) this.#change(entry, () => entry.machine.disconnected());
|
|
1167
|
+
});
|
|
1168
|
+
return socket;
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* The backoff ended: opens a socket, and once it is open every key the cut ended subscribes
|
|
1172
|
+
* again on it. Until then they stay `disconnected`, as they do if it fails to open.
|
|
1173
|
+
*/
|
|
1174
|
+
#reconnected() {
|
|
1175
|
+
this.#reconnect = void 0;
|
|
1176
|
+
if (this.#entries.size === 0) return;
|
|
1177
|
+
const socket = this.#connect();
|
|
1178
|
+
socket.addEventListener("open", () => {
|
|
1179
|
+
if (this.#socket !== socket) return;
|
|
1180
|
+
for (const entry of this.#entries.values()) this.#change(entry, () => entry.machine.connected());
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
#receive(text) {
|
|
1184
|
+
call(this.#debug, { frame: text });
|
|
1185
|
+
let message;
|
|
1186
|
+
try {
|
|
1187
|
+
message = JSON.parse(text);
|
|
1188
|
+
} catch {
|
|
1189
|
+
return;
|
|
1190
|
+
}
|
|
1191
|
+
if (typeof message !== "object" || message === null) return;
|
|
1192
|
+
if (message.type === "tip") {
|
|
1193
|
+
const tip = {
|
|
1194
|
+
height: message.height,
|
|
1195
|
+
headerId: message.headerId
|
|
1196
|
+
};
|
|
1197
|
+
this.#tip = tip;
|
|
1198
|
+
for (const listener of this.#tipListeners) call(listener, tip);
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
if (typeof message.key !== "object") return;
|
|
1202
|
+
const entry = this.#entries.get(keyName(message.key));
|
|
1203
|
+
if (entry) this.#change(entry, () => entry.machine.receive(message));
|
|
1204
|
+
}
|
|
1205
|
+
};
|
|
1206
|
+
/** The wait before the `attempt`-th retry, from 0: see {@link RelayOptions.backoff}. */
|
|
1207
|
+
function backoff(firstMs, maxMs) {
|
|
1208
|
+
return (attempt) => Math.random() * Math.min(maxMs, firstMs * 2 ** attempt);
|
|
1209
|
+
}
|
|
1210
|
+
/** Cancels what a key's machine still has under way: its retry's wait and its snapshot read. */
|
|
1211
|
+
function forget(entry) {
|
|
1212
|
+
clearTimeout(entry.retry);
|
|
1213
|
+
entry.reading?.abort();
|
|
1214
|
+
}
|
|
1215
|
+
export { Relay, RelayError, RestClient };
|