@vordium/sdk 0.2.2 → 0.3.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 +18 -0
- package/dist/cjs/client.js +251 -50
- package/dist/cjs/index.js +5 -1
- package/dist/cjs/network.js +36 -14
- package/dist/cjs/outcome.js +649 -0
- package/dist/cjs/outcomeWords.js +172 -0
- package/dist/cjs/pins.js +5 -0
- package/dist/cjs/releaseRecord.js +48 -11
- package/dist/cjs/types.js +2 -1
- package/dist/esm/client.d.ts +83 -6
- package/dist/esm/client.js +250 -49
- package/dist/esm/index.d.ts +3 -1
- package/dist/esm/index.js +3 -1
- package/dist/esm/network.d.ts +6 -0
- package/dist/esm/network.js +36 -14
- package/dist/esm/outcome.d.ts +201 -0
- package/dist/esm/outcome.js +623 -0
- package/dist/esm/outcomeWords.d.ts +168 -0
- package/dist/esm/outcomeWords.js +169 -0
- package/dist/esm/pins.d.ts +5 -0
- package/dist/esm/pins.js +5 -0
- package/dist/esm/releaseRecord.d.ts +6 -0
- package/dist/esm/releaseRecord.js +47 -10
- package/dist/esm/types.d.ts +1 -0
- package/dist/esm/types.js +2 -1
- package/package.json +1 -1
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a write whose answer was lost turned into, read from the node only.
|
|
3
|
+
*
|
|
4
|
+
* A write the network takes is answered "submitted": it carries no receipt, so when that answer is lost (a timeout, a
|
|
5
|
+
* dropped connection, a gateway error, a resent copy answered with the nonce code) the only way to know what happened
|
|
6
|
+
* is to read the state the write changes. The same for every action:
|
|
7
|
+
*
|
|
8
|
+
* sending ──answer──▶ (the answer decides)
|
|
9
|
+
* └─lost──▶ pending_checking ──the read shows it────────────▶ applied / applied_other
|
|
10
|
+
* │ ──a refusal record names it────▶ refused
|
|
11
|
+
* │ ──its signed deadline passed───▶ not_applied (only a write with a deadline)
|
|
12
|
+
* └──the limit passed, nothing proven─────▶ still_unknown (a later check can still end it)
|
|
13
|
+
*
|
|
14
|
+
* - Reads go to the node the write was sent to, never to an explorer: committed state first (`/orders`, `/agents`,
|
|
15
|
+
* `/session/get`, `/signers`), then the node's own records (`/events/account`) for a refusal and for filled versus
|
|
16
|
+
* cancelled. A missing record never means "not applied".
|
|
17
|
+
* - Every read has its own time limit; a failed read is "not shown yet", never a final.
|
|
18
|
+
* - Reads come every second for the first 10 s, every 2 s to 30 s, then every 5 s, up to {@link LIMIT_MS} (120 s) after
|
|
19
|
+
* the send. A call waits {@link SETTLE_MS} (30 s) by default and then returns `pending_checking` with a
|
|
20
|
+
* {@link PendingWrite} whose `check()` and `wait()` go on reading.
|
|
21
|
+
* - Only the same signed bytes are ever sent again, and only for a write the network applies once (a cancel, an agent
|
|
22
|
+
* revoke, the stop). Nothing here signs anything.
|
|
23
|
+
*
|
|
24
|
+
* Words come from the shared word file (`outcomeWords.ts`, generated). Under Node.js a write is noted in a journal next
|
|
25
|
+
* to the nonce marks (`outcome-pending-js.json`, mode 0600) before it is sent and taken off once its outcome is known:
|
|
26
|
+
* {@link pending} lists what is still open after a restart.
|
|
27
|
+
*/
|
|
28
|
+
import { sha256 } from '@noble/hashes/sha256';
|
|
29
|
+
import { OUTCOME_WORDS } from './outcomeWords.js';
|
|
30
|
+
import { cancelOutcome, matchesSigned } from './client.js';
|
|
31
|
+
/** How long after the send an outcome is checked before it is called `still_unknown`. */
|
|
32
|
+
export const LIMIT_MS = OUTCOME_WORDS.limit_s * 1000;
|
|
33
|
+
/** How long a call waits for the outcome before it returns `pending_checking` (0 returns at once). */
|
|
34
|
+
export const SETTLE_MS = 30_000;
|
|
35
|
+
/** The time limit of each read while checking. */
|
|
36
|
+
export const READ_TIMEOUT_MS = 6_000;
|
|
37
|
+
/** How many of the account's latest records are read (the records have no filter by client nonce). */
|
|
38
|
+
export const RECORDS_LIMIT = 200;
|
|
39
|
+
/** A deadline counts as passed only this long after it, on the network's clock (seconds). */
|
|
40
|
+
export const DEADLINE_GRACE_S = 10;
|
|
41
|
+
const JOURNAL_MAX_AGE_MS = 86_400_000;
|
|
42
|
+
const FINAL = new Set(['applied', 'applied_other', 'refused', 'not_applied']);
|
|
43
|
+
/** Milliseconds to the next read: 1 s for the first 10 s, 2 s to 30 s, then 5 s. */
|
|
44
|
+
export const intervalMs = (elapsedMs) => (elapsedMs < 10_000 ? 1000 : elapsedMs < 30_000 ? 2000 : 5000);
|
|
45
|
+
const fillIn = (s, f) => s.replace(/\{([a-z_]+)\}/g, (_, k) => (f[k] === null || f[k] === undefined ? '?' : String(f[k])));
|
|
46
|
+
/** {text, next} of `action` in `state`, the placeholders filled. */
|
|
47
|
+
export function say(action, state, fill = {}) {
|
|
48
|
+
const w = OUTCOME_WORDS.actions[action][state];
|
|
49
|
+
if (!w)
|
|
50
|
+
throw new Error(`no words for ${action} ${state}`);
|
|
51
|
+
return { text: fillIn(w.text, fill), next: fillIn(w.next, fill) };
|
|
52
|
+
}
|
|
53
|
+
/** A chain meaning as the end of a sentence ("Not placed: {meaning}."): no closing stop, a lower-case first word. */
|
|
54
|
+
export function clause(meaning) {
|
|
55
|
+
let s = String(meaning ?? '').trim().replace(/\.+$/, '').trim();
|
|
56
|
+
if (s.length > 1 && /[A-Z]/.test(s[0]) && /[a-z '’]/.test(s[1]))
|
|
57
|
+
s = s[0].toLowerCase() + s.slice(1);
|
|
58
|
+
return s || 'the network refused it';
|
|
59
|
+
}
|
|
60
|
+
/** sha256 hex of the exact bytes sent: the same on every copy of one signed write. */
|
|
61
|
+
export function bodyDigest(body) {
|
|
62
|
+
return Array.from(sha256(new TextEncoder().encode(body)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
63
|
+
}
|
|
64
|
+
const SAME_BYTES = new Set(Object.entries(OUTCOME_WORDS.resend_while_pending).filter(([, v]) => v).map(([k]) => k));
|
|
65
|
+
export function resendRule(action, state) {
|
|
66
|
+
if (FINAL.has(state))
|
|
67
|
+
return { allowed: false, sameBytes: false, label: null, why: 'final' };
|
|
68
|
+
if (SAME_BYTES.has(action))
|
|
69
|
+
return { allowed: true, sameBytes: true, label: OUTCOME_WORDS.resend_while_pending[action], why: 'applies_once' };
|
|
70
|
+
if (action === 'order')
|
|
71
|
+
return { allowed: false, sameBytes: false, label: null, why: 'a_new_signature_is_a_new_order' };
|
|
72
|
+
return { allowed: false, sameBytes: false, label: null, why: 'not_known_to_apply_once' };
|
|
73
|
+
}
|
|
74
|
+
const none = (still = {}, stillKey) => ({ state: null, fill: {}, read: null, still, stillKey });
|
|
75
|
+
const asInt = (v) => (typeof v === 'number' && Number.isSafeInteger(v) ? v : typeof v === 'string' && /^\d{1,16}$/.test(v.trim()) ? Number(v.trim()) : null);
|
|
76
|
+
const rd = (route, height) => ({ source: 'node', route, height, atMs: Date.now() });
|
|
77
|
+
/** GET reads of one node; every route read is kept in `routes`. */
|
|
78
|
+
export class NodeReads {
|
|
79
|
+
read;
|
|
80
|
+
routes = [];
|
|
81
|
+
codesRead = null;
|
|
82
|
+
constructor(read) {
|
|
83
|
+
this.read = read;
|
|
84
|
+
}
|
|
85
|
+
async get(path) {
|
|
86
|
+
this.routes.push(path);
|
|
87
|
+
try {
|
|
88
|
+
return await this.read(path);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return { status: null, body: null };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async ok(path) { const r = await this.get(path); return r.status === 200 ? r.body : null; }
|
|
95
|
+
async records(owner) {
|
|
96
|
+
const j = (await this.ok(`/events/account/${owner.toLowerCase()}?limit=${RECORDS_LIMIT}`));
|
|
97
|
+
if (!j || !Array.isArray(j.events))
|
|
98
|
+
return { recs: null, cov: {} };
|
|
99
|
+
return { recs: j.events.filter((e) => !!e && typeof e === 'object'), cov: (j.coverage && typeof j.coverage === 'object' ? j.coverage : {}) };
|
|
100
|
+
}
|
|
101
|
+
async head() { return asInt((await this.ok('/status'))?.chain_head); }
|
|
102
|
+
async codes() {
|
|
103
|
+
if (!this.codesRead) {
|
|
104
|
+
const j = await this.ok('/orders/codes');
|
|
105
|
+
this.codesRead = j && typeof j === 'object' ? j : {};
|
|
106
|
+
}
|
|
107
|
+
return this.codesRead;
|
|
108
|
+
}
|
|
109
|
+
async meaning(code, agent) {
|
|
110
|
+
const rows = (await this.codes())[agent ? 'agent_refusal_keys' : 'order_refusal_codes'];
|
|
111
|
+
for (const r of Array.isArray(rows) ? rows : []) {
|
|
112
|
+
if (r && typeof r === 'object' && r[agent ? 'key' : 'code'] === code) {
|
|
113
|
+
const x = r;
|
|
114
|
+
return { meaning: typeof x.meaning === 'string' ? x.meaning : null, action: typeof x.action === 'string' ? x.action : null };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return { meaning: null, action: null };
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** The height of the newest record older than `sinceMs` when the read of the latest records covers every record since
|
|
121
|
+
* then: it holds such a record (so it reached back before the send) and no gap (a snapshot restore) or pruning lies
|
|
122
|
+
* above it. Null when that is not shown. */
|
|
123
|
+
function scanAnchor(recs, cov, sinceMs) {
|
|
124
|
+
const at = (e) => { const v = asInt(e.at_ms); return v !== null && v >= 1e12 ? v : null; }; // milliseconds only
|
|
125
|
+
const before = recs.filter((e) => (at(e) ?? sinceMs) < sinceMs).map((e) => asInt(e.height)).filter((h) => h !== null);
|
|
126
|
+
if (!before.length)
|
|
127
|
+
return null;
|
|
128
|
+
const anchor = Math.max(...before);
|
|
129
|
+
for (const g of Array.isArray(cov.gaps) ? cov.gaps : []) {
|
|
130
|
+
const x = (g && typeof g === 'object' ? g : {});
|
|
131
|
+
const resumed = asInt(x.resumed_at), after = asInt(x.after_height);
|
|
132
|
+
if (resumed === null || after === null || resumed > anchor || after >= anchor)
|
|
133
|
+
return null; // above the anchor, or not understood
|
|
134
|
+
}
|
|
135
|
+
const pruned = asInt(cov.pruned_below);
|
|
136
|
+
return pruned === null || pruned <= anchor ? anchor : null;
|
|
137
|
+
}
|
|
138
|
+
async function deadlinePassed(validUntilS, chainMs) {
|
|
139
|
+
if (validUntilS == null || !chainMs)
|
|
140
|
+
return false;
|
|
141
|
+
const now = await chainMs().catch(() => null);
|
|
142
|
+
return typeof now === 'number' && now > (validUntilS + DEADLINE_GRACE_S) * 1000;
|
|
143
|
+
}
|
|
144
|
+
function closedWords(rec) {
|
|
145
|
+
if (String(rec.status ?? '').toLowerCase() === 'filled')
|
|
146
|
+
return 'Filled';
|
|
147
|
+
if ((asInt(rec.filled_total_18dec) ?? asInt(rec.filled_18dec) ?? 0) > 0 || rec.partially_filled === true)
|
|
148
|
+
return 'Partly filled';
|
|
149
|
+
return 'Placed';
|
|
150
|
+
}
|
|
151
|
+
/** Refusal codes that name the nonce: a later copy of OUR write (or another signer's) meets them while an earlier copy
|
|
152
|
+
* applied, so they never prove that our write did not apply. */
|
|
153
|
+
export const NONCE_CODES = new Set(['nonce', 'nonce_used', 'nonce_window', 'nonce_jam', 'duplicate', 'duplicate_nonce']);
|
|
154
|
+
/** Whether a row or record was signed by our signer (`agent` when an agent of the account signed; null: the account's
|
|
155
|
+
* own key or its session key). The network keeps one nonce window per signer. */
|
|
156
|
+
function signerMatches(rec, agent) {
|
|
157
|
+
const got = typeof rec.agent === 'string' && rec.agent ? rec.agent.toLowerCase() : null;
|
|
158
|
+
return got === (agent ? agent.toLowerCase() : null);
|
|
159
|
+
}
|
|
160
|
+
/** The node's records are being written and have reached `head` (read just before them). */
|
|
161
|
+
function recordsCurrent(head, cov) {
|
|
162
|
+
if (head === null || cov.recording === false)
|
|
163
|
+
return false;
|
|
164
|
+
const last = asInt(cov.last_height);
|
|
165
|
+
return last !== null && last >= head;
|
|
166
|
+
}
|
|
167
|
+
/** Whether the signer of a write is an agent of the account, read once from the node (`/agents/{owner}/{signer}`) and
|
|
168
|
+
* kept only once the read answered: {known, agent address or null}. */
|
|
169
|
+
export function signerOf(r, owner, signer, journalId = null) {
|
|
170
|
+
let known = !signer || signer.toLowerCase() === owner.toLowerCase() ? { known: true, agent: null } : null;
|
|
171
|
+
return async () => {
|
|
172
|
+
if (known)
|
|
173
|
+
return known;
|
|
174
|
+
const g = await r.get(`/agents/${owner}/${String(signer).toLowerCase()}`);
|
|
175
|
+
const a = g.body;
|
|
176
|
+
if (g.status === 200 && a && typeof a === 'object')
|
|
177
|
+
known = { known: true, agent: a.found !== false && a.agent ? signer : null };
|
|
178
|
+
else
|
|
179
|
+
return { known: false, agent: null }; // not answered: asked again at the next check
|
|
180
|
+
await journalSet(journalId, { agent: known.agent });
|
|
181
|
+
return known;
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const sameId = (o, id) => !!o && typeof o === 'object' && String(o.id ?? o.order_id) === id;
|
|
185
|
+
/** An order by its client nonce: listed with what was signed, its closing or placing record, a refusal record with its
|
|
186
|
+
* nonce, or — for an order with a signed deadline, once it passed and a full read of the records shows nothing —
|
|
187
|
+
* not_applied. */
|
|
188
|
+
export async function judgeOrder(r, owner, clientNonce, signed, o = {}) {
|
|
189
|
+
if (!signed)
|
|
190
|
+
return none(); // without what was signed nothing can be told apart from another write
|
|
191
|
+
const want = String(clientNonce);
|
|
192
|
+
const newer = (rec) => {
|
|
193
|
+
if (o.rewound == null)
|
|
194
|
+
return true;
|
|
195
|
+
const ts = [rec.timestamp_ms, rec.timestampMs, rec.ts_ms, rec.at_ms].map(asInt).find((x) => x !== null);
|
|
196
|
+
return ts != null && ts > o.rewound;
|
|
197
|
+
};
|
|
198
|
+
const match = (rec) => matchesSigned(rec, signed);
|
|
199
|
+
const routeO = `/orders/${owner}`;
|
|
200
|
+
const rows = await r.ok(routeO);
|
|
201
|
+
const resting = Array.isArray(rows) ? rows.find((x) => x && String(x.client_nonce) === want && match(x) && signerMatches(x, o.agent) && newer(x)) : undefined;
|
|
202
|
+
const head = o.validUntilS != null ? await r.head() : null;
|
|
203
|
+
const { recs, cov } = await r.records(owner);
|
|
204
|
+
const routeR = `/events/account/${owner.toLowerCase()}`;
|
|
205
|
+
const mine = (recs ?? []).filter((e) => String(e.client_nonce) === want && newer(e) && signerMatches(e, o.agent));
|
|
206
|
+
const placed = mine.find((e) => e.kind === 'order_placed' && match(e));
|
|
207
|
+
const closed = mine.find((e) => e.kind === 'order_closed' && match(e));
|
|
208
|
+
if (resting) {
|
|
209
|
+
const h = asInt(placed?.height) ?? (await r.head());
|
|
210
|
+
return { state: 'applied', fill: { order_words: 'Placed', height: h }, read: rd(routeO, h), found: { source: 'orders', ...resting } };
|
|
211
|
+
}
|
|
212
|
+
if (closed || placed) {
|
|
213
|
+
const rec = (closed ?? placed);
|
|
214
|
+
const h = asInt(rec.height);
|
|
215
|
+
return { state: 'applied', fill: { order_words: closed ? closedWords(closed) : 'Placed', height: h }, read: rd(routeR, h), found: { source: 'events', ...rec } };
|
|
216
|
+
}
|
|
217
|
+
const pair = signed.pairId;
|
|
218
|
+
for (const [kind, agent] of [['agent_refused', true], ['order_refused', false]]) {
|
|
219
|
+
const e = mine.find((x) => x.kind === kind && asInt(x.pair_id) === pair && !NONCE_CODES.has(String((agent ? x.reason : x.code) ?? '').toLowerCase()));
|
|
220
|
+
if (e) {
|
|
221
|
+
const code = String((agent ? e.reason : e.code) ?? '');
|
|
222
|
+
const m = await r.meaning(code, agent);
|
|
223
|
+
const meaning = m.meaning ?? (typeof e.meaning === 'string' ? e.meaning : null) ?? code;
|
|
224
|
+
const h = asInt(e.height);
|
|
225
|
+
return { state: 'refused', fill: { meaning: clause(meaning), action: m.action ?? '' }, read: rd(routeR, h), refusal: { code, meaning, action: m.action }, found: { source: 'events', ...e } };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (Array.isArray(rows) && recs && o.sentAtMs != null && (await deadlinePassed(o.validUntilS, o.chainMs)) && scanAnchor(recs, cov, o.sentAtMs - 60_000) !== null
|
|
229
|
+
&& recordsCurrent(head, cov)) {
|
|
230
|
+
return { state: 'not_applied', fill: {}, read: rd(routeR, null) };
|
|
231
|
+
}
|
|
232
|
+
return none();
|
|
233
|
+
}
|
|
234
|
+
/** A cancel: the order no longer listed AND its record says cancelled (applied) or filled (applied_other). */
|
|
235
|
+
export async function judgeCancel(r, owner, orderId) {
|
|
236
|
+
const rows = await r.ok(`/orders/${owner}`);
|
|
237
|
+
if (!Array.isArray(rows))
|
|
238
|
+
return none({}, 'still_unknown_unread');
|
|
239
|
+
if (rows.some((o) => sameId(o, orderId.toString())))
|
|
240
|
+
return none();
|
|
241
|
+
const { recs } = await r.records(owner);
|
|
242
|
+
const how = cancelOutcome(recs ?? [], orderId);
|
|
243
|
+
const rec = (recs ?? []).find((e) => String(e.order_id ?? e.id) === orderId.toString() && (e.kind === 'order_closed' || e.kind === 'order_cancelled'));
|
|
244
|
+
const h = asInt(rec?.height);
|
|
245
|
+
const routeR = `/events/account/${owner.toLowerCase()}`;
|
|
246
|
+
if (how === 'cancelled')
|
|
247
|
+
return { state: 'applied', fill: { height: h }, read: rd(routeR, h), found: rec ?? null };
|
|
248
|
+
if (how === 'filled')
|
|
249
|
+
return { state: 'applied_other', fill: { height: h }, read: rd(routeR, h), found: rec ?? null };
|
|
250
|
+
return none({ order_gone: true }, 'still_unknown_gone');
|
|
251
|
+
}
|
|
252
|
+
/** The account's order ids in an `/orders` read (the network's liquidation order left out); null when unreadable. */
|
|
253
|
+
export function orderIds(rows, pairId = 0) {
|
|
254
|
+
if (!Array.isArray(rows))
|
|
255
|
+
return null;
|
|
256
|
+
const out = [];
|
|
257
|
+
for (const o of rows) {
|
|
258
|
+
if (!o || typeof o !== 'object' || o.liquidation === true || o.is_liquidation === true)
|
|
259
|
+
continue;
|
|
260
|
+
if (pairId && asInt(o.pair_id) !== pairId)
|
|
261
|
+
continue;
|
|
262
|
+
const i = o.id ?? o.order_id;
|
|
263
|
+
if (i !== undefined && i !== null)
|
|
264
|
+
out.push(String(i));
|
|
265
|
+
}
|
|
266
|
+
return out;
|
|
267
|
+
}
|
|
268
|
+
/** A cancel-all: none of the orders listed before the send is still listed, every one of them has its closing record,
|
|
269
|
+
* and at least one closed as cancelled (applied; applied_other when some filled first). With nothing listed before, or
|
|
270
|
+
* no cancel among the records, nothing shows that the cancel-all applied: it stays not known. */
|
|
271
|
+
export async function judgeCancelAll(r, owner, before, pairId = 0) {
|
|
272
|
+
const routeO = `/orders/${owner}`;
|
|
273
|
+
const ids = orderIds(await r.ok(routeO), pairId);
|
|
274
|
+
if (!ids)
|
|
275
|
+
return none({}, 'still_unknown_unread');
|
|
276
|
+
if (!before)
|
|
277
|
+
return none({ n: ids.length });
|
|
278
|
+
const left = before.filter((i) => ids.includes(i));
|
|
279
|
+
if (left.length || !before.length)
|
|
280
|
+
return none({ n: left.length });
|
|
281
|
+
const recs = (await r.records(owner)).recs ?? [];
|
|
282
|
+
const how = before.map((i) => cancelOutcome(recs, BigInt(i)));
|
|
283
|
+
if (how.some((h) => h === null) || !how.includes('cancelled'))
|
|
284
|
+
return none({ n: 0 });
|
|
285
|
+
const m = before.length, k = how.filter((h) => h === 'filled').length;
|
|
286
|
+
const h = await r.head();
|
|
287
|
+
if (k)
|
|
288
|
+
return { state: 'applied_other', fill: { n: m - k, m, k }, read: rd(routeO, h) };
|
|
289
|
+
return { state: 'applied', fill: { n: m }, read: rd(routeO, h) };
|
|
290
|
+
}
|
|
291
|
+
/** A batch: every place shown (or refused) by its client nonce, and every cancelled order (by id, or by client nonce)
|
|
292
|
+
* no longer listed and closed in the records. Applied only when every action is decided. */
|
|
293
|
+
export async function judgeBatch(r, owner, places, cancels, rewound = null, cancelNonces = [], agent = null) {
|
|
294
|
+
const routeO = `/orders/${owner}`;
|
|
295
|
+
if (!places.length && !cancels.length && !cancelNonces.length)
|
|
296
|
+
return none();
|
|
297
|
+
if (cancels.length || cancelNonces.length) {
|
|
298
|
+
const rows = await r.ok(routeO);
|
|
299
|
+
if (!Array.isArray(rows))
|
|
300
|
+
return none({}, 'still_unknown_unread');
|
|
301
|
+
const ids = orderIds(rows) ?? [];
|
|
302
|
+
const cns = new Set(rows.map((o) => String(o?.client_nonce)));
|
|
303
|
+
if (cancels.some((i) => ids.includes(i)) || cancelNonces.some((n) => cns.has(String(n))))
|
|
304
|
+
return none({ n: cancels.length + cancelNonces.length });
|
|
305
|
+
const recs = (await r.records(owner)).recs ?? [];
|
|
306
|
+
if (cancels.some((i) => cancelOutcome(recs, BigInt(i)) === null))
|
|
307
|
+
return none({ n: 0 });
|
|
308
|
+
const closed = new Set(recs.filter((e) => e.kind === 'order_closed').map((e) => String(e.client_nonce)));
|
|
309
|
+
if (cancelNonces.some((n) => !closed.has(String(n))))
|
|
310
|
+
return none({ n: 0 });
|
|
311
|
+
}
|
|
312
|
+
const res = [];
|
|
313
|
+
for (const [n, s] of places)
|
|
314
|
+
res.push(await judgeOrder(r, owner, n, s, { rewound, agent }));
|
|
315
|
+
if (res.some((v) => v.state === null))
|
|
316
|
+
return none();
|
|
317
|
+
if (res.length && !cancels.length && !cancelNonces.length && res.every((v) => v.state === 'refused'))
|
|
318
|
+
return res[0];
|
|
319
|
+
if (!res.length)
|
|
320
|
+
return { state: 'applied', fill: { n: cancels.length + cancelNonces.length }, read: rd(routeO, await r.head()) };
|
|
321
|
+
const h = Math.max(0, ...res.map((v) => (typeof v.fill.height === 'number' ? v.fill.height : 0))) || (await r.head());
|
|
322
|
+
const refused = res.filter((v) => v.state === 'refused').length;
|
|
323
|
+
return { state: 'applied', fill: { order_words: 'Placed', height: h, placed: res.length - refused, refused, cancelled: cancels.length + cancelNonces.length }, read: rd(routeO, h) };
|
|
324
|
+
}
|
|
325
|
+
/** An agent revoke: the agent's committed record reads `revoked`. */
|
|
326
|
+
export async function judgeRevoke(r, owner, agent) {
|
|
327
|
+
const route = `/agents/${owner}/${agent}`;
|
|
328
|
+
const a = (await r.ok(route));
|
|
329
|
+
if (!a || typeof a !== 'object')
|
|
330
|
+
return none({}, 'still_unknown_unread');
|
|
331
|
+
if (String(a.status ?? '').toLowerCase() !== 'revoked')
|
|
332
|
+
return none();
|
|
333
|
+
const h = asInt(a.revoked_height);
|
|
334
|
+
return { state: 'applied', fill: { height: h, m: asInt(a.revoke_orders_cancelled) ?? 0 }, read: rd(route, h ?? asInt(a.head_height)), found: a };
|
|
335
|
+
}
|
|
336
|
+
/** The session nonce a read names (`nonce`, `last_nonce` or `session_nonce`, the largest), else null. */
|
|
337
|
+
export function storedSessionNonce(...reads) {
|
|
338
|
+
let out = null;
|
|
339
|
+
for (const j of reads) {
|
|
340
|
+
if (!j || typeof j !== 'object')
|
|
341
|
+
continue;
|
|
342
|
+
for (const k of ['nonce', 'last_nonce', 'session_nonce']) {
|
|
343
|
+
const v = asInt(j[k]);
|
|
344
|
+
if (v !== null)
|
|
345
|
+
out = out === null ? v : Math.max(out, v);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return out;
|
|
349
|
+
}
|
|
350
|
+
/** The stop (StopAllSigners): no trading key (the session read answers "no active session") and no live agent
|
|
351
|
+
* (`/signers` names `app_session` as null and `live_agents` 0); then the open orders decide applied (none) or
|
|
352
|
+
* applied_other (orders the wallet placed itself stay). Past its deadline with a key or an agent still live, and the
|
|
353
|
+
* stored session nonce still below the stop's `nonce`: not_applied. */
|
|
354
|
+
export async function judgeStop(r, owner, validUntilS = null, chainMs = null, nonce = null) {
|
|
355
|
+
const s = await r.get(`/session/get?owner=${owner}`);
|
|
356
|
+
const body = (s.body && typeof s.body === 'object' ? s.body : {});
|
|
357
|
+
const session = s.status === 404 && /no active session/i.test(String(body.error ?? '')) ? 'none' : s.status === 200 && typeof body.session_key === 'string' ? 'live' : null;
|
|
358
|
+
const sg = (await r.ok(`/signers/${owner}`));
|
|
359
|
+
const live = sg && typeof sg === 'object' ? asInt(sg.live_agents) : null;
|
|
360
|
+
const app = sg && typeof sg === 'object' && 'app_session' in sg ? sg.app_session : 'unread';
|
|
361
|
+
const rows = await r.ok(`/orders/${owner}`);
|
|
362
|
+
const orders = Array.isArray(rows) ? rows.length : null;
|
|
363
|
+
const h = sg && typeof sg === 'object' ? asInt(sg.head_height) : null;
|
|
364
|
+
const route = `/signers/${owner}`;
|
|
365
|
+
const appLive = app !== null && app !== 'unread';
|
|
366
|
+
if (session === 'none' && live === 0 && app === null) {
|
|
367
|
+
if (orders === 0)
|
|
368
|
+
return { state: 'applied', fill: {}, read: rd(route, h) };
|
|
369
|
+
if (orders !== null)
|
|
370
|
+
return { state: 'applied_other', fill: { n: orders }, read: rd(route, h) };
|
|
371
|
+
}
|
|
372
|
+
else if (session === 'live' || (live ?? 0) > 0 || appLive) {
|
|
373
|
+
const stored = storedSessionNonce(s.body, sg);
|
|
374
|
+
if (nonce !== null && stored !== null && stored < nonce && (await deadlinePassed(validUntilS, chainMs)))
|
|
375
|
+
return { state: 'not_applied', fill: {}, read: rd(route, h) };
|
|
376
|
+
}
|
|
377
|
+
const parts = [];
|
|
378
|
+
if (session === 'live' || appLive)
|
|
379
|
+
parts.push('your trading key is still on');
|
|
380
|
+
else if (session === null)
|
|
381
|
+
parts.push('your trading key could not be read');
|
|
382
|
+
if (live === null)
|
|
383
|
+
parts.push('your agents could not be read');
|
|
384
|
+
else if (live > 0)
|
|
385
|
+
parts.push(`${live} ${live === 1 ? 'agent is' : 'agents are'} still live`);
|
|
386
|
+
if (orders === null)
|
|
387
|
+
parts.push('your open orders could not be read');
|
|
388
|
+
const what = parts.join('; ') || 'the network has not shown the stop';
|
|
389
|
+
return none({ what_is_live: what[0].toUpperCase() + what.slice(1) });
|
|
390
|
+
}
|
|
391
|
+
// ── a write being checked ───────────────────────────────────────────────────────────────────────────────────────────
|
|
392
|
+
/** The clock the checks run on (tests replace it with a virtual one). */
|
|
393
|
+
export const outcomeClock = {
|
|
394
|
+
now: () => Date.now(),
|
|
395
|
+
sleep: (ms) => new Promise((res) => setTimeout(res, ms)),
|
|
396
|
+
};
|
|
397
|
+
/** A sent write whose outcome is being read: `check()` reads once, `wait()` reads until a final or a time limit,
|
|
398
|
+
* `resendSame()` sends the same signed bytes again (only where the network applies the write once). */
|
|
399
|
+
export class PendingWrite {
|
|
400
|
+
action;
|
|
401
|
+
judge;
|
|
402
|
+
opts;
|
|
403
|
+
startedMs;
|
|
404
|
+
attempts;
|
|
405
|
+
last;
|
|
406
|
+
found = null;
|
|
407
|
+
busy = Promise.resolve();
|
|
408
|
+
constructor(action, judge, opts = {}) {
|
|
409
|
+
this.action = action;
|
|
410
|
+
this.judge = judge;
|
|
411
|
+
this.opts = opts;
|
|
412
|
+
if (!(action in OUTCOME_WORDS.actions))
|
|
413
|
+
throw new Error(`no words for the action ${action}`);
|
|
414
|
+
this.startedMs = opts.startedMs ?? outcomeClock.now();
|
|
415
|
+
this.attempts = opts.meta?.attempts ?? 1;
|
|
416
|
+
this.last = this.outcome('pending_checking', none());
|
|
417
|
+
}
|
|
418
|
+
get limitMs() { return this.opts.limitMs ?? LIMIT_MS; }
|
|
419
|
+
get elapsedMs() { return outcomeClock.now() - this.startedMs; }
|
|
420
|
+
outcome(state, v) {
|
|
421
|
+
const fill = FINAL.has(state) ? v.fill : v.still ?? {};
|
|
422
|
+
const words = OUTCOME_WORDS.actions[this.action];
|
|
423
|
+
const key = (state === 'still_unknown' && v.stillKey && v.stillKey in words ? v.stillKey : state);
|
|
424
|
+
const { text, next } = say(this.action, key, fill);
|
|
425
|
+
let resend = resendRule(this.action, state);
|
|
426
|
+
if (resend.allowed && !this.opts.resend)
|
|
427
|
+
resend = { allowed: false, sameBytes: false, label: null, why: 'bytes_not_kept' };
|
|
428
|
+
const m = this.opts.meta ?? {};
|
|
429
|
+
const counts = {};
|
|
430
|
+
for (const [k, x] of Object.entries(fill))
|
|
431
|
+
if (typeof x === 'number' || typeof x === 'boolean')
|
|
432
|
+
counts[k] = x;
|
|
433
|
+
return {
|
|
434
|
+
action: this.action, state, text, next, final: FINAL.has(state),
|
|
435
|
+
applied: state === 'applied' || state === 'applied_other' ? true : state === 'refused' || state === 'not_applied' ? false : null,
|
|
436
|
+
refusal: v.refusal ?? null, read: v.read, resend, nonce: m.nonce ?? null,
|
|
437
|
+
orderId: m.orderId ?? null, agent: m.agent ?? null, digest: m.digest ?? null, attempts: this.attempts, counts,
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
/** Read once. A final ends it (and takes it off the journal); else `pending_checking` within the limit,
|
|
441
|
+
* `still_unknown` after it. */
|
|
442
|
+
async check() {
|
|
443
|
+
const run = this.busy.then(async () => {
|
|
444
|
+
let v;
|
|
445
|
+
try {
|
|
446
|
+
v = await this.judge();
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
v = none();
|
|
450
|
+
} // a failed read is "not shown yet"
|
|
451
|
+
this.found = v.found ?? null;
|
|
452
|
+
if (v.state && FINAL.has(v.state)) {
|
|
453
|
+
this.last = this.outcome(v.state, v);
|
|
454
|
+
await journalDone(this.opts.journalId);
|
|
455
|
+
}
|
|
456
|
+
else
|
|
457
|
+
this.last = this.outcome(this.elapsedMs >= this.limitMs ? 'still_unknown' : 'pending_checking', v);
|
|
458
|
+
return this.last;
|
|
459
|
+
});
|
|
460
|
+
this.busy = run.catch(() => undefined);
|
|
461
|
+
return run;
|
|
462
|
+
}
|
|
463
|
+
/** Read until a final, or `limitMs` from now (default: to the end of the limit after the send; at least one read). */
|
|
464
|
+
async wait(limitMs) {
|
|
465
|
+
const end = outcomeClock.now() + Math.max(0, limitMs ?? this.limitMs - this.elapsedMs);
|
|
466
|
+
for (;;) {
|
|
467
|
+
const o = await this.check();
|
|
468
|
+
const now = outcomeClock.now();
|
|
469
|
+
if (o.final || now >= end)
|
|
470
|
+
return o;
|
|
471
|
+
await outcomeClock.sleep(Math.max(0, Math.min(intervalMs(now - this.startedMs), end - now)));
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
/** Send the same signed bytes once more (a cancel, a revoke, the stop), then read once. Throws for any other write
|
|
475
|
+
* or once the outcome is final. */
|
|
476
|
+
async resendSame() {
|
|
477
|
+
const rule = resendRule(this.action, this.last.state);
|
|
478
|
+
if (!rule.allowed || !this.opts.resend)
|
|
479
|
+
throw new Error(`this write is not sent again: ${rule.why}`);
|
|
480
|
+
try {
|
|
481
|
+
await this.opts.resend();
|
|
482
|
+
}
|
|
483
|
+
catch { /* its answer decides nothing: the read does */ }
|
|
484
|
+
finally {
|
|
485
|
+
this.attempts++;
|
|
486
|
+
}
|
|
487
|
+
return this.check();
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/** Wait inside the call: up to `settleMs` (0 = no read: `pending_checking` at once). */
|
|
491
|
+
export async function settle(pw, settleMs) {
|
|
492
|
+
if (!(settleMs > 0))
|
|
493
|
+
return pw.last;
|
|
494
|
+
return pw.wait(Math.min(settleMs, Math.max(0, pw.limitMs - pw.elapsedMs)));
|
|
495
|
+
}
|
|
496
|
+
// ── the journal (Node.js) ───────────────────────────────────────────────────────────────────────────────────────────
|
|
497
|
+
export const JOURNAL_NAME = 'outcome-pending-js.json';
|
|
498
|
+
const nodeModule = async (name) => (await import(name)); // kept out of browser bundles
|
|
499
|
+
const pid = () => globalThis.process?.pid ?? 0;
|
|
500
|
+
const isNode = () => typeof globalThis.process?.versions?.node === 'string';
|
|
501
|
+
let jturn = Promise.resolve();
|
|
502
|
+
async function journalPath() {
|
|
503
|
+
if (!isNode())
|
|
504
|
+
return null;
|
|
505
|
+
const path = await nodeModule('node:path');
|
|
506
|
+
const os = await nodeModule('node:os');
|
|
507
|
+
const env = globalThis.process?.env ?? {};
|
|
508
|
+
return path.join(env.VORDIUM_STATE_DIR ?? path.join(os.homedir(), '.vordium', 'nonces'), JOURNAL_NAME);
|
|
509
|
+
}
|
|
510
|
+
async function readJournal() {
|
|
511
|
+
const p = await journalPath();
|
|
512
|
+
if (!p)
|
|
513
|
+
return {};
|
|
514
|
+
try {
|
|
515
|
+
const fs = await nodeModule('node:fs/promises');
|
|
516
|
+
const j = JSON.parse(await fs.readFile(p, 'utf8'));
|
|
517
|
+
return j && typeof j === 'object' && !Array.isArray(j) ? j : {};
|
|
518
|
+
}
|
|
519
|
+
catch {
|
|
520
|
+
return {};
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
function journalUpdate(fn) {
|
|
524
|
+
const run = jturn.then(async () => {
|
|
525
|
+
const p = await journalPath();
|
|
526
|
+
if (!p)
|
|
527
|
+
return;
|
|
528
|
+
try {
|
|
529
|
+
const fs = await nodeModule('node:fs/promises');
|
|
530
|
+
const path = await nodeModule('node:path');
|
|
531
|
+
await fs.mkdir(path.dirname(p), { recursive: true, mode: 0o700 });
|
|
532
|
+
// one process at a time on this computer: an exclusive lock file (a lock older than 10 s is stale), at most 5 s
|
|
533
|
+
const lock = `${p}.lock`;
|
|
534
|
+
const token = `${pid()}.${Math.random().toString(36).slice(2)}`;
|
|
535
|
+
let held = false;
|
|
536
|
+
for (const end = Date.now() + 5000; !held && Date.now() < end;) {
|
|
537
|
+
try {
|
|
538
|
+
await fs.writeFile(lock, token, { flag: 'wx', mode: 0o600 });
|
|
539
|
+
held = true;
|
|
540
|
+
}
|
|
541
|
+
catch {
|
|
542
|
+
const st = await fs.stat(lock).catch(() => null);
|
|
543
|
+
if (st && Date.now() - st.mtimeMs > 10_000)
|
|
544
|
+
await fs.rm(lock, { force: true }).catch(() => undefined);
|
|
545
|
+
else
|
|
546
|
+
await new Promise((res) => setTimeout(res, 20));
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
if (!held)
|
|
550
|
+
return;
|
|
551
|
+
try {
|
|
552
|
+
const d = await readJournal();
|
|
553
|
+
fn(d);
|
|
554
|
+
const cut = Date.now() - JOURNAL_MAX_AGE_MS;
|
|
555
|
+
for (const k of Object.keys(d))
|
|
556
|
+
if (!(d[k]?.sentAtMs >= cut))
|
|
557
|
+
delete d[k];
|
|
558
|
+
const tmp = `${p}.${token}.tmp`;
|
|
559
|
+
await fs.writeFile(tmp, JSON.stringify(d), { mode: 0o600 });
|
|
560
|
+
await fs.rename(tmp, p);
|
|
561
|
+
}
|
|
562
|
+
finally {
|
|
563
|
+
if ((await fs.readFile(lock, 'utf8').catch(() => '')) === token)
|
|
564
|
+
await fs.rm(lock, { force: true }).catch(() => undefined);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
catch { /* the outcome is still checked in this process */ }
|
|
568
|
+
});
|
|
569
|
+
jturn = run.catch(() => undefined);
|
|
570
|
+
return run;
|
|
571
|
+
}
|
|
572
|
+
/** Note a write BEFORE it is sent; returns its id (the digest of its bytes). */
|
|
573
|
+
export async function journalAdd(entry) { await journalUpdate((d) => { d[entry.digest] = { ...entry, state: 'sending' }; }); return entry.digest; }
|
|
574
|
+
export async function journalSet(id, fields) { if (id)
|
|
575
|
+
await journalUpdate((d) => { if (d[id])
|
|
576
|
+
Object.assign(d[id], fields); }); }
|
|
577
|
+
export async function journalDone(id) { if (id)
|
|
578
|
+
await journalUpdate((d) => { delete d[id]; }); }
|
|
579
|
+
/** The writes noted in this computer's journal whose outcome is not known yet (younger than a day). Check one with
|
|
580
|
+
* {@link pendingCheck} and a client of its network. */
|
|
581
|
+
export async function pending(maxAgeMs = JOURNAL_MAX_AGE_MS) {
|
|
582
|
+
await jturn;
|
|
583
|
+
const cut = Date.now() - maxAgeMs;
|
|
584
|
+
return Object.values(await readJournal()).filter((e) => e && e.sentAtMs >= cut).sort((a, b) => a.sentAtMs - b.sentAtMs);
|
|
585
|
+
}
|
|
586
|
+
/** Read one journal entry once at a node (`read`, the node it was sent to: entry.rest); a final takes it off. */
|
|
587
|
+
export async function pendingCheck(e, read, chainMs = null) {
|
|
588
|
+
const r = new NodeReads(read);
|
|
589
|
+
const owner = String(e.owner);
|
|
590
|
+
const signed = (s) => {
|
|
591
|
+
if (!s || typeof s !== 'object')
|
|
592
|
+
return null;
|
|
593
|
+
const x = s;
|
|
594
|
+
return { pairId: Number(x.pairId), side: Number(x.side), size: BigInt(String(x.size)), price: x.price === null || x.price === undefined ? null : BigInt(String(x.price)) };
|
|
595
|
+
};
|
|
596
|
+
let action = e.action;
|
|
597
|
+
let judge;
|
|
598
|
+
const recorded = 'agent' in e ? { known: true, agent: e.agent ?? null } : null;
|
|
599
|
+
const who = recorded ? async () => recorded : signerOf(r, owner, e.signer ?? null, e.digest);
|
|
600
|
+
if (action === 'order')
|
|
601
|
+
judge = async () => { const w = await who(); return w.known ? judgeOrder(r, owner, Number(e.nonce), signed(e.signed), { rewound: e.rewound, validUntilS: e.validUntil, sentAtMs: e.sentAtMs, chainMs, agent: w.agent }) : none(); };
|
|
602
|
+
else if (action === 'cancel')
|
|
603
|
+
judge = () => judgeCancel(r, owner, BigInt(String(e.orderId)));
|
|
604
|
+
else if (action === 'cancel_all')
|
|
605
|
+
judge = () => judgeCancelAll(r, owner, e.before ?? null, Number(e.pairId ?? 0));
|
|
606
|
+
else if (action === 'revoke')
|
|
607
|
+
judge = () => judgeRevoke(r, owner, String(e.agent));
|
|
608
|
+
else if (action === 'stop')
|
|
609
|
+
judge = () => judgeStop(r, owner, e.validUntil ?? null, chainMs, e.nonce ?? null);
|
|
610
|
+
else if (action === 'batch') {
|
|
611
|
+
const places = (e.places ?? []).map(([n, s]) => [Number(n), signed(s)]);
|
|
612
|
+
const cancels = (e.cancels ?? []).map(String);
|
|
613
|
+
const cancelNonces = (e.cancelNonces ?? []).map(Number);
|
|
614
|
+
action = places.length ? 'order' : 'cancel_all';
|
|
615
|
+
judge = async () => { const w = places.length ? await who() : { known: true, agent: null }; return w.known ? judgeBatch(r, owner, places, cancels, e.rewound ?? null, cancelNonces, w.agent) : none(); };
|
|
616
|
+
}
|
|
617
|
+
else
|
|
618
|
+
throw new Error(`unknown action ${String(e.action)}`);
|
|
619
|
+
const pw = new PendingWrite(action, judge, { meta: { nonce: e.nonce ?? null, orderId: e.orderId ?? null, agent: e.agent ?? null, digest: e.digest, attempts: e.attempts ?? 1 }, journalId: e.digest, startedMs: outcomeClock.now() - Math.max(0, Date.now() - e.sentAtMs) });
|
|
620
|
+
return pw.check();
|
|
621
|
+
}
|
|
622
|
+
/** A JSON value with bigint fields as strings (for the journal). */
|
|
623
|
+
export const plain = (v) => JSON.parse(JSON.stringify(v, (_, x) => (typeof x === 'bigint' ? x.toString() : x)));
|