@vordium/sdk 0.2.1 → 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 CHANGED
@@ -19,11 +19,17 @@ const v = await Vordium.connect({ network: 'testnet' }) // or 'mainnet'
19
19
  ```
20
20
 
21
21
  `connect` reads the network spec, the node's `/status` and the JSON-RPC `eth_chainId`, and refuses unless all three name
22
- the same chain and the same genesis. Each named network is pinned in the SDK (`PINS`: mainnet chain 101101, testnet chain
23
- 101102, each with its genesis sha256), and every signature is made under the pin: the EIP-712 domain's chain id and
24
- `salt` come from it. When what the network reports differs from its pin, reads still work, `network.pinProblem` says
25
- why (and `onPinProblem`, when given, is called), and every signature is refused with `PinMismatch`, naming the network,
26
- the expected and the reported values. A new genesis for a named network needs a new SDK release.
22
+ the same chain and the same genesis. A named network's identity comes from the signed release record: `releases.json`
23
+ (at `https://binaries.vordium.com/<network>/releases.json`) names each network's chain id, genesis sha256 and deposit
24
+ bridge, and is used only when its detached OpenPGP signature (`releases.json.asc`) verifies under the release key that
25
+ ships in the SDK (fingerprint `C5EB4728F660369CE519D834B48FB4B71EFD48AE`). The SDK verifies it itself (Ed25519, no
26
+ other program, no key fetched), and refuses a record that is unsigned, signed by another key, changed after signing,
27
+ expired or older than one it has seen, and any genesis other than the one the record names for the network
28
+ (`network.record`, `network.recordProblem`). While no record is served, the pins in the SDK apply (`PINS`: mainnet
29
+ chain 101101, testnet chain 101102, each with its genesis sha256). Every signature is made under that identity: the
30
+ EIP-712 domain's chain id and `salt` come from it. When what the network reports differs, reads still work,
31
+ `network.pinProblem` says why (and `onPinProblem`, when given, is called), and every signature is refused with
32
+ `PinMismatch`, naming the network, the expected and the reported values.
27
33
 
28
34
  An address of your own must say which network it serves, or carry a pin; without one it can be read, but nothing is
29
35
  signed for it (`UnpinnedNetwork`):
@@ -33,6 +39,8 @@ const mine = await Vordium.connect({ network: { ...NETWORKS.mainnet, spec: 'http
33
39
  rpc: 'https://node.example', api: 'https://node.example' } }) // held to the mainnet pin
34
40
  const dev = await Vordium.connect({ network: { name: 'devnet', spec: '…', rpc: '…', api: '…',
35
41
  pin: { chainId: 777001, genesis: '<64 hex>' } } }) // a network of your own
42
+ const listed = await Vordium.connect({ network: { name: 'devnet', spec: '…', rpc: '…', api: '…',
43
+ recordChainId: 777002 } }) // a chain the signed record lists
36
44
  ```
37
45
 
38
46
  ## Trade
@@ -104,6 +112,24 @@ account operations — session keys, agents, TWAP, margin mode and builder appro
104
112
  `applied` is true only once the chain's own read shows the change. Orders return the submission; read them back with
105
113
  `waitForOrder()`, `openOrders()` and `positions()`.
106
114
 
115
+ ## When the answer is lost
116
+
117
+ A write carries no receipt, so when its answer is lost (a timeout, a dropped connection, a gateway error) the SDK reads
118
+ the node it sent the write to — never an explorer — until the state shows what happened, for up to 30 s inside the call
119
+ (`settleMs`; 0 returns at once) and up to 2 minutes in all. The answer then carries `outcome`:
120
+
121
+ ```ts
122
+ const r = await me.placeOrder({ pairId: 1, side: 'buy', size: '0.01', orderType: 'Limit', price: '2000' })
123
+ if (r.outcome) {
124
+ console.log(r.outcome.state, r.outcome.text, r.outcome.next) // pending_checking · applied · refused · not_applied · still_unknown
125
+ if (r.pending) await r.pending.wait() // keep reading to the 2-minute limit
126
+ }
127
+ ```
128
+
129
+ Only the same signed bytes are ever sent again: an order is never signed twice for one intent; a cancel, an agent revoke
130
+ and `stopAll()` offer `pending.resendSame()`; `cancelAll()` and `batch()` are never sent again. `pending()` lists the
131
+ writes of this computer whose outcome is not known yet.
132
+
107
133
  ## Agents
108
134
 
109
135
  ```ts
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Account = exports.Vordium = void 0;
3
+ exports.Account = exports.Vordium = exports.STOP_ALL_AHEAD_S = void 0;
4
4
  exports.twapOnSteps = twapOnSteps;
5
5
  exports.matchesSigned = matchesSigned;
6
6
  exports.twapMatches = twapMatches;
@@ -15,6 +15,7 @@ const network_js_1 = require("./network.js");
15
15
  const pins_js_1 = require("./pins.js");
16
16
  const nonce_js_1 = require("./nonce.js");
17
17
  const resend_js_1 = require("./resend.js");
18
+ const outcome_js_1 = require("./outcome.js");
18
19
  const orders_js_1 = require("./orders.js");
19
20
  const reads_js_1 = require("./reads.js");
20
21
  const sign_js_1 = require("./sign.js");
@@ -33,6 +34,8 @@ async function outcome(r, shows, waitMs, notShown) {
33
34
  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` };
34
35
  }
35
36
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
37
+ /** Seconds ahead a stop's deadline is set (the chain takes at most 300). */
38
+ exports.STOP_ALL_AHEAD_S = 120;
36
39
  /** Read the chain until `fn` is true or `ms` runs out. A failed read counts as "not yet". */
37
40
  async function waitFor(fn, ms, stepMs = 1000) {
38
41
  const end = Date.now() + ms;
@@ -77,15 +80,19 @@ class Vordium {
77
80
  static async connect(opts = {}) {
78
81
  const transport = opts.transport ?? http_js_1.fetchTransport;
79
82
  const timeoutMs = opts.timeoutMs ?? 15000;
80
- const net = await (0, network_js_1.connectNetwork)(opts.network ?? 'testnet', { transport, timeoutMs, onPinProblem: opts.onPinProblem });
83
+ const net = await (0, network_js_1.connectNetwork)(opts.network ?? 'testnet', {
84
+ transport, timeoutMs, onPinProblem: opts.onPinProblem,
85
+ releaseKeys: opts.releaseKeys, releaseRecordStore: opts.releaseRecordStore, releaseRecordNow: opts.releaseRecordNow, releaseRecordMinSequence: opts.releaseRecordMinSequence,
86
+ });
81
87
  return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000, opts.chainClock ?? opts.transport === undefined);
82
88
  }
83
89
  /**
84
- * The signing domain of the node this client posts to, built from the network's pin (`PINS`) after the network's
85
- * reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
90
+ * The signing domain of the node this client posts to, built from the network's identity (the signed release record's,
91
+ * else its pin in `PINS`) after the network's reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
86
92
  * chain is refused, never followed.
87
93
  */
88
94
  async domain(cls) {
95
+ await (0, network_js_1.refreshRecord)(this.network);
89
96
  const pin = (0, network_js_1.signingPin)(this.network);
90
97
  if (Date.now() - this.checkedAt >= this.ttlMs) {
91
98
  const id = await (0, network_js_1.nodeIdentity)(this.network.api, this.transport, this.timeoutMs);
@@ -111,6 +118,18 @@ class Vordium {
111
118
  throw new errors_js_1.VordiumError('read_failed', `The read ${path} answered HTTP ${r.status}.`);
112
119
  return r.body;
113
120
  }
121
+ /** One read while an outcome is checked: {status, body} with its own time limit; status null when it failed. */
122
+ async read(path) {
123
+ try {
124
+ const r = await this.transport.get(this.network.api + path, Math.min(this.timeoutMs, outcome_js_1.READ_TIMEOUT_MS));
125
+ return { status: r.status, body: r.body };
126
+ }
127
+ catch {
128
+ return { status: null, body: null };
129
+ }
130
+ }
131
+ /** Reads of this client's node for an outcome check (never an explorer). */
132
+ nodeReads() { return new outcome_js_1.NodeReads((p) => this.read(p)); }
114
133
  async post(path, body) {
115
134
  return this.transport.post(this.network.api + path, body, this.timeoutMs);
116
135
  }
@@ -321,10 +340,17 @@ class Account {
321
340
  * Sign and submit one order (Market or Limit). The answer is a submission; the order is on the book when
322
341
  * {@link Vordium.openOrders} lists its `clientNonce`, or filled when the account's fills show it. Use
323
342
  * {@link waitForOrder} to read it back.
343
+ *
344
+ * The order is signed ONCE; a lost answer or a busy gateway sends the same signed body again (never a new nonce). When
345
+ * an earlier copy may have arrived and no 2xx came back, the outcome is read from the node (the account's orders by
346
+ * this client nonce AND what was signed, then its records: placed, closed, refused) for up to `settleMs` (default 30 s;
347
+ * 0 returns at once): the answer carries `outcome` (`state` pending_checking, applied, refused, not_applied or
348
+ * still_unknown, with `text` and `next`) and, while it is not final, `pending` (`check()`, `wait()`). It is never
349
+ * signed again. When no copy left this machine, {@link DeliveryUnknown} is thrown (`neverSent`).
324
350
  */
325
351
  async placeOrder(o) {
326
352
  const signer = this.orderSigner();
327
- const { builder: wanted, worstPrice, ...plain } = o;
353
+ const { builder: wanted, worstPrice, settleMs, ...plain } = o;
328
354
  if (worstPrice != null && (wanted == null || o.orderType !== 'Market'))
329
355
  throw new errors_js_1.InvalidRequest('worstPrice applies to a market order that names a builder.');
330
356
  (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
@@ -333,10 +359,12 @@ class Account {
333
359
  const clientNonce = o.clientNonce ?? (await this.fresh('orders'));
334
360
  const v = (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce }, spec);
335
361
  let body;
362
+ let validUntilS = null;
336
363
  if (ob) {
337
364
  // a buy's cap rounds down onto the price step and a sell's floor up: never worse than the caller gave
338
365
  const worst8 = worstPrice == null ? 0n : (0, rounding_js_1.price8OnTick)(worstPrice, spec, o.side, true);
339
366
  const v3 = (0, builder_js_1.placeOrderV3Value)(v, (0, builder_js_1.deadline)(null, await this.client.nowS()), ob, undefined, worst8);
367
+ validUntilS = Number(v3.validUntil);
340
368
  body = (0, builder_js_1.placeOrderV3Body)(v3, await this.sign(signer, 'PlaceOrderV3', v3));
341
369
  }
342
370
  else {
@@ -353,26 +381,52 @@ class Account {
353
381
  const ts = [f.timestampMs, f.timestamp_ms, f.ts_ms].find((x) => typeof x === 'number');
354
382
  return ts !== undefined && ts > rewound ? f : null;
355
383
  };
384
+ const wire = JSON.stringify(body);
385
+ const digest = (0, outcome_js_1.bodyDigest)(wire);
386
+ const sentAtMs = Date.now();
387
+ const signerAddr = (0, ethers_1.getAddress)(await signer.getAddress());
388
+ const jid = await (0, outcome_js_1.journalAdd)({ action: 'order', owner: this.owner, rest: this.client.network.api, nonce: clientNonce, signer: signerAddr, signed: (0, outcome_js_1.plain)(signed), rewound, validUntil: validUntilS, sentAtMs, digest });
389
+ // an earlier copy may have arrived and no 2xx came back (a lost answer, the nonce code - which also means "outside
390
+ // the window" or "used by another signer" -, a refusal of a later copy, a 5xx): the node's reads decide, and the
391
+ // order is ours only when it carries what was signed
392
+ const lost = async (attempts, answer) => {
393
+ const reads = this.client.nodeReads();
394
+ const who = (0, outcome_js_1.signerOf)(reads, this.owner, signerAddr, jid); // an agent of the account or not, once it answers
395
+ const pw = new outcome_js_1.PendingWrite('order', async () => {
396
+ const w = await who();
397
+ if (!w.known)
398
+ return { state: null, fill: {}, read: null };
399
+ return (0, outcome_js_1.judgeOrder)(reads, this.owner, clientNonce, signed, { rewound, validUntilS, sentAtMs, chainMs: () => this.client.chainTimeMs(), agent: w.agent });
400
+ }, { meta: { nonce: clientNonce, digest, attempts }, journalId: jid });
401
+ await (0, outcome_js_1.journalSet)(jid, { state: 'pending_checking', attempts });
402
+ const oc = await (0, outcome_js_1.settle)(pw, settleMs ?? outcome_js_1.SETTLE_MS);
403
+ const found = oc.state === 'applied' ? ours(pw.found) : null;
404
+ const base = { clientNonce, attempts, answer, found, outcome: oc, pending: oc.final ? null : pw, ...withBuilder };
405
+ if (oc.state === 'applied')
406
+ return { submitted: true, status: 0, refusal: null, actions: [], alreadyReceived: true, unknown: false, ...base };
407
+ if (oc.state === 'refused' || oc.state === 'not_applied') {
408
+ 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 };
409
+ }
410
+ return { ...unknownResult(attempts, oc.text, answer), ...base, alreadyReceived: false };
411
+ };
356
412
  let r;
357
413
  try {
358
- r = await this.postSame('/order/place', JSON.stringify(body), clientNonce);
414
+ r = await this.postSame('/order/place', wire, clientNonce);
359
415
  }
360
416
  catch (e) {
361
- if (!(e instanceof resend_js_1.DeliveryUnknown))
417
+ if (!(e instanceof resend_js_1.DeliveryUnknown)) {
418
+ await (0, outcome_js_1.journalDone)(jid);
362
419
  throw e;
363
- const found = ours(await this.orderByClientNonce(clientNonce, signed));
364
- if (!found)
420
+ }
421
+ if (e.neverSent) {
422
+ await (0, outcome_js_1.journalDone)(jid);
365
423
  throw e;
366
- return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
367
- }
368
- if (r.needsReadBack) {
369
- // the network's nonce code means "used" (perhaps by our earlier copy), "outside the window", or "used by another
370
- // signer": it is ours only when the order the network lists carries what was signed
371
- const found = ours(await this.orderByClientNonce(clientNonce, signed));
372
- if (found)
373
- return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
374
- 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 };
424
+ }
425
+ return lost(e.attempts, null);
375
426
  }
427
+ if (r.needsReadBack)
428
+ return lost(r.attempts, r.body);
429
+ await (0, outcome_js_1.journalDone)(jid);
376
430
  const s = (0, orders_js_1.readAnswer)(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
377
431
  return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false, ...withBuilder };
378
432
  }
@@ -419,45 +473,53 @@ class Account {
419
473
  }, ms);
420
474
  return state;
421
475
  }
422
- async cancelOrder(orderId) {
476
+ /**
477
+ * Cancel one order. A cancel carries no nonce and the network cancels an order once, so a lost answer sends the SAME
478
+ * signed body again. When an earlier copy may have arrived and no 2xx came back, the outcome is read from the node
479
+ * (the order no longer listed, and its record: cancelled, or filled first) for up to `settleMs` (default 30 s; 0
480
+ * returns at once): `done` / `filled` / `unknown`, with `outcome` and, while it is not final, `pending` (whose
481
+ * `resendSame()` sends the same signed cancel again).
482
+ */
483
+ async cancelOrder(orderId, opts = {}) {
423
484
  const signer = this.orderSigner();
424
485
  const id = (0, units_js_1.uint)(orderId, units_js_1.U64, 'orderId');
425
486
  const sig = await this.sign(signer, 'CancelOrder', { owner: this.owner, orderId: id });
426
- // a cancel carries no nonce; cancelling an order twice cancels it once, so a lost answer sends the same body again.
487
+ const wire = JSON.stringify((0, orders_js_1.cancelOrderBody)(this.owner, (0, ethers_1.getAddress)(await signer.getAddress()), id, (0, sign_js_1.rs64)(sig)));
488
+ const digest = (0, outcome_js_1.bodyDigest)(wire);
489
+ const send = () => this.client.post('/order/cancel', wire);
490
+ const jid = await (0, outcome_js_1.journalAdd)({ action: 'cancel', owner: this.owner, rest: this.client.network.api, orderId: id.toString(), sentAtMs: Date.now(), digest });
427
491
  // When an earlier copy may have arrived, the answer to a later one ("not found", a 5xx) is about that later copy:
428
- // the account's resting orders decide.
429
- const readBack = async (answer, attempts) => {
430
- let rows = null;
431
- try {
432
- rows = await this.client.openOrders(this.owner);
433
- }
434
- catch {
435
- rows = null;
436
- }
437
- if (!rows || rows.some((o) => BigInt(o.orderId) === id)) {
438
- 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);
439
- }
440
- // not resting: the order's own records say whether the cancel or a fill closed it
441
- const how = cancelOutcome(await this.client.orderRecords(this.owner).catch(() => []), id);
442
- if (how === 'cancelled')
443
- return { submitted: true, status: 0, refusal: null, actions: [], answer, done: true, attempts };
444
- if (how === 'filled')
445
- 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 };
446
- return unknownResult(attempts, 'The order no longer rests: it closed (filled or cancelled). Check the fills and the position.', answer);
492
+ // the node's reads decide.
493
+ const lost = async (answer, attempts) => {
494
+ const reads = this.client.nodeReads();
495
+ const pw = new outcome_js_1.PendingWrite('cancel', () => (0, outcome_js_1.judgeCancel)(reads, this.owner, id), { meta: { orderId: id.toString(), digest, attempts }, resend: send, journalId: jid });
496
+ await (0, outcome_js_1.journalSet)(jid, { state: 'pending_checking', attempts });
497
+ const oc = await (0, outcome_js_1.settle)(pw, opts.settleMs ?? outcome_js_1.SETTLE_MS);
498
+ const more = { outcome: oc, pending: oc.final ? null : pw, attempts };
499
+ if (oc.state === 'applied')
500
+ return { submitted: true, status: 0, refusal: null, actions: [], answer, done: true, ...more };
501
+ if (oc.state === 'applied_other')
502
+ return { submitted: false, status: 0, refusal: { code: 'order_filled', message: oc.text, detail: oc.next, retryAfter: null }, actions: [], answer, filled: true, ...more };
503
+ return { ...unknownResult(attempts, oc.text, answer), ...more };
447
504
  };
448
505
  let r;
449
506
  try {
450
- r = await this.postSame('/order/cancel', JSON.stringify((0, orders_js_1.cancelOrderBody)(this.owner, (0, ethers_1.getAddress)(await signer.getAddress()), id, (0, sign_js_1.rs64)(sig))));
507
+ r = await (0, resend_js_1.sendSame)(send);
451
508
  }
452
509
  catch (e) {
453
- if (!(e instanceof resend_js_1.DeliveryUnknown))
510
+ if (!(e instanceof resend_js_1.DeliveryUnknown)) {
511
+ await (0, outcome_js_1.journalDone)(jid);
454
512
  throw e;
455
- if (e.neverSent)
513
+ }
514
+ if (e.neverSent) {
515
+ await (0, outcome_js_1.journalDone)(jid);
456
516
  return { submitted: false, status: 0, refusal: { code: 'not_sent', message: e.message, detail: '', retryAfter: null }, actions: [], answer: null, attempts: e.attempts };
457
- return readBack(null, e.attempts);
517
+ }
518
+ return lost(null, e.attempts);
458
519
  }
459
520
  if (r.needsReadBack)
460
- return readBack(r.body, r.attempts);
521
+ return lost(r.body, r.attempts);
522
+ await (0, outcome_js_1.journalDone)(jid);
461
523
  return (0, orders_js_1.readAnswer)(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
462
524
  }
463
525
  /** Take-profit / stop-loss on an open position (8-decimal prices; 0 leaves a leg unset). */
@@ -470,7 +532,11 @@ class Account {
470
532
  const sig = await this.sign(signer, 'SetTpSl', value);
471
533
  return this.send('/tpsl/set', (0, orders_js_1.setTpSlBody)(this.owner, (0, ethers_1.getAddress)(await signer.getAddress()), value.pairId, value.positionId, value.takeProfit8dec, value.stopLoss8dec, sig));
472
534
  }
473
- /** Up to the published maximum of place / cancel actions in one signed batch. Cancels apply first. */
535
+ /**
536
+ * Up to the published maximum of place / cancel actions in one signed batch. Cancels apply first. A batch is never
537
+ * sent again after a lost answer; its outcome is then read from the node (each place by its client nonce, each
538
+ * cancelled order no longer listed) for up to `settleMs` (default 30 s; 0 returns at once).
539
+ */
474
540
  async batch(actions, opts = {}) {
475
541
  const max = opts.maxActions ?? orders_js_1.BATCH_MAX;
476
542
  if (actions.length < 1 || actions.length > max)
@@ -478,7 +544,44 @@ class Account {
478
544
  actions = await this.onSteps(actions);
479
545
  const nonce = opts.nonce ?? (await this.fresh('orders'));
480
546
  const sig = await this.sign(this.orderSigner(), 'BatchOrders', { owner: this.owner, nonce, actions });
481
- return { ...(await this.send('/order/batch-signed', (0, orders_js_1.batchBody)(this.owner, nonce, actions, sig), nonce)), nonce };
547
+ const wire = JSON.stringify((0, orders_js_1.batchBody)(this.owner, nonce, actions, sig));
548
+ 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 }]);
549
+ const cancels = actions.filter((a) => a.kind === 1).map((a) => String(a.orderId));
550
+ const cancelNonces = actions.filter((a) => a.kind === 2).map((a) => Number(a.clientNonce));
551
+ const digest = (0, outcome_js_1.bodyDigest)(wire);
552
+ const signerAddr = (0, ethers_1.getAddress)(await this.orderSigner().getAddress());
553
+ const jid = await (0, outcome_js_1.journalAdd)({ action: 'batch', owner: this.owner, rest: this.client.network.api, nonce, signer: signerAddr, places: (0, outcome_js_1.plain)(places), cancels, cancelNonces, sentAtMs: Date.now(), digest });
554
+ const reads = this.client.nodeReads();
555
+ const who = (0, outcome_js_1.signerOf)(reads, this.owner, places.length ? signerAddr : null, jid);
556
+ const judge = async () => {
557
+ const w = await who();
558
+ if (!w.known)
559
+ return { state: null, fill: {}, read: null };
560
+ return (0, outcome_js_1.judgeBatch)(reads, this.owner, places, cancels, null, cancelNonces, w.agent);
561
+ };
562
+ const action = places.length ? 'order' : 'cancel_all';
563
+ let sent;
564
+ try {
565
+ sent = await this.send('/order/batch-signed', wire, nonce);
566
+ }
567
+ catch (e) {
568
+ await (0, outcome_js_1.journalDone)(jid);
569
+ throw e;
570
+ }
571
+ return { ...(await this.checked(sent, action, judge, opts.settleMs, { nonce, digest }, jid)), nonce };
572
+ }
573
+ /** A write the network is not known to apply once, whose answer was lost: never sent again; the node's reads decide. */
574
+ async checked(s, action, judge, settleMs, meta, jid) {
575
+ if (!s.unknown) {
576
+ await (0, outcome_js_1.journalDone)(jid);
577
+ return s;
578
+ }
579
+ const pw = new outcome_js_1.PendingWrite(action, judge, { meta: { ...meta, attempts: s.attempts }, journalId: jid });
580
+ await (0, outcome_js_1.journalSet)(jid, { state: 'pending_checking', attempts: s.attempts });
581
+ const oc = await (0, outcome_js_1.settle)(pw, settleMs ?? outcome_js_1.SETTLE_MS);
582
+ if (oc.applied === true)
583
+ return { ...s, submitted: true, unknown: false, refusal: null, outcome: oc, pending: null }; // the node shows it applied
584
+ return { ...s, refusal: { code: s.refusal?.code ?? 'delivery_unknown', message: oc.text, detail: oc.next, retryAfter: null }, outcome: oc, pending: oc.final ? null : pw };
482
585
  }
483
586
  /**
484
587
  * The batch as it will be signed: every place action's price and size on its market's tick and lot (one rules read
@@ -498,12 +601,30 @@ class Account {
498
601
  return { ...a, price, size };
499
602
  });
500
603
  }
501
- /** Cancel every open order on `pairId` (0 = every market). */
502
- async cancelAll(pairId = 0) {
604
+ /**
605
+ * Cancel every open order on `pairId` (0 = every market). The open orders are read first. A cancel-all is never sent
606
+ * again after a lost answer (a late copy could cancel orders placed after the first applied); its outcome is then read
607
+ * from the node — none of the orders listed before is still listed — for up to `settleMs` (default 30 s; 0 returns
608
+ * at once): `outcome` and, while it is not final, `pending`.
609
+ */
610
+ async cancelAll(pairId = 0, opts = {}) {
503
611
  const p = (0, units_js_1.safeNumber)((0, units_js_1.uint)(pairId, units_js_1.U32, 'pairId'), 'pairId');
612
+ const before = (0, outcome_js_1.orderIds)((await this.client.read(`/orders/${this.owner}`)).body, p);
504
613
  const nonce = await this.fresh('orders');
505
614
  const sig = await this.sign(this.orderSigner(), 'CancelAllOrders', { owner: this.owner, pairId: p, nonce });
506
- return this.send('/order/cancel-all', (0, orders_js_1.cancelAllBody)(this.owner, p, nonce, sig), nonce);
615
+ const wire = JSON.stringify((0, orders_js_1.cancelAllBody)(this.owner, p, nonce, sig));
616
+ const digest = (0, outcome_js_1.bodyDigest)(wire);
617
+ const jid = await (0, outcome_js_1.journalAdd)({ action: 'cancel_all', owner: this.owner, rest: this.client.network.api, nonce, pairId: p, before, sentAtMs: Date.now(), digest });
618
+ const reads = this.client.nodeReads();
619
+ let sent;
620
+ try {
621
+ sent = await this.send('/order/cancel-all', wire, nonce);
622
+ }
623
+ catch (e) {
624
+ await (0, outcome_js_1.journalDone)(jid);
625
+ throw e;
626
+ }
627
+ return this.checked(sent, 'cancel_all', () => (0, outcome_js_1.judgeCancelAll)(reads, this.owner, before, p), opts.settleMs, { nonce, digest }, jid);
507
628
  }
508
629
  /**
509
630
  * Cancel-and-replace at a new price and size (a new order id, no time priority). The new price and size go onto the
@@ -756,11 +877,95 @@ class Account {
756
877
  const r = await this.submitAgentOp(signer, op, value, (x) => !!x && x.name === value.name, value.agent, waitMs);
757
878
  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)' };
758
879
  }
759
- async revokeAgent(agent, waitMs = 30000) {
880
+ /**
881
+ * Revoke an agent (RevokeAgent, owner key, its nonce above the chain's mark for that agent). An agent the chain already
882
+ * lists as revoked is not signed for. A lost answer sends the same bytes again (the network applies it once). It is
883
+ * applied only when the agent's committed record reads `revoked`: even after a 2xx the state is `pending_checking`
884
+ * until then. Reads for up to `waitMs` (default 30 s; 0 returns at once); `outcome` and, while not final, `pending`.
885
+ */
886
+ async revokeAgent(agent, waitMs = outcome_js_1.SETTLE_MS) {
760
887
  const signer = this.needOwner('Revoking an agent');
761
888
  const op = 'RevokeAgent';
762
- const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), nonce: await this.fresh('account') };
763
- return this.submitAgentOp(signer, op, value, (rec) => !!rec && rec.status === 'revoked', value.agent, waitMs);
889
+ const a = this.addr(agent, op);
890
+ const reads = this.client.nodeReads();
891
+ const held = (await reads.ok(`/agents/${this.owner}/${a}`));
892
+ if (held && String(held.status ?? '').toLowerCase() === 'revoked') {
893
+ const v = await (0, outcome_js_1.judgeRevoke)(reads, this.owner, a);
894
+ const pw = new outcome_js_1.PendingWrite('revoke', async () => v, { meta: { agent: a, attempts: 0 } });
895
+ const oc = await pw.check();
896
+ return { applied: true, status: 0, answer: null, detail: 'the agent is already revoked', outcome: oc, pending: null };
897
+ }
898
+ const sg = (await reads.ok(`/signers/${this.owner}`));
899
+ const row = (Array.isArray(sg?.agents) ? sg.agents : []).find((x) => String(x?.key ?? '').toLowerCase() === a.toLowerCase());
900
+ const mark = (0, outcome_js_1.storedSessionNonce)({ last_nonce: row?.last_nonce }) ?? 0;
901
+ const value = { owner: this.addr(this.owner, op), agent: a, nonce: await this.fresh('account', undefined, mark + 1) };
902
+ const sig = await this.sign(signer, op, value);
903
+ const wire = JSON.stringify((0, agents_js_1.submitBody)(op, value, sig));
904
+ return this.ownerChecked('revoke', '/submit', wire, () => (0, outcome_js_1.judgeRevoke)(reads, this.owner, a), waitMs, { nonce: value.nonce, agent: a }, { nonce: value.nonce, agent: a });
905
+ }
906
+ /** An owner write whose effect the node's reads decide: same bytes on every copy; pending until the read shows it. */
907
+ async ownerChecked(action, path, wire, judge, settleMs, meta, entry) {
908
+ const digest = (0, outcome_js_1.bodyDigest)(wire);
909
+ const jid = await (0, outcome_js_1.journalAdd)({ ...entry, action, owner: this.owner, rest: this.client.network.api, sentAtMs: Date.now(), digest });
910
+ let r;
911
+ try {
912
+ r = await this.postForResult(path, wire);
913
+ }
914
+ catch (e) {
915
+ await (0, outcome_js_1.journalDone)(jid);
916
+ throw e;
917
+ }
918
+ if (!r.proceed) {
919
+ await (0, outcome_js_1.journalDone)(jid);
920
+ if (r.body?.status === 'not_sent')
921
+ return { applied: false, status: r.status, answer: r.body, detail: 'the network could not be reached: nothing was sent', outcome: null, pending: null };
922
+ const a = (r.body && typeof r.body === 'object' ? r.body : {});
923
+ const code = String(a.code ?? a.reason ?? (r.status ? `http_${r.status}` : 'refused'));
924
+ const meaning = String(a.meaning ?? a.error ?? a.reason ?? 'the network refused it');
925
+ const w = (0, outcome_js_1.say)(action, 'refused', { meaning: (0, outcome_js_1.clause)(meaning), action: '' });
926
+ const oc = { action, state: 'refused', text: w.text, next: w.next, applied: false, final: true, refusal: { code, meaning, action: null },
927
+ read: { source: 'node', route: null, height: null, atMs: Date.now() }, resend: (0, outcome_js_1.resendRule)(action, 'refused'), nonce: meta.nonce, orderId: null, agent: meta.agent ?? null, digest, attempts: 1, counts: {} };
928
+ return { applied: false, status: r.status, answer: r.body, detail: w.text, outcome: oc, pending: null };
929
+ }
930
+ const pw = new outcome_js_1.PendingWrite(action, judge, { meta: { ...meta, digest, attempts: 1 }, resend: () => this.client.post(path, wire), journalId: jid });
931
+ await (0, outcome_js_1.journalSet)(jid, { state: 'pending_checking' });
932
+ const oc = await (0, outcome_js_1.settle)(pw, settleMs);
933
+ 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 };
934
+ }
935
+ /** Whether this network takes StopAllSigners, asked without signing: an empty body is refused as unreadable by a
936
+ * network that has the route; a missing route (404 / 405) or `not_in_force` means it does not take it yet. Null when
937
+ * the network did not answer (not known). */
938
+ async takesStopAll() {
939
+ try {
940
+ const r = await this.client.post('/signers/stop-all', '{}');
941
+ return r.status !== 404 && r.status !== 405 && r.body?.code !== 'not_in_force';
942
+ }
943
+ catch {
944
+ return null;
945
+ }
946
+ }
947
+ /**
948
+ * Stop, on the chain, this account's trading key and every one of its agents with ONE owner signature (StopAllSigners,
949
+ * VordexSession domain, a deadline 120 s after block time — this computer's clock when block time cannot be read —, the
950
+ * session nonce above the stored one). It does not cancel resting orders. Nothing is signed where the network says it
951
+ * does not take it (`applied` false, `outcome` null). A lost
952
+ * answer sends the same bytes again. Applied only when the node reads no trading key and no live agent
953
+ * (`applied_other` when orders the wallet placed itself stay open); not_applied once its deadline passed with a key or
954
+ * an agent still live. Reads for up to `settleMs` (default 30 s; 0 returns at once).
955
+ */
956
+ async stopAll(settleMs = outcome_js_1.SETTLE_MS) {
957
+ const signer = this.needOwner('Stopping every signer');
958
+ if ((await this.takesStopAll()) === false)
959
+ return { applied: false, status: 0, answer: null, detail: 'this network does not take Stop all signers yet: nothing was signed', outcome: null, pending: null };
960
+ const reads = this.client.nodeReads();
961
+ // above the session nonce the chain stored (the session read names it, with or without a live session)
962
+ const stored = (0, outcome_js_1.storedSessionNonce)((await reads.get(`/session/get?owner=${this.owner}`)).body) ?? 0;
963
+ const nonce = await this.fresh('account', undefined, stored + 1);
964
+ const validUntil = (await this.client.nowS()) + exports.STOP_ALL_AHEAD_S;
965
+ const value = { owner: this.owner, nonce, validUntil };
966
+ const sig = await this.sign(signer, 'StopAllSigners', value);
967
+ const wire = JSON.stringify({ owner: this.owner, nonce, validUntil, signature: sig });
968
+ return this.ownerChecked('stop', '/signers/stop-all', wire, () => (0, outcome_js_1.judgeStop)(reads, this.owner, validUntil, () => this.client.chainTimeMs(), nonce), settleMs, { nonce }, { nonce, validUntil });
764
969
  }
765
970
  /**
766
971
  * Set an agent's policy. Refused before signing when the chain would refuse it at apply (it does so silently). The
package/dist/cjs/http.js CHANGED
@@ -30,6 +30,32 @@ async function readBody(r) {
30
30
  }
31
31
  }
32
32
  const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
33
+ /** The body of `r`, read no further than `limit` + 1 bytes (the rest is not downloaded). */
34
+ async function readCapped(r, limit) {
35
+ if (!r.body)
36
+ return new Uint8Array(0);
37
+ const reader = r.body.getReader();
38
+ const parts = [];
39
+ let n = 0;
40
+ for (;;) {
41
+ const { done, value } = await reader.read();
42
+ if (done)
43
+ break;
44
+ parts.push(value);
45
+ n += value.length;
46
+ if (n > limit) {
47
+ await reader.cancel().catch(() => undefined);
48
+ break;
49
+ }
50
+ }
51
+ const out = new Uint8Array(n);
52
+ let i = 0;
53
+ for (const p of parts) {
54
+ out.set(p, i);
55
+ i += p.length;
56
+ }
57
+ return out;
58
+ }
33
59
  const isRedirect = (status) => status >= 300 && status < 400;
34
60
  /** What a redirect answer reads as: never the redirect's own body. */
35
61
  exports.REDIRECT_REFUSAL = Object.freeze({ code: 'redirect_refused', error: 'The node answered with a redirect, which is not followed: use the https address of the node.' });
@@ -59,6 +85,26 @@ exports.fetchTransport = {
59
85
  }
60
86
  throw new errors_js_1.VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
61
87
  },
88
+ async getBytes(url, timeoutMs, limit = Infinity) {
89
+ let last = null;
90
+ for (let attempt = 0; attempt < 3; attempt++) {
91
+ try {
92
+ const r = await fetchWithTimeout(url, {}, timeoutMs);
93
+ if (RETRY_STATUS.has(r.status) && attempt < 2) {
94
+ await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
95
+ continue;
96
+ }
97
+ // a redirect is not followed and its body is not read
98
+ return { status: r.status, bytes: isRedirect(r.status) ? new Uint8Array(0) : await readCapped(r, limit) };
99
+ }
100
+ catch (e) {
101
+ last = e;
102
+ if (attempt < 2)
103
+ await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
104
+ }
105
+ }
106
+ throw new errors_js_1.VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
107
+ },
62
108
  async post(url, body, timeoutMs) {
63
109
  const r = await fetchWithTimeout(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body }, timeoutMs);
64
110
  // a redirect is not an answer about the write: no body is read from it
package/dist/cjs/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.cancelOutcome = exports.twapMatches = exports.matchesSigned = exports.twapOnSteps = exports.Account = exports.Vordium = exports.parseExactJson = exports.fetchTransport = void 0;
17
+ exports.OUTCOME_WORDS = exports.STOP_ALL_AHEAD_S = exports.cancelOutcome = exports.twapMatches = exports.matchesSigned = exports.twapOnSteps = exports.Account = exports.Vordium = exports.parseExactJson = exports.fetchTransport = void 0;
18
18
  __exportStar(require("./errors.js"), exports);
19
19
  var http_js_1 = require("./http.js");
20
20
  Object.defineProperty(exports, "fetchTransport", { enumerable: true, get: function () { return http_js_1.fetchTransport; } });
@@ -24,6 +24,7 @@ __exportStar(require("./types.js"), exports);
24
24
  __exportStar(require("./sign.js"), exports);
25
25
  __exportStar(require("./network.js"), exports);
26
26
  __exportStar(require("./pins.js"), exports);
27
+ __exportStar(require("./releaseRecord.js"), exports);
27
28
  __exportStar(require("./nonce.js"), exports);
28
29
  __exportStar(require("./resend.js"), exports);
29
30
  __exportStar(require("./units.js"), exports);
@@ -41,3 +42,7 @@ Object.defineProperty(exports, "twapOnSteps", { enumerable: true, get: function
41
42
  Object.defineProperty(exports, "matchesSigned", { enumerable: true, get: function () { return client_js_1.matchesSigned; } });
42
43
  Object.defineProperty(exports, "twapMatches", { enumerable: true, get: function () { return client_js_1.twapMatches; } });
43
44
  Object.defineProperty(exports, "cancelOutcome", { enumerable: true, get: function () { return client_js_1.cancelOutcome; } });
45
+ Object.defineProperty(exports, "STOP_ALL_AHEAD_S", { enumerable: true, get: function () { return client_js_1.STOP_ALL_AHEAD_S; } });
46
+ __exportStar(require("./outcome.js"), exports);
47
+ var outcomeWords_js_1 = require("./outcomeWords.js");
48
+ Object.defineProperty(exports, "OUTCOME_WORDS", { enumerable: true, get: function () { return outcomeWords_js_1.OUTCOME_WORDS; } });