@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/README.md
CHANGED
|
@@ -1,3 +1,282 @@
|
|
|
1
|
-
#
|
|
1
|
+
# hergmes SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The TypeScript client for the hergmes relay: an address's or a small-supply token's boxes and an
|
|
4
|
+
address's balance, kept current over one WebSocket with the mempool applied, its tx history, and
|
|
5
|
+
the relay's REST routes.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Not published yet; the package is `@hergmes/sdk`. It runs on Node 22 or later and in browsers
|
|
10
|
+
(the built-in `fetch` and `WebSocket`, nothing else).
|
|
11
|
+
|
|
12
|
+
## Usage
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { Relay } from "@hergmes/sdk";
|
|
16
|
+
|
|
17
|
+
// The relay's root, under which `/v1` is served; it may have a path.
|
|
18
|
+
const relay = new Relay("https://relay.example.com");
|
|
19
|
+
|
|
20
|
+
const wallet = relay.subscribe({ address: "9f…" });
|
|
21
|
+
wallet.subscribe(({ phase, boxes, balance }) => {
|
|
22
|
+
if (phase !== "live") return; // `boxes` and `balance` are their last live values, stale
|
|
23
|
+
console.log(boxes?.spendable.length, balance?.confirmed.nanoErgs, balance?.pending.nanoErgs);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// Later: ends this hold, and the key's subscription with the last one.
|
|
27
|
+
wallet.close();
|
|
28
|
+
// Or everything: the socket, every subscription and history.
|
|
29
|
+
relay.close();
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Subscriptions
|
|
33
|
+
|
|
34
|
+
`relay.subscribe(key, { boxes })` answers a `Subscription`: a hold on the key. The key is
|
|
35
|
+
`{ address }`, `{ tokenId }` or `{ template }`: a template in hex, a constant-segregated
|
|
36
|
+
ErgoTree's bytes after its constants, for the boxes of every instance of a contract whatever its
|
|
37
|
+
constants.
|
|
38
|
+
|
|
39
|
+
- With boxes (the default) the SDK reads the key's confirmed boxes, subscribes from that block
|
|
40
|
+
and applies every block, rollback and mempool change that touches the key. Its `state.boxes` has
|
|
41
|
+
the confirmed boxes, the pending txs as they affect the key, and `spendable`, what a tx can
|
|
42
|
+
spend now: confirmed boxes and pending outputs no pending tx spends. For an address, its total
|
|
43
|
+
is the balance's `confirmed + pending`; for any key, `utxoSum(boxes.spendable)` from
|
|
44
|
+
`@fleet-sdk/common` totals it. `boxes.lastChange` is the block of
|
|
45
|
+
the key's last change: the relay sends a key only the blocks that change it, so the height to
|
|
46
|
+
show is the relay's, `relay.tip`.
|
|
47
|
+
- With `{ boxes: false }`, an address's balance alone: no snapshot, the lightest subscription.
|
|
48
|
+
Token and template keys have no balance and always follow boxes.
|
|
49
|
+
|
|
50
|
+
`state.balance` is the address's balance: `confirmed`, and `pending`, the signed change the
|
|
51
|
+
mempool makes to it. Amounts are `bigint`s, tokens a `Map` from token id to amount.
|
|
52
|
+
|
|
53
|
+
`state.phase` says where the subscription is, and whether `boxes` and `balance` are current:
|
|
54
|
+
|
|
55
|
+
| Phase | Meaning |
|
|
56
|
+
| -------------- | ---------------------------------------------------------------------------- |
|
|
57
|
+
| `snapshot` | reading the key's boxes |
|
|
58
|
+
| `catching_up` | subscribed, replaying to the relay's tip |
|
|
59
|
+
| `live` | following the chain: `boxes` and `balance` are current |
|
|
60
|
+
| `waiting` | refused or failed for now; `error.retryAfter` says when it starts again |
|
|
61
|
+
| `rejected` | refused or failed for good, `error` says why; a later subscribe tries again |
|
|
62
|
+
| `disconnected` | the socket closed; it resumes from the key's last change once it opens again |
|
|
63
|
+
|
|
64
|
+
Outside `live`, `boxes` and `balance` keep their last live values, to show as stale. Recovery is
|
|
65
|
+
the SDK's: after a closed socket it reconnects with a jittered backoff and each key resumes from
|
|
66
|
+
its last change, and when the relay asks for a resync, or a message doesn't fit its boxes, the key reads
|
|
67
|
+
a new snapshot.
|
|
68
|
+
|
|
69
|
+
`state` is replaced whole on every change. `subscribe(listener)` calls the listener at once with
|
|
70
|
+
the current state, then once for the messages that arrived together, with the latest state. It
|
|
71
|
+
answers a function that removes the listener.
|
|
72
|
+
|
|
73
|
+
Several holds on one key share its subscription, so components can each open their own. A box
|
|
74
|
+
hold replaces a balance-only subscription; the key is unsubscribed when its last hold closes.
|
|
75
|
+
|
|
76
|
+
`relay.tip` is the relay's tip, the block every box and balance it serves is at, and
|
|
77
|
+
`relay.onTip(listener)` sees each new one.
|
|
78
|
+
|
|
79
|
+
### History
|
|
80
|
+
|
|
81
|
+
`relay.history(address, { refresh, limit })` answers a `TxHistory`: the address's txs, newest
|
|
82
|
+
first, pending ones on top, each with its signed net change to the address. The first page is
|
|
83
|
+
read at once; `more()` reads the next older one.
|
|
84
|
+
|
|
85
|
+
With `refresh: true` the first page is read again whenever the address's balance changes. This
|
|
86
|
+
holds the address as a balance-only subscription does, sharing the key's subscription if the
|
|
87
|
+
app has one, so close the history when done. Older pages are not checked again: when the list
|
|
88
|
+
no longer joins them, it is read again from the top and `state.resets` goes up.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
const history = relay.history(address, { refresh: true });
|
|
92
|
+
history.subscribe(({ items, end, loading, error }) => render(items));
|
|
93
|
+
await history.more();
|
|
94
|
+
history.close();
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### REST
|
|
98
|
+
|
|
99
|
+
`relay.rest` is a `RestClient`, also usable alone as `new RestClient(url)`. Each method answers
|
|
100
|
+
the route's JSON as it came, amounts as base-10 strings:
|
|
101
|
+
|
|
102
|
+
| Method | Route |
|
|
103
|
+
| -------------------------------------- | --------------------------------------------- |
|
|
104
|
+
| `status()` | `GET /v1/status` |
|
|
105
|
+
| `boxes(key, { cursor, limit })` | `GET /v1/{addresses,tokens}/{key}/boxes` |
|
|
106
|
+
| `spendable(address)` | `GET /v1/addresses/{address}/boxes/spendable` |
|
|
107
|
+
| `balance(address)` | `GET /v1/addresses/{address}/balance` |
|
|
108
|
+
| `history(address, { cursor, limit })` | `GET /v1/addresses/{address}/transactions` |
|
|
109
|
+
| `headers({ limit })` | `GET /v1/headers` |
|
|
110
|
+
| `box(boxId)` | `GET /v1/boxes/{boxId}` |
|
|
111
|
+
| `tokens(ids)` | `GET /v1/tokens/metadata?ids=...` |
|
|
112
|
+
| `submitTransaction(tx, { broadcast })` | `POST /v1/transactions` |
|
|
113
|
+
|
|
114
|
+
`tokens` answers the metadata of the tokens the relay's node knows among `ids`, leaving out the
|
|
115
|
+
others; more than 100 ids take a request per 100, one after another.
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
const { items } = await relay.rest.tokens(tokenIds);
|
|
119
|
+
const decimals = new Map(items.map((t) => [t.tokenId, t.decimals]));
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`submitTransaction` takes a signed tx in hex, or as Fleet's `SignedTransaction`, which the SDK
|
|
123
|
+
serializes. With `broadcast: false` the node only checks it.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const { transactionId } = await relay.rest.submitTransaction(signedTx);
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Every method takes a `signal` to cancel it. A response other than 2xx throws a `RelayError`
|
|
130
|
+
with its `status`, `code`, `reason` (why the node refused a tx) and `retryAfter`. A `503` is
|
|
131
|
+
retried after its `Retry-After`, up to `maxAttempts` in all, except
|
|
132
|
+
`capacity_exceeded`, which frees up only as keys go idle.
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
try {
|
|
136
|
+
await relay.rest.submitTransaction(signedTx);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (error instanceof RelayError && error.reason === "fee_too_low") {
|
|
139
|
+
// …
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Options
|
|
145
|
+
|
|
146
|
+
`new Relay(url, options)`:
|
|
147
|
+
|
|
148
|
+
- `backoff: { firstMs, maxMs }`: the waits before reconnecting and before retrying a key, each
|
|
149
|
+
drawn from 0 to a bound that doubles from `firstMs` to `maxMs`; 1 s and 30 s by default.
|
|
150
|
+
- `pageSize`: boxes per snapshot page, at most 1000 (the default).
|
|
151
|
+
- `maxAttempts`: attempts in all for a request answered `503`; 3 by default.
|
|
152
|
+
- `debug`: sees every message the relay sends, as text, and every new snapshot taken, for
|
|
153
|
+
logging.
|
|
154
|
+
- `fetch`, `WebSocket`: the implementations to use, the global ones by default.
|
|
155
|
+
|
|
156
|
+
## Using the SDK with UI frameworks
|
|
157
|
+
|
|
158
|
+
The SDK hands out two kinds of handle, with one shape:
|
|
159
|
+
|
|
160
|
+
- `relay.subscribe(key)`, a key's boxes: the confirmed set, the mempool's overlay and what is
|
|
161
|
+
spendable now, plus an address's balance;
|
|
162
|
+
- `relay.subscribe({ address }, { boxes: false })`, an address's balance alone;
|
|
163
|
+
- `relay.history(address, { refresh: true })`, an address's txs, the first page kept fresh.
|
|
164
|
+
|
|
165
|
+
Each has a `state` replaced whole on every change, `subscribe(listener)` (a Svelte store's
|
|
166
|
+
contract: the current state at once, then each change) and `close()`. So one
|
|
167
|
+
helper per framework serves all of them. Close a handle when the component that opened it goes
|
|
168
|
+
away: a subscription, and a history with `refresh`, hold the key at the relay until then.
|
|
169
|
+
|
|
170
|
+
### React
|
|
171
|
+
|
|
172
|
+
```tsx
|
|
173
|
+
import { useCallback, useEffect, useState, useSyncExternalStore, type DependencyList } from "react";
|
|
174
|
+
|
|
175
|
+
interface Handle<S> {
|
|
176
|
+
readonly state: S;
|
|
177
|
+
subscribe(listener: (state: S) => void): () => void;
|
|
178
|
+
close(): void;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Opens a handle while the component is mounted, again when `deps` change. */
|
|
182
|
+
export function useHandle<H extends Handle<unknown>>(open: () => H, deps: DependencyList) {
|
|
183
|
+
const [handle, setHandle] = useState<H>();
|
|
184
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
185
|
+
useEffect(() => {
|
|
186
|
+
const h = open();
|
|
187
|
+
setHandle(h);
|
|
188
|
+
return () => h.close();
|
|
189
|
+
}, deps);
|
|
190
|
+
const subscribe = useCallback(
|
|
191
|
+
(onChange: () => void) => handle?.subscribe(onChange) ?? (() => undefined),
|
|
192
|
+
[handle],
|
|
193
|
+
);
|
|
194
|
+
const state = useSyncExternalStore(subscribe, () => handle?.state as H["state"] | undefined);
|
|
195
|
+
return { handle, state };
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Vue
|
|
200
|
+
|
|
201
|
+
`examples/vue` is a runnable page built on this helper. `state` is frozen, so a `shallowRef` holds it. The handle opens again when what `open` reads
|
|
202
|
+
changes (a prop, a ref):
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
import { shallowRef, watchEffect } from "vue";
|
|
206
|
+
|
|
207
|
+
interface Handle<S> {
|
|
208
|
+
readonly state: S;
|
|
209
|
+
subscribe(listener: (state: S) => void): () => void;
|
|
210
|
+
close(): void;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function useHandle<H extends Handle<unknown>>(open: () => H) {
|
|
214
|
+
const handle = shallowRef<H>();
|
|
215
|
+
const state = shallowRef<H["state"]>();
|
|
216
|
+
watchEffect((onCleanup) => {
|
|
217
|
+
const h = open();
|
|
218
|
+
handle.value = h;
|
|
219
|
+
const off = h.subscribe((s) => (state.value = s));
|
|
220
|
+
onCleanup(() => {
|
|
221
|
+
off();
|
|
222
|
+
h.close();
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
return { handle, state };
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
### Svelte
|
|
230
|
+
|
|
231
|
+
A handle is a store: `$handle` is its state. Wrap the component in `{#key address}` where the
|
|
232
|
+
address can change.
|
|
233
|
+
|
|
234
|
+
```svelte
|
|
235
|
+
<script lang="ts">
|
|
236
|
+
import { onDestroy } from "svelte";
|
|
237
|
+
import type { Relay } from "@hergmes/sdk";
|
|
238
|
+
|
|
239
|
+
let { relay, address }: { relay: Relay; address: string } = $props();
|
|
240
|
+
const wallet = relay.subscribe({ address });
|
|
241
|
+
const history = relay.history(address, { refresh: true });
|
|
242
|
+
onDestroy(() => {
|
|
243
|
+
wallet.close();
|
|
244
|
+
history.close();
|
|
245
|
+
});
|
|
246
|
+
</script>
|
|
247
|
+
|
|
248
|
+
<p>{$wallet.phase}: {$wallet.boxes?.spendable.length ?? "…"} boxes spendable</p>
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### What each state holds
|
|
252
|
+
|
|
253
|
+
With React (Vue's `state` is a ref, `state.value` in a script):
|
|
254
|
+
|
|
255
|
+
```tsx
|
|
256
|
+
// An address's balance alone: no snapshot, the lightest subscription.
|
|
257
|
+
const { state: balance } = useHandle(
|
|
258
|
+
() => relay.subscribe({ address }, { boxes: false }),
|
|
259
|
+
[relay, address],
|
|
260
|
+
);
|
|
261
|
+
// balance?.balance?.confirmed.nanoErgs, balance?.balance?.pending.nanoErgs (signed)
|
|
262
|
+
|
|
263
|
+
// Boxes, for building txs: what can be spent now.
|
|
264
|
+
const { state: wallet } = useHandle(() => relay.subscribe({ address }), [relay, address]);
|
|
265
|
+
// wallet?.boxes?.spendable; its totals: utxoSum(wallet.boxes.spendable) from @fleet-sdk/common
|
|
266
|
+
|
|
267
|
+
// History: the first page kept fresh, older pages on demand.
|
|
268
|
+
const { state: txs, handle: history } = useHandle(
|
|
269
|
+
() => relay.history(address, { refresh: true }),
|
|
270
|
+
[relay, address],
|
|
271
|
+
);
|
|
272
|
+
// txs?.items, then history?.more() at the bottom of the list
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
- `phase` says whether `boxes` and `balance` are current: only `live` is. While the
|
|
276
|
+
subscription recovers (`snapshot`, `catching_up`, `disconnected`, `waiting`) they keep their
|
|
277
|
+
last live values, to show as stale; `rejected` is final until the next subscribe, and
|
|
278
|
+
`error` says why.
|
|
279
|
+
- Several handles on one key share its subscription: a balance-only one and a history with
|
|
280
|
+
`refresh` on an address the app already follows cost nothing at the relay.
|
|
281
|
+
- A history's `resets` goes up when the list was read again from its first page, its older
|
|
282
|
+
pages dropped: scroll back to the top. A history item without `height` is pending.
|