@vordium/sdk 0.1.2 → 0.1.3

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.
@@ -0,0 +1,180 @@
1
+ import { VordiumError } from './errors.js';
2
+ /** Answers that mean "try again": the write was not taken, or a gateway cannot tell. */
3
+ export const RESEND_STATUS = new Set([429, 502, 503, 504]);
4
+ const USED = /already used|already applied|duplicate|nonce not above|not above the account's last|must be greater than/i;
5
+ const USED_CODES = new Set(['nonce', 'nonce_used', 'duplicate', 'duplicate_nonce', 'vault_nonce']);
6
+ /** Whether an answer says the nonce (of a body we sent) is already used. */
7
+ export function nonceUsedAnswer(status, body) {
8
+ if (status === 409)
9
+ return true;
10
+ if (typeof body === 'string')
11
+ return USED.test(body);
12
+ if (!body || typeof body !== 'object')
13
+ return false;
14
+ const j = body;
15
+ if (typeof j.code === 'string' && USED_CODES.has(j.code.toLowerCase()))
16
+ return true;
17
+ return USED.test(['error', 'reason', 'message'].map((k) => String(j[k] ?? '')).join(' '));
18
+ }
19
+ /** The network did not answer any copy of a signed write. It may have arrived: read the account before sending a new
20
+ * one (a new one takes a new nonce). */
21
+ export class DeliveryUnknown extends VordiumError {
22
+ nonce;
23
+ attempts;
24
+ /** True when no copy left this machine (the connection could not be made on any try): it certainly did not arrive. */
25
+ neverSent = false;
26
+ constructor(message, nonce, attempts) {
27
+ super('delivery_unknown', message);
28
+ this.nonce = nonce;
29
+ this.attempts = attempts;
30
+ this.name = 'DeliveryUnknown';
31
+ }
32
+ }
33
+ const DNS = new Set(['ENOTFOUND', 'EAI_AGAIN']);
34
+ const AT_CONNECT = new Set(['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'ETIMEDOUT']);
35
+ /** True when the error happened while the connection was being made: the name lookup, a connect timeout, or a refused
36
+ * / unreachable error whose `syscall` is `connect`. The same refused or unreachable code on a connection that was
37
+ * already open (after a retransmit timeout), a timeout, or a gateway answer is not that: the copy may have arrived. */
38
+ export function neverSent(e) {
39
+ const name = e?.name;
40
+ if (name === 'TimeoutError' || name === 'AbortError')
41
+ return false; // our own time limit: the request had left
42
+ for (let x = e, i = 0; x && i < 4; x = x.cause, i++) {
43
+ const { code, syscall } = x;
44
+ if (typeof code !== 'string')
45
+ continue;
46
+ if (DNS.has(code) || code === 'UND_ERR_CONNECT_TIMEOUT')
47
+ return true;
48
+ if (AT_CONNECT.has(code) && syscall === 'connect')
49
+ return true;
50
+ }
51
+ return false;
52
+ }
53
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
54
+ const wait = (attempt, retryAfter) => {
55
+ const ra = Number(retryAfter);
56
+ return Math.max(Math.random() * Math.min(500 * 2 ** attempt, 8000), Number.isFinite(ra) && ra > 0 ? Math.min(ra, 30) * 1000 : 0);
57
+ };
58
+ /**
59
+ * Send one signed body until the network answers it, at most `attempts` times, each time the same bytes.
60
+ *
61
+ * `dedup` says whether the network applies this write once per nonce. Then a thrown error (a lost connection, a
62
+ * timeout) or HTTP 429/502/503/504 sends it again after a short random wait (at least the server's Retry-After); when an
63
+ * earlier copy may have arrived and the final answer is not a 2xx, `needsReadBack` is set. For a write the network does
64
+ * not deduplicate (`dedup: false`) a copy is sent again only when the first never left this machine or was answered
65
+ * 429; a timeout, a dropped connection or any 5xx throws {@link DeliveryUnknown} at once, so the caller reads state
66
+ * instead of risking a second effect.
67
+ */
68
+ export async function sendSame(send, opts = {}) {
69
+ const n = Math.max(1, Math.floor(opts.attempts ?? 3));
70
+ const pause = opts.sleep ?? sleep;
71
+ const dedup = opts.dedup ?? true;
72
+ let maybeArrived = false; // a copy sent in THIS call may have reached the network
73
+ let lastErr = null;
74
+ let last = null;
75
+ const unknown = (i, why) => new DeliveryUnknown(`It is not known whether the network received this write${opts.nonce != null ? ` (nonce ${opts.nonce})` : ''}: ${why} after ${i} ${i === 1 ? 'try' : 'tries'}. Read the account before sending a new one.`, opts.nonce ?? null, i);
76
+ const done = (r, i) => {
77
+ const ok = r.status >= 200 && r.status < 300;
78
+ if (!ok && r.status >= 500) {
79
+ if (!dedup)
80
+ throw unknown(i, `the network answered ${r.status}`);
81
+ return { ...r, attempts: i, needsReadBack: true }; // a gateway or node error: it may have applied
82
+ }
83
+ return { ...r, attempts: i, needsReadBack: maybeArrived && !ok };
84
+ };
85
+ for (let i = 0; i < n; i++) {
86
+ let r;
87
+ try {
88
+ r = await send();
89
+ }
90
+ catch (e) {
91
+ if (e instanceof VordiumError && !(e instanceof DeliveryUnknown) && e.code !== 'unreachable')
92
+ throw e;
93
+ lastErr = e;
94
+ if (!neverSent(e)) {
95
+ maybeArrived = true;
96
+ if (!dedup)
97
+ throw unknown(i + 1, 'the answer was lost');
98
+ }
99
+ if (i < n - 1)
100
+ await pause(wait(i, null));
101
+ continue;
102
+ }
103
+ if (RESEND_STATUS.has(r.status) && i < n - 1) {
104
+ if (r.status !== 429) {
105
+ maybeArrived = true;
106
+ if (!dedup)
107
+ throw unknown(i + 1, `a gateway answered ${r.status}`);
108
+ }
109
+ last = r;
110
+ lastErr = null;
111
+ await pause(wait(i, r.retryAfter));
112
+ continue;
113
+ }
114
+ return done(r, i + 1);
115
+ }
116
+ if (last && lastErr === null)
117
+ return done(last, n);
118
+ if (!maybeArrived)
119
+ throw Object.assign(new DeliveryUnknown(`The network could not be reached${opts.nonce != null ? ` (nonce ${opts.nonce})` : ''} after ${n} tries; nothing was sent.`, opts.nonce ?? null, n), { neverSent: true });
120
+ throw unknown(n, 'no copy was answered');
121
+ }
122
+ /**
123
+ * The network's block time, estimated as this computer's clock plus the offset measured at the last read: the latest
124
+ * block (JSON-RPC), cross-checked against the node's `/status` head (a JSON-RPC that serves another head is not this
125
+ * chain's clock). Null when unavailable. A reading is kept `ttlMs`; a failed one is retried after a fifth of that.
126
+ */
127
+ export class ChainClock {
128
+ readBlock;
129
+ readHead;
130
+ ttlMs;
131
+ now;
132
+ maxHeadGap;
133
+ offset = null;
134
+ nextRead = 0;
135
+ constructor(readBlock, readHead, ttlMs = 300_000, now = Date.now, maxHeadGap = 10_000) {
136
+ this.readBlock = readBlock;
137
+ this.readHead = readHead;
138
+ this.ttlMs = ttlMs;
139
+ this.now = now;
140
+ this.maxHeadGap = maxHeadGap;
141
+ }
142
+ static int(v) {
143
+ if (typeof v === 'number' && Number.isSafeInteger(v))
144
+ return v;
145
+ if (typeof v === 'string' && /^(0x[0-9a-f]+|\d+)$/i.test(v))
146
+ return Number(BigInt(v));
147
+ return null;
148
+ }
149
+ /** Read the network now: block time minus this computer's clock (ms), or null. */
150
+ async measure() {
151
+ try {
152
+ const b = await this.readBlock();
153
+ const ts = ChainClock.int(b?.timestamp), num = ChainClock.int(b?.number);
154
+ if (ts === null || ts <= 0)
155
+ return null;
156
+ const head = await this.readHead().catch(() => null);
157
+ if (head !== null && (num === null || Math.abs(head - num) > this.maxHeadGap))
158
+ return null;
159
+ return ts * 1000 + 500 - Math.floor(this.now());
160
+ }
161
+ catch {
162
+ return null;
163
+ }
164
+ }
165
+ inFlight = null;
166
+ /** Block time now, or null. When a reading is due, the caller that finds it due runs ONE read and waits for it;
167
+ * every other caller meanwhile is served the last reading at once (null before the first). */
168
+ async time() {
169
+ let o = this.offset;
170
+ if (this.now() >= this.nextRead && !this.inFlight) {
171
+ this.inFlight = this.measure().then((x) => {
172
+ this.offset = x;
173
+ this.nextRead = this.now() + (x !== null ? this.ttlMs : this.ttlMs / 5);
174
+ return x;
175
+ }).finally(() => { this.inFlight = null; });
176
+ o = await this.inFlight;
177
+ }
178
+ return o === null ? null : Math.floor(this.now()) + o;
179
+ }
180
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vordium/sdk",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "TypeScript and JavaScript SDK for Vordium Chain and the Vordex perpetuals exchange: signing, orders, session keys, agents, TWAP, margin mode and live feeds.",
5
5
  "license": "MIT",
6
6
  "author": "Vordium <dev@vordium.com>",