@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.
@@ -8,6 +8,7 @@ import { connectNetwork, nodeIdentity, refreshRecord, signingPin } from './netwo
8
8
  import { PinMismatch, pinDifferences, pinRefusal } from './pins.js';
9
9
  import { NonceAllocator, nonceAllocator } from './nonce.js';
10
10
  import { ChainClock, DeliveryUnknown, sendSame } from './resend.js';
11
+ import { NodeReads, PendingWrite, READ_TIMEOUT_MS, SETTLE_MS, bodyDigest, clause, journalAdd, journalDone, journalSet, judgeBatch, judgeCancel, judgeCancelAll, judgeOrder, judgeRevoke, judgeStop, orderIds, signerOf, storedSessionNonce, plain as plainJson, resendRule, say, settle, } from './outcome.js';
11
12
  import { BATCH_MAX, batchBody, cancelAllBody, cancelOrderBody, modifyBody, placeOrderBody, placeOrderValue, readAnswer, scheduleCancelBody, setTpSlBody, } from './orders.js';
12
13
  import { readAgentRefusals, refusalMeanings, readEquity, readOpenOrders, readPositions } from './reads.js';
13
14
  import { rs64, signOp } from './sign.js';
@@ -26,6 +27,8 @@ async function outcome(r, shows, waitMs, notShown) {
26
27
  return { applied: null, unknown: true, status: r.status, answer: r.body, detail: `${notShown} yet; it may still apply: read the account again before sending it anew` };
27
28
  }
28
29
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
30
+ /** Seconds ahead a stop's deadline is set (the chain takes at most 300). */
31
+ export const STOP_ALL_AHEAD_S = 120;
29
32
  /** Read the chain until `fn` is true or `ms` runs out. A failed read counts as "not yet". */
30
33
  async function waitFor(fn, ms, stepMs = 1000) {
31
34
  const end = Date.now() + ms;
@@ -72,7 +75,7 @@ export class Vordium {
72
75
  const timeoutMs = opts.timeoutMs ?? 15000;
73
76
  const net = await connectNetwork(opts.network ?? 'testnet', {
74
77
  transport, timeoutMs, onPinProblem: opts.onPinProblem,
75
- releaseKeys: opts.releaseKeys, releaseRecordStore: opts.releaseRecordStore, releaseRecordNow: opts.releaseRecordNow,
78
+ releaseKeys: opts.releaseKeys, releaseRecordStore: opts.releaseRecordStore, releaseRecordNow: opts.releaseRecordNow, releaseRecordMinSequence: opts.releaseRecordMinSequence,
76
79
  });
77
80
  return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000, opts.chainClock ?? opts.transport === undefined);
78
81
  }
@@ -108,6 +111,18 @@ export class Vordium {
108
111
  throw new VordiumError('read_failed', `The read ${path} answered HTTP ${r.status}.`);
109
112
  return r.body;
110
113
  }
114
+ /** One read while an outcome is checked: {status, body} with its own time limit; status null when it failed. */
115
+ async read(path) {
116
+ try {
117
+ const r = await this.transport.get(this.network.api + path, Math.min(this.timeoutMs, READ_TIMEOUT_MS));
118
+ return { status: r.status, body: r.body };
119
+ }
120
+ catch {
121
+ return { status: null, body: null };
122
+ }
123
+ }
124
+ /** Reads of this client's node for an outcome check (never an explorer). */
125
+ nodeReads() { return new NodeReads((p) => this.read(p)); }
111
126
  async post(path, body) {
112
127
  return this.transport.post(this.network.api + path, body, this.timeoutMs);
113
128
  }
@@ -317,10 +332,17 @@ export class Account {
317
332
  * Sign and submit one order (Market or Limit). The answer is a submission; the order is on the book when
318
333
  * {@link Vordium.openOrders} lists its `clientNonce`, or filled when the account's fills show it. Use
319
334
  * {@link waitForOrder} to read it back.
335
+ *
336
+ * The order is signed ONCE; a lost answer or a busy gateway sends the same signed body again (never a new nonce). When
337
+ * an earlier copy may have arrived and no 2xx came back, the outcome is read from the node (the account's orders by
338
+ * this client nonce AND what was signed, then its records: placed, closed, refused) for up to `settleMs` (default 30 s;
339
+ * 0 returns at once): the answer carries `outcome` (`state` pending_checking, applied, refused, not_applied or
340
+ * still_unknown, with `text` and `next`) and, while it is not final, `pending` (`check()`, `wait()`). It is never
341
+ * signed again. When no copy left this machine, {@link DeliveryUnknown} is thrown (`neverSent`).
320
342
  */
321
343
  async placeOrder(o) {
322
344
  const signer = this.orderSigner();
323
- const { builder: wanted, worstPrice, ...plain } = o;
345
+ const { builder: wanted, worstPrice, settleMs, ...plain } = o;
324
346
  if (worstPrice != null && (wanted == null || o.orderType !== 'Market'))
325
347
  throw new InvalidRequest('worstPrice applies to a market order that names a builder.');
326
348
  placeOrderValue({ ...plain, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
@@ -329,10 +351,12 @@ export class Account {
329
351
  const clientNonce = o.clientNonce ?? (await this.fresh('orders'));
330
352
  const v = placeOrderValue({ ...plain, owner: this.owner, clientNonce }, spec);
331
353
  let body;
354
+ let validUntilS = null;
332
355
  if (ob) {
333
356
  // a buy's cap rounds down onto the price step and a sell's floor up: never worse than the caller gave
334
357
  const worst8 = worstPrice == null ? 0n : price8OnTick(worstPrice, spec, o.side, true);
335
358
  const v3 = placeOrderV3Value(v, deadline(null, await this.client.nowS()), ob, undefined, worst8);
359
+ validUntilS = Number(v3.validUntil);
336
360
  body = placeOrderV3Body(v3, await this.sign(signer, 'PlaceOrderV3', v3));
337
361
  }
338
362
  else {
@@ -349,26 +373,52 @@ export class Account {
349
373
  const ts = [f.timestampMs, f.timestamp_ms, f.ts_ms].find((x) => typeof x === 'number');
350
374
  return ts !== undefined && ts > rewound ? f : null;
351
375
  };
376
+ const wire = JSON.stringify(body);
377
+ const digest = bodyDigest(wire);
378
+ const sentAtMs = Date.now();
379
+ const signerAddr = getAddress(await signer.getAddress());
380
+ const jid = await journalAdd({ action: 'order', owner: this.owner, rest: this.client.network.api, nonce: clientNonce, signer: signerAddr, signed: plainJson(signed), rewound, validUntil: validUntilS, sentAtMs, digest });
381
+ // an earlier copy may have arrived and no 2xx came back (a lost answer, the nonce code - which also means "outside
382
+ // the window" or "used by another signer" -, a refusal of a later copy, a 5xx): the node's reads decide, and the
383
+ // order is ours only when it carries what was signed
384
+ const lost = async (attempts, answer) => {
385
+ const reads = this.client.nodeReads();
386
+ const who = signerOf(reads, this.owner, signerAddr, jid); // an agent of the account or not, once it answers
387
+ const pw = new PendingWrite('order', async () => {
388
+ const w = await who();
389
+ if (!w.known)
390
+ return { state: null, fill: {}, read: null };
391
+ return judgeOrder(reads, this.owner, clientNonce, signed, { rewound, validUntilS, sentAtMs, chainMs: () => this.client.chainTimeMs(), agent: w.agent });
392
+ }, { meta: { nonce: clientNonce, digest, attempts }, journalId: jid });
393
+ await journalSet(jid, { state: 'pending_checking', attempts });
394
+ const oc = await settle(pw, settleMs ?? SETTLE_MS);
395
+ const found = oc.state === 'applied' ? ours(pw.found) : null;
396
+ const base = { clientNonce, attempts, answer, found, outcome: oc, pending: oc.final ? null : pw, ...withBuilder };
397
+ if (oc.state === 'applied')
398
+ return { submitted: true, status: 0, refusal: null, actions: [], alreadyReceived: true, unknown: false, ...base };
399
+ if (oc.state === 'refused' || oc.state === 'not_applied') {
400
+ return { submitted: false, status: 0, refusal: { code: oc.state === 'refused' ? oc.refusal?.code ?? 'refused' : 'not_applied', message: oc.text, detail: oc.next, retryAfter: null }, actions: [], alreadyReceived: false, unknown: false, ...base };
401
+ }
402
+ return { ...unknownResult(attempts, oc.text, answer), ...base, alreadyReceived: false };
403
+ };
352
404
  let r;
353
405
  try {
354
- r = await this.postSame('/order/place', JSON.stringify(body), clientNonce);
406
+ r = await this.postSame('/order/place', wire, clientNonce);
355
407
  }
356
408
  catch (e) {
357
- if (!(e instanceof DeliveryUnknown))
409
+ if (!(e instanceof DeliveryUnknown)) {
410
+ await journalDone(jid);
358
411
  throw e;
359
- const found = ours(await this.orderByClientNonce(clientNonce, signed));
360
- if (!found)
412
+ }
413
+ if (e.neverSent) {
414
+ await journalDone(jid);
361
415
  throw e;
362
- return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
363
- }
364
- if (r.needsReadBack) {
365
- // the network's nonce code means "used" (perhaps by our earlier copy), "outside the window", or "used by another
366
- // signer": it is ours only when the order the network lists carries what was signed
367
- const found = ours(await this.orderByClientNonce(clientNonce, signed));
368
- if (found)
369
- return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
370
- return { ...unknownResult(r.attempts, `An earlier copy may have arrived (its answer was lost), the network answered ${r.status}, and it does not list this order (yet). Read the account's orders before sending a new one.`, r.body), clientNonce, alreadyReceived: false, found: null, ...withBuilder };
416
+ }
417
+ return lost(e.attempts, null);
371
418
  }
419
+ if (r.needsReadBack)
420
+ return lost(r.attempts, r.body);
421
+ await journalDone(jid);
372
422
  const s = readAnswer(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
373
423
  return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false, ...withBuilder };
374
424
  }
@@ -415,45 +465,53 @@ export class Account {
415
465
  }, ms);
416
466
  return state;
417
467
  }
418
- async cancelOrder(orderId) {
468
+ /**
469
+ * Cancel one order. A cancel carries no nonce and the network cancels an order once, so a lost answer sends the SAME
470
+ * signed body again. When an earlier copy may have arrived and no 2xx came back, the outcome is read from the node
471
+ * (the order no longer listed, and its record: cancelled, or filled first) for up to `settleMs` (default 30 s; 0
472
+ * returns at once): `done` / `filled` / `unknown`, with `outcome` and, while it is not final, `pending` (whose
473
+ * `resendSame()` sends the same signed cancel again).
474
+ */
475
+ async cancelOrder(orderId, opts = {}) {
419
476
  const signer = this.orderSigner();
420
477
  const id = uint(orderId, U64, 'orderId');
421
478
  const sig = await this.sign(signer, 'CancelOrder', { owner: this.owner, orderId: id });
422
- // a cancel carries no nonce; cancelling an order twice cancels it once, so a lost answer sends the same body again.
479
+ const wire = JSON.stringify(cancelOrderBody(this.owner, getAddress(await signer.getAddress()), id, rs64(sig)));
480
+ const digest = bodyDigest(wire);
481
+ const send = () => this.client.post('/order/cancel', wire);
482
+ const jid = await journalAdd({ action: 'cancel', owner: this.owner, rest: this.client.network.api, orderId: id.toString(), sentAtMs: Date.now(), digest });
423
483
  // When an earlier copy may have arrived, the answer to a later one ("not found", a 5xx) is about that later copy:
424
- // the account's resting orders decide.
425
- const readBack = async (answer, attempts) => {
426
- let rows = null;
427
- try {
428
- rows = await this.client.openOrders(this.owner);
429
- }
430
- catch {
431
- rows = null;
432
- }
433
- if (!rows || rows.some((o) => BigInt(o.orderId) === id)) {
434
- return unknownResult(attempts, `${rows ? 'The order is still resting' : 'The orders could not be read'} after an earlier copy of the cancel may have arrived; read the account's orders, then cancel again if it is still resting.`, answer);
435
- }
436
- // not resting: the order's own records say whether the cancel or a fill closed it
437
- const how = cancelOutcome(await this.client.orderRecords(this.owner).catch(() => []), id);
438
- if (how === 'cancelled')
439
- return { submitted: true, status: 0, refusal: null, actions: [], answer, done: true, attempts };
440
- if (how === 'filled')
441
- return { submitted: false, status: 0, refusal: { code: 'order_filled', message: 'The order filled before the cancel: check your position.', detail: '', retryAfter: null }, actions: [], answer, filled: true, attempts };
442
- return unknownResult(attempts, 'The order no longer rests: it closed (filled or cancelled). Check the fills and the position.', answer);
484
+ // the node's reads decide.
485
+ const lost = async (answer, attempts) => {
486
+ const reads = this.client.nodeReads();
487
+ const pw = new PendingWrite('cancel', () => judgeCancel(reads, this.owner, id), { meta: { orderId: id.toString(), digest, attempts }, resend: send, journalId: jid });
488
+ await journalSet(jid, { state: 'pending_checking', attempts });
489
+ const oc = await settle(pw, opts.settleMs ?? SETTLE_MS);
490
+ const more = { outcome: oc, pending: oc.final ? null : pw, attempts };
491
+ if (oc.state === 'applied')
492
+ return { submitted: true, status: 0, refusal: null, actions: [], answer, done: true, ...more };
493
+ if (oc.state === 'applied_other')
494
+ return { submitted: false, status: 0, refusal: { code: 'order_filled', message: oc.text, detail: oc.next, retryAfter: null }, actions: [], answer, filled: true, ...more };
495
+ return { ...unknownResult(attempts, oc.text, answer), ...more };
443
496
  };
444
497
  let r;
445
498
  try {
446
- r = await this.postSame('/order/cancel', JSON.stringify(cancelOrderBody(this.owner, getAddress(await signer.getAddress()), id, rs64(sig))));
499
+ r = await sendSame(send);
447
500
  }
448
501
  catch (e) {
449
- if (!(e instanceof DeliveryUnknown))
502
+ if (!(e instanceof DeliveryUnknown)) {
503
+ await journalDone(jid);
450
504
  throw e;
451
- if (e.neverSent)
505
+ }
506
+ if (e.neverSent) {
507
+ await journalDone(jid);
452
508
  return { submitted: false, status: 0, refusal: { code: 'not_sent', message: e.message, detail: '', retryAfter: null }, actions: [], answer: null, attempts: e.attempts };
453
- return readBack(null, e.attempts);
509
+ }
510
+ return lost(null, e.attempts);
454
511
  }
455
512
  if (r.needsReadBack)
456
- return readBack(r.body, r.attempts);
513
+ return lost(r.body, r.attempts);
514
+ await journalDone(jid);
457
515
  return readAnswer(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
458
516
  }
459
517
  /** Take-profit / stop-loss on an open position (8-decimal prices; 0 leaves a leg unset). */
@@ -466,7 +524,11 @@ export class Account {
466
524
  const sig = await this.sign(signer, 'SetTpSl', value);
467
525
  return this.send('/tpsl/set', setTpSlBody(this.owner, getAddress(await signer.getAddress()), value.pairId, value.positionId, value.takeProfit8dec, value.stopLoss8dec, sig));
468
526
  }
469
- /** Up to the published maximum of place / cancel actions in one signed batch. Cancels apply first. */
527
+ /**
528
+ * Up to the published maximum of place / cancel actions in one signed batch. Cancels apply first. A batch is never
529
+ * sent again after a lost answer; its outcome is then read from the node (each place by its client nonce, each
530
+ * cancelled order no longer listed) for up to `settleMs` (default 30 s; 0 returns at once).
531
+ */
470
532
  async batch(actions, opts = {}) {
471
533
  const max = opts.maxActions ?? BATCH_MAX;
472
534
  if (actions.length < 1 || actions.length > max)
@@ -474,7 +536,44 @@ export class Account {
474
536
  actions = await this.onSteps(actions);
475
537
  const nonce = opts.nonce ?? (await this.fresh('orders'));
476
538
  const sig = await this.sign(this.orderSigner(), 'BatchOrders', { owner: this.owner, nonce, actions });
477
- return { ...(await this.send('/order/batch-signed', batchBody(this.owner, nonce, actions, sig), nonce)), nonce };
539
+ const wire = JSON.stringify(batchBody(this.owner, nonce, actions, sig));
540
+ const places = actions.filter((a) => a.kind === 0).map((a) => [Number(a.clientNonce), { pairId: a.pairId, side: a.side, size: a.size, price: a.price ? a.price : null }]);
541
+ const cancels = actions.filter((a) => a.kind === 1).map((a) => String(a.orderId));
542
+ const cancelNonces = actions.filter((a) => a.kind === 2).map((a) => Number(a.clientNonce));
543
+ const digest = bodyDigest(wire);
544
+ const signerAddr = getAddress(await this.orderSigner().getAddress());
545
+ const jid = await journalAdd({ action: 'batch', owner: this.owner, rest: this.client.network.api, nonce, signer: signerAddr, places: plainJson(places), cancels, cancelNonces, sentAtMs: Date.now(), digest });
546
+ const reads = this.client.nodeReads();
547
+ const who = signerOf(reads, this.owner, places.length ? signerAddr : null, jid);
548
+ const judge = async () => {
549
+ const w = await who();
550
+ if (!w.known)
551
+ return { state: null, fill: {}, read: null };
552
+ return judgeBatch(reads, this.owner, places, cancels, null, cancelNonces, w.agent);
553
+ };
554
+ const action = places.length ? 'order' : 'cancel_all';
555
+ let sent;
556
+ try {
557
+ sent = await this.send('/order/batch-signed', wire, nonce);
558
+ }
559
+ catch (e) {
560
+ await journalDone(jid);
561
+ throw e;
562
+ }
563
+ return { ...(await this.checked(sent, action, judge, opts.settleMs, { nonce, digest }, jid)), nonce };
564
+ }
565
+ /** A write the network is not known to apply once, whose answer was lost: never sent again; the node's reads decide. */
566
+ async checked(s, action, judge, settleMs, meta, jid) {
567
+ if (!s.unknown) {
568
+ await journalDone(jid);
569
+ return s;
570
+ }
571
+ const pw = new PendingWrite(action, judge, { meta: { ...meta, attempts: s.attempts }, journalId: jid });
572
+ await journalSet(jid, { state: 'pending_checking', attempts: s.attempts });
573
+ const oc = await settle(pw, settleMs ?? SETTLE_MS);
574
+ if (oc.applied === true)
575
+ return { ...s, submitted: true, unknown: false, refusal: null, outcome: oc, pending: null }; // the node shows it applied
576
+ return { ...s, refusal: { code: s.refusal?.code ?? 'delivery_unknown', message: oc.text, detail: oc.next, retryAfter: null }, outcome: oc, pending: oc.final ? null : pw };
478
577
  }
479
578
  /**
480
579
  * The batch as it will be signed: every place action's price and size on its market's tick and lot (one rules read
@@ -494,12 +593,30 @@ export class Account {
494
593
  return { ...a, price, size };
495
594
  });
496
595
  }
497
- /** Cancel every open order on `pairId` (0 = every market). */
498
- async cancelAll(pairId = 0) {
596
+ /**
597
+ * Cancel every open order on `pairId` (0 = every market). The open orders are read first. A cancel-all is never sent
598
+ * again after a lost answer (a late copy could cancel orders placed after the first applied); its outcome is then read
599
+ * from the node — none of the orders listed before is still listed — for up to `settleMs` (default 30 s; 0 returns
600
+ * at once): `outcome` and, while it is not final, `pending`.
601
+ */
602
+ async cancelAll(pairId = 0, opts = {}) {
499
603
  const p = safeNumber(uint(pairId, U32, 'pairId'), 'pairId');
604
+ const before = orderIds((await this.client.read(`/orders/${this.owner}`)).body, p);
500
605
  const nonce = await this.fresh('orders');
501
606
  const sig = await this.sign(this.orderSigner(), 'CancelAllOrders', { owner: this.owner, pairId: p, nonce });
502
- return this.send('/order/cancel-all', cancelAllBody(this.owner, p, nonce, sig), nonce);
607
+ const wire = JSON.stringify(cancelAllBody(this.owner, p, nonce, sig));
608
+ const digest = bodyDigest(wire);
609
+ const jid = await journalAdd({ action: 'cancel_all', owner: this.owner, rest: this.client.network.api, nonce, pairId: p, before, sentAtMs: Date.now(), digest });
610
+ const reads = this.client.nodeReads();
611
+ let sent;
612
+ try {
613
+ sent = await this.send('/order/cancel-all', wire, nonce);
614
+ }
615
+ catch (e) {
616
+ await journalDone(jid);
617
+ throw e;
618
+ }
619
+ return this.checked(sent, 'cancel_all', () => judgeCancelAll(reads, this.owner, before, p), opts.settleMs, { nonce, digest }, jid);
503
620
  }
504
621
  /**
505
622
  * Cancel-and-replace at a new price and size (a new order id, no time priority). The new price and size go onto the
@@ -752,11 +869,95 @@ export class Account {
752
869
  const r = await this.submitAgentOp(signer, op, value, (x) => !!x && x.name === value.name, value.agent, waitMs);
753
870
  return r.applied ? r : { ...r, detail: 'the chain does not show the new name (a rename within the wait after the last naming is ignored)' };
754
871
  }
755
- async revokeAgent(agent, waitMs = 30000) {
872
+ /**
873
+ * Revoke an agent (RevokeAgent, owner key, its nonce above the chain's mark for that agent). An agent the chain already
874
+ * lists as revoked is not signed for. A lost answer sends the same bytes again (the network applies it once). It is
875
+ * applied only when the agent's committed record reads `revoked`: even after a 2xx the state is `pending_checking`
876
+ * until then. Reads for up to `waitMs` (default 30 s; 0 returns at once); `outcome` and, while not final, `pending`.
877
+ */
878
+ async revokeAgent(agent, waitMs = SETTLE_MS) {
756
879
  const signer = this.needOwner('Revoking an agent');
757
880
  const op = 'RevokeAgent';
758
- const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), nonce: await this.fresh('account') };
759
- return this.submitAgentOp(signer, op, value, (rec) => !!rec && rec.status === 'revoked', value.agent, waitMs);
881
+ const a = this.addr(agent, op);
882
+ const reads = this.client.nodeReads();
883
+ const held = (await reads.ok(`/agents/${this.owner}/${a}`));
884
+ if (held && String(held.status ?? '').toLowerCase() === 'revoked') {
885
+ const v = await judgeRevoke(reads, this.owner, a);
886
+ const pw = new PendingWrite('revoke', async () => v, { meta: { agent: a, attempts: 0 } });
887
+ const oc = await pw.check();
888
+ return { applied: true, status: 0, answer: null, detail: 'the agent is already revoked', outcome: oc, pending: null };
889
+ }
890
+ const sg = (await reads.ok(`/signers/${this.owner}`));
891
+ const row = (Array.isArray(sg?.agents) ? sg.agents : []).find((x) => String(x?.key ?? '').toLowerCase() === a.toLowerCase());
892
+ const mark = storedSessionNonce({ last_nonce: row?.last_nonce }) ?? 0;
893
+ const value = { owner: this.addr(this.owner, op), agent: a, nonce: await this.fresh('account', undefined, mark + 1) };
894
+ const sig = await this.sign(signer, op, value);
895
+ const wire = JSON.stringify(submitBody(op, value, sig));
896
+ return this.ownerChecked('revoke', '/submit', wire, () => judgeRevoke(reads, this.owner, a), waitMs, { nonce: value.nonce, agent: a }, { nonce: value.nonce, agent: a });
897
+ }
898
+ /** An owner write whose effect the node's reads decide: same bytes on every copy; pending until the read shows it. */
899
+ async ownerChecked(action, path, wire, judge, settleMs, meta, entry) {
900
+ const digest = bodyDigest(wire);
901
+ const jid = await journalAdd({ ...entry, action, owner: this.owner, rest: this.client.network.api, sentAtMs: Date.now(), digest });
902
+ let r;
903
+ try {
904
+ r = await this.postForResult(path, wire);
905
+ }
906
+ catch (e) {
907
+ await journalDone(jid);
908
+ throw e;
909
+ }
910
+ if (!r.proceed) {
911
+ await journalDone(jid);
912
+ if (r.body?.status === 'not_sent')
913
+ return { applied: false, status: r.status, answer: r.body, detail: 'the network could not be reached: nothing was sent', outcome: null, pending: null };
914
+ const a = (r.body && typeof r.body === 'object' ? r.body : {});
915
+ const code = String(a.code ?? a.reason ?? (r.status ? `http_${r.status}` : 'refused'));
916
+ const meaning = String(a.meaning ?? a.error ?? a.reason ?? 'the network refused it');
917
+ const w = say(action, 'refused', { meaning: clause(meaning), action: '' });
918
+ const oc = { action, state: 'refused', text: w.text, next: w.next, applied: false, final: true, refusal: { code, meaning, action: null },
919
+ read: { source: 'node', route: null, height: null, atMs: Date.now() }, resend: resendRule(action, 'refused'), nonce: meta.nonce, orderId: null, agent: meta.agent ?? null, digest, attempts: 1, counts: {} };
920
+ return { applied: false, status: r.status, answer: r.body, detail: w.text, outcome: oc, pending: null };
921
+ }
922
+ const pw = new PendingWrite(action, judge, { meta: { ...meta, digest, attempts: 1 }, resend: () => this.client.post(path, wire), journalId: jid });
923
+ await journalSet(jid, { state: 'pending_checking' });
924
+ const oc = await settle(pw, settleMs);
925
+ return { applied: oc.applied, unknown: oc.applied === null || undefined, status: r.status, answer: r.body, detail: oc.text, outcome: oc, pending: oc.final ? null : pw };
926
+ }
927
+ /** Whether this network takes StopAllSigners, asked without signing: an empty body is refused as unreadable by a
928
+ * network that has the route; a missing route (404 / 405) or `not_in_force` means it does not take it yet. Null when
929
+ * the network did not answer (not known). */
930
+ async takesStopAll() {
931
+ try {
932
+ const r = await this.client.post('/signers/stop-all', '{}');
933
+ return r.status !== 404 && r.status !== 405 && r.body?.code !== 'not_in_force';
934
+ }
935
+ catch {
936
+ return null;
937
+ }
938
+ }
939
+ /**
940
+ * Stop, on the chain, this account's trading key and every one of its agents with ONE owner signature (StopAllSigners,
941
+ * VordexSession domain, a deadline 120 s after block time — this computer's clock when block time cannot be read —, the
942
+ * session nonce above the stored one). It does not cancel resting orders. Nothing is signed where the network says it
943
+ * does not take it (`applied` false, `outcome` null). A lost
944
+ * answer sends the same bytes again. Applied only when the node reads no trading key and no live agent
945
+ * (`applied_other` when orders the wallet placed itself stay open); not_applied once its deadline passed with a key or
946
+ * an agent still live. Reads for up to `settleMs` (default 30 s; 0 returns at once).
947
+ */
948
+ async stopAll(settleMs = SETTLE_MS) {
949
+ const signer = this.needOwner('Stopping every signer');
950
+ if ((await this.takesStopAll()) === false)
951
+ return { applied: false, status: 0, answer: null, detail: 'this network does not take Stop all signers yet: nothing was signed', outcome: null, pending: null };
952
+ const reads = this.client.nodeReads();
953
+ // above the session nonce the chain stored (the session read names it, with or without a live session)
954
+ const stored = storedSessionNonce((await reads.get(`/session/get?owner=${this.owner}`)).body) ?? 0;
955
+ const nonce = await this.fresh('account', undefined, stored + 1);
956
+ const validUntil = (await this.client.nowS()) + STOP_ALL_AHEAD_S;
957
+ const value = { owner: this.owner, nonce, validUntil };
958
+ const sig = await this.sign(signer, 'StopAllSigners', value);
959
+ const wire = JSON.stringify({ owner: this.owner, nonce, validUntil, signature: sig });
960
+ return this.ownerChecked('stop', '/signers/stop-all', wire, () => judgeStop(reads, this.owner, validUntil, () => this.client.chainTimeMs(), nonce), settleMs, { nonce }, { nonce, validUntil });
760
961
  }
761
962
  /**
762
963
  * Set an agent's policy. Refused before signing when the chain would refuse it at apply (it does so silently). The
@@ -16,4 +16,6 @@ export * from './agents.js';
16
16
  export * from './reads.js';
17
17
  export * from './feeds.js';
18
18
  export * from './builder.js';
19
- export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome, type Result, type ConnectOptions, type SignedOrder } from './client.js';
19
+ export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome, STOP_ALL_AHEAD_S, type Result, type Checked, type ConnectOptions, type SignedOrder } from './client.js';
20
+ export * from './outcome.js';
21
+ export { OUTCOME_WORDS } from './outcomeWords.js';
package/dist/esm/index.js CHANGED
@@ -16,4 +16,6 @@ export * from './agents.js';
16
16
  export * from './reads.js';
17
17
  export * from './feeds.js';
18
18
  export * from './builder.js';
19
- export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome } from './client.js';
19
+ export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome, STOP_ALL_AHEAD_S } from './client.js';
20
+ export * from './outcome.js';
21
+ export { OUTCOME_WORDS } from './outcomeWords.js';
@@ -42,6 +42,8 @@ export interface Network extends NetworkPreset {
42
42
  record: VerifiedRecord | null;
43
43
  /** Why the served release record cannot be used; nothing is signed while it is set. */
44
44
  recordProblem: string | null;
45
+ /** The code of `recordProblem` (`expired`, `rollback`, `not_served`, `unsigned`, `bad_signature`, `not_listed`, …). */
46
+ recordProblemCode?: string | null;
45
47
  /** Where the record is read again, and the record as last read: signing uses the record as it is now (see
46
48
  * {@link refreshRecord}). Absent for a network with a pin of its own. */
47
49
  recordLive?: RecordLive;
@@ -55,6 +57,8 @@ export interface RecordLive {
55
57
  read: ReadRecordOptions;
56
58
  record: VerifiedRecord | null;
57
59
  problem: string | null;
60
+ /** The code of `problem`. */
61
+ code?: string | null;
58
62
  /** Date.now() when it was read. */
59
63
  at: number;
60
64
  }
@@ -97,6 +101,8 @@ export interface ConnectNetworkOptions {
97
101
  releaseRecordStore?: NonceStore;
98
102
  /** Tests only: this computer's clock in milliseconds. */
99
103
  releaseRecordNow?: () => number;
104
+ /** Tests only: the lowest record sequence accepted per chain id, instead of `MIN_RECORD_SEQUENCE`. */
105
+ releaseRecordMinSequence?: Readonly<Record<number, number>>;
100
106
  }
101
107
  /**
102
108
  * Read and check a network. Refuses (NetworkMismatch, nothing signed) unless the spec, the node's `/status` and
@@ -42,36 +42,51 @@ export async function refreshRecord(net, opts = {}) {
42
42
  try {
43
43
  l.record = await readRecord(l.chainId, l.urls, l.keys, l.read);
44
44
  l.problem = null;
45
+ l.code = null;
45
46
  }
46
47
  catch (e) {
47
48
  if (!(e instanceof RecordRefused))
48
49
  throw e;
49
50
  l.record = null;
50
- l.problem = `${e.message} Nothing was signed.`;
51
+ l.problem = withNothing(e.message);
52
+ l.code = e.code;
51
53
  }
52
- if (!l.record && !l.problem && l.byChain)
54
+ if (!l.record && !l.problem && l.byChain) {
53
55
  l.problem = noRecordText(l.chainId);
56
+ l.code = 'not_listed';
57
+ }
54
58
  l.at = Date.now();
55
59
  }
60
+ /** A record refusal's sentence, saying once that nothing was signed. */
61
+ const withNothing = (m) => (/Nothing (is|was) signed/.test(m) ? m : `${m} Nothing was signed.`);
62
+ /** The error for a record problem: a `PinMismatch` (or `UnpinnedNetwork` for a network named only by its chain id) whose
63
+ * `recordCode` names why. */
64
+ function recordError(message, code, unpinned) {
65
+ return Object.assign(unpinned ? new UnpinnedNetwork(message) : new PinMismatch(message), { recordCode: code ?? null });
66
+ }
56
67
  const noRecordText = (chainId) => `Refusing to sign: no signed release record lists chain ${chainId}, and a network named only by its chain id needs one. Nothing was signed.`;
57
68
  /** The pin from the network's release record as last read (throws when it cannot be used), or null when no record is
58
69
  * served and none was used for the network (then its pin applies). */
59
70
  function recordSigningPin(net, l) {
60
71
  const now = l.read.now ?? Date.now;
61
- let problem = l.problem;
62
- if (!problem && l.record && now() / 1000 > l.record.record.validUntil)
63
- problem = `The signed release record expired; it is read again before the next signature. Nothing was signed.`;
64
- if (!problem && !l.record && net.record)
72
+ let problem = l.problem, code = l.code ?? null;
73
+ if (!problem && l.record && now() / 1000 > l.record.record.validUntil) {
74
+ problem = "The signed release record expired; it is read again before the next signature. Nothing was signed. Try again later; if this persists, check this computer's clock.";
75
+ code = 'expired';
76
+ }
77
+ if (!problem && !l.record && net.record) {
65
78
  problem = 'Refusing to sign: the signed release record this network was checked against is not served now. Nothing was signed.';
79
+ code = 'not_served';
80
+ }
66
81
  if (problem)
67
- throw l.byChain ? new UnpinnedNetwork(problem) : new PinMismatch(problem);
82
+ throw recordError(problem, code, l.byChain);
68
83
  let pin;
69
84
  if (!l.record) {
70
85
  if (!net.recordProblem)
71
86
  return null;
72
87
  const named = presetPinOrNull({ ...net, pin: undefined });
73
88
  if (!named)
74
- throw new UnpinnedNetwork(net.recordProblem);
89
+ throw recordError(net.recordProblem, net.recordProblemCode, true);
75
90
  pin = named;
76
91
  }
77
92
  else {
@@ -119,7 +134,7 @@ export function signingPin(net) {
119
134
  return live;
120
135
  }
121
136
  if (net.recordProblem)
122
- throw net.record || presetPinOrNull(net) ? new PinMismatch(net.recordProblem) : new UnpinnedNetwork(net.recordProblem);
137
+ throw recordError(net.recordProblem, net.recordProblemCode, !(net.record || presetPinOrNull(net)));
123
138
  const pin = net.record && net.pin ? net.pin : presetPin(net);
124
139
  if (net.pinProblem)
125
140
  throw pin ? new PinMismatch(net.pinProblem) : new UnpinnedNetwork(net.pinProblem);
@@ -208,12 +223,13 @@ export async function connectNetwork(network = 'testnet', opts = {}) {
208
223
  const recordChain = p.recordChainId ?? (named ? named.chainId : null);
209
224
  let record = null;
210
225
  let recordProblem = null;
226
+ let recordProblemCode = null;
211
227
  let recordLive;
212
228
  if (recordChain !== null) {
213
229
  const urls = p.releaseRecord ? [p.releaseRecord]
214
230
  : p.recordChainId !== undefined ? Object.values(RELEASE_RECORD_URLS).flat() // a chain only the record names: every address
215
231
  : RELEASE_RECORD_URLS[p.name] ?? [];
216
- const read = { transport: t, timeoutMs: ms, store: opts.releaseRecordStore, now: opts.releaseRecordNow };
232
+ const read = { transport: t, timeoutMs: ms, store: opts.releaseRecordStore, now: opts.releaseRecordNow, minSequence: opts.releaseRecordMinSequence };
217
233
  try {
218
234
  const keys = pinnedKeys(opts.releaseKeys);
219
235
  recordLive = { chainId: recordChain, urls, keys, byChain: p.recordChainId !== undefined, read, record: null, problem: null, at: Date.now() };
@@ -222,12 +238,15 @@ export async function connectNetwork(network = 'testnet', opts = {}) {
222
238
  catch (e) {
223
239
  if (!(e instanceof RecordRefused))
224
240
  throw e;
225
- recordProblem = `${e.message} Nothing was signed.`;
241
+ recordProblem = withNothing(e.message);
242
+ recordProblemCode = e.code;
226
243
  }
227
- if (!record && !recordProblem && p.recordChainId !== undefined)
244
+ if (!record && !recordProblem && p.recordChainId !== undefined) {
228
245
  recordProblem = noRecordText(p.recordChainId);
246
+ recordProblemCode = 'not_listed';
247
+ }
229
248
  if (recordLive)
230
- Object.assign(recordLive, { record, problem: recordProblem, at: Date.now() });
249
+ Object.assign(recordLive, { record, problem: recordProblem, code: recordProblemCode, at: Date.now() });
231
250
  }
232
251
  const pin = record ? Object.freeze({ ...(p.name ? { name: p.name } : {}), chainId: recordChain, genesis: record.entry.genesis }) : hardPin;
233
252
  const sr = await t.get(p.spec, ms);
@@ -267,8 +286,11 @@ export async function connectNetwork(network = 'testnet', opts = {}) {
267
286
  }
268
287
  if (d.length)
269
288
  pinProblem = pinRefusal(pin, d);
289
+ if (d.length && !record && recordChain !== null && d.some((x) => x.includes('genesis'))) {
290
+ pinProblem += " The signed release record could not be read, so the SDK's own pin was used: if this network has moved to a new genesis, try again once the record can be read.";
291
+ }
270
292
  }
271
293
  if (pinProblem && opts.onPinProblem)
272
294
  opts.onPinProblem(pinProblem);
273
- return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem, record, recordProblem, ...(recordLive ? { recordLive } : {}) };
295
+ return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem, record, recordProblem, recordProblemCode, ...(recordLive ? { recordLive } : {}) };
274
296
  }