@vordium/sdk 0.2.2 → 0.4.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
@@ -112,10 +112,28 @@ account operations — session keys, agents, TWAP, margin mode and builder appro
112
112
  `applied` is true only once the chain's own read shows the change. Orders return the submission; read them back with
113
113
  `waitForOrder()`, `openOrders()` and `positions()`.
114
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
+
115
133
  ## Agents
116
134
 
117
135
  ```ts
118
- await me.registerAgent({ agent: agentAddress, name: 'Night Desk', mandate: 'market making on ETH', expiresMs })
136
+ await me.registerAgent({ agent: agentAddress, name: 'Night Desk', mandate: 'market making on ETH', expiresMs }) // a revoked agent throws AgentWasRevoked: use a new key
119
137
  await me.setAgentPolicy(agentAddress, policy) // refused before signing if the chain would refuse it
120
138
  await me.setAgentMarketLimit(agentAddress, { pair: 1, allowed: true, maxOrder18, maxPosition18, maxLeverageBps: 20000 })
121
139
  await me.createSession(agentAddress, endMs) // the agent trades with its own key for this account
@@ -1,12 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LOWERCASE_ADDRESS_OPS = exports.SUBMIT_FIELDS = exports.DAY_MS = exports.MAX_LEVERAGE_BPS = exports.ORACLE_BAND_MAX_BPS = exports.ORACLE_BAND_MIN_BPS = exports.CAPS_ALL = exports.CAPABILITY_BITS = exports.RESERVED_WORDS_DEFAULT = exports.NAME_MAX_BYTES = exports.NAME_MIN_BYTES = void 0;
3
+ exports.LOWERCASE_ADDRESS_OPS = exports.SUBMIT_FIELDS = exports.AgentWasRevoked = exports.DAY_MS = exports.MAX_LEVERAGE_BPS = exports.ORACLE_BAND_MAX_BPS = exports.ORACLE_BAND_MIN_BPS = exports.CAPS_ALL = exports.CAPABILITY_BITS = exports.RESERVED_WORDS_DEFAULT = exports.NAME_MAX_BYTES = exports.NAME_MIN_BYTES = void 0;
4
4
  exports.normalizeName = normalizeName;
5
5
  exports.nameSkeleton = nameSkeleton;
6
6
  exports.nameRefusalStep = nameRefusalStep;
7
7
  exports.requireName = requireName;
8
8
  exports.policyProblems = policyProblems;
9
9
  exports.loosens = loosens;
10
+ exports.agentRecordRead = agentRecordRead;
11
+ exports.agentWasRevoked = agentWasRevoked;
10
12
  exports.submitBody = submitBody;
11
13
  exports.policyValue = policyValue;
12
14
  exports.policyFromRead = policyFromRead;
@@ -143,6 +145,31 @@ function loosens(prev, next) {
143
145
  out.push('changes the active hours');
144
146
  return out;
145
147
  }
148
+ // ── A revoked agent is never registered again ─────────────────────────────────────────────────────────────────────
149
+ /** The agent's record shows it was revoked before: it is never registered again. Make a new key for a new agent. */
150
+ class AgentWasRevoked extends errors_js_1.VordiumError {
151
+ agent;
152
+ constructor(agent) {
153
+ super('agent_revoked_before', `Agent ${agent} was revoked before. A revoked agent is never registered again: make a new key for a new agent. Nothing was signed.`);
154
+ this.name = 'AgentWasRevoked';
155
+ this.agent = agent;
156
+ }
157
+ }
158
+ exports.AgentWasRevoked = AgentWasRevoked;
159
+ /** True when `rec` is an agent read the network answered: `found` true (an agent record) or false (never added). Any
160
+ * other answer counts as not read, and nothing is signed on it. */
161
+ function agentRecordRead(rec) {
162
+ return !!rec && typeof rec === 'object' && !Array.isArray(rec) && typeof rec.found === 'boolean';
163
+ }
164
+ /** True when the agent's record (`GET /agents/{owner}/{agent}`) shows it was ever revoked: `revoked_at_ms` or
165
+ * `revoked_height` set, `revoked` true, or `status` "revoked". The network's `found: false` is never revoked. */
166
+ function agentWasRevoked(rec) {
167
+ if (!agentRecordRead(rec) || rec.found === false)
168
+ return false;
169
+ const set = (v) => v !== undefined && v !== null && v !== 0 && v !== '0' && v !== '' && v !== false;
170
+ return set(rec.revoked_at_ms) || set(rec.revoked_height) || rec.revoked === true
171
+ || (typeof rec.status === 'string' && rec.status.toLowerCase().includes('revoked'));
172
+ }
146
173
  /** Per operation: [struct name, wire name, kind], in the order the node reads them. */
147
174
  exports.SUBMIT_FIELDS = {
148
175
  RegisterAgentV2: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['name', 'name', 'string'], ['mandate', 'mandate', 'string'], ['expiresMs', 'expires_ms', 'u64'], ['nonce', 'nonce', 'u64']],
@@ -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;
@@ -79,7 +82,7 @@ class Vordium {
79
82
  const timeoutMs = opts.timeoutMs ?? 15000;
80
83
  const net = await (0, network_js_1.connectNetwork)(opts.network ?? 'testnet', {
81
84
  transport, timeoutMs, onPinProblem: opts.onPinProblem,
82
- releaseKeys: opts.releaseKeys, releaseRecordStore: opts.releaseRecordStore, releaseRecordNow: opts.releaseRecordNow,
85
+ releaseKeys: opts.releaseKeys, releaseRecordStore: opts.releaseRecordStore, releaseRecordNow: opts.releaseRecordNow, releaseRecordMinSequence: opts.releaseRecordMinSequence,
83
86
  });
84
87
  return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000, opts.chainClock ?? opts.transport === undefined);
85
88
  }
@@ -115,6 +118,18 @@ class Vordium {
115
118
  throw new errors_js_1.VordiumError('read_failed', `The read ${path} answered HTTP ${r.status}.`);
116
119
  return r.body;
117
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)); }
118
133
  async post(path, body) {
119
134
  return this.transport.post(this.network.api + path, body, this.timeoutMs);
120
135
  }
@@ -325,10 +340,17 @@ class Account {
325
340
  * Sign and submit one order (Market or Limit). The answer is a submission; the order is on the book when
326
341
  * {@link Vordium.openOrders} lists its `clientNonce`, or filled when the account's fills show it. Use
327
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`).
328
350
  */
329
351
  async placeOrder(o) {
330
352
  const signer = this.orderSigner();
331
- const { builder: wanted, worstPrice, ...plain } = o;
353
+ const { builder: wanted, worstPrice, settleMs, ...plain } = o;
332
354
  if (worstPrice != null && (wanted == null || o.orderType !== 'Market'))
333
355
  throw new errors_js_1.InvalidRequest('worstPrice applies to a market order that names a builder.');
334
356
  (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
@@ -337,10 +359,12 @@ class Account {
337
359
  const clientNonce = o.clientNonce ?? (await this.fresh('orders'));
338
360
  const v = (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce }, spec);
339
361
  let body;
362
+ let validUntilS = null;
340
363
  if (ob) {
341
364
  // a buy's cap rounds down onto the price step and a sell's floor up: never worse than the caller gave
342
365
  const worst8 = worstPrice == null ? 0n : (0, rounding_js_1.price8OnTick)(worstPrice, spec, o.side, true);
343
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);
344
368
  body = (0, builder_js_1.placeOrderV3Body)(v3, await this.sign(signer, 'PlaceOrderV3', v3));
345
369
  }
346
370
  else {
@@ -357,26 +381,52 @@ class Account {
357
381
  const ts = [f.timestampMs, f.timestamp_ms, f.ts_ms].find((x) => typeof x === 'number');
358
382
  return ts !== undefined && ts > rewound ? f : null;
359
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
+ };
360
412
  let r;
361
413
  try {
362
- r = await this.postSame('/order/place', JSON.stringify(body), clientNonce);
414
+ r = await this.postSame('/order/place', wire, clientNonce);
363
415
  }
364
416
  catch (e) {
365
- if (!(e instanceof resend_js_1.DeliveryUnknown))
417
+ if (!(e instanceof resend_js_1.DeliveryUnknown)) {
418
+ await (0, outcome_js_1.journalDone)(jid);
366
419
  throw e;
367
- const found = ours(await this.orderByClientNonce(clientNonce, signed));
368
- if (!found)
420
+ }
421
+ if (e.neverSent) {
422
+ await (0, outcome_js_1.journalDone)(jid);
369
423
  throw e;
370
- return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
371
- }
372
- if (r.needsReadBack) {
373
- // the network's nonce code means "used" (perhaps by our earlier copy), "outside the window", or "used by another
374
- // signer": it is ours only when the order the network lists carries what was signed
375
- const found = ours(await this.orderByClientNonce(clientNonce, signed));
376
- if (found)
377
- return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
378
- 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);
379
426
  }
427
+ if (r.needsReadBack)
428
+ return lost(r.attempts, r.body);
429
+ await (0, outcome_js_1.journalDone)(jid);
380
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());
381
431
  return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false, ...withBuilder };
382
432
  }
@@ -423,45 +473,53 @@ class Account {
423
473
  }, ms);
424
474
  return state;
425
475
  }
426
- 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 = {}) {
427
484
  const signer = this.orderSigner();
428
485
  const id = (0, units_js_1.uint)(orderId, units_js_1.U64, 'orderId');
429
486
  const sig = await this.sign(signer, 'CancelOrder', { owner: this.owner, orderId: id });
430
- // 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 });
431
491
  // When an earlier copy may have arrived, the answer to a later one ("not found", a 5xx) is about that later copy:
432
- // the account's resting orders decide.
433
- const readBack = async (answer, attempts) => {
434
- let rows = null;
435
- try {
436
- rows = await this.client.openOrders(this.owner);
437
- }
438
- catch {
439
- rows = null;
440
- }
441
- if (!rows || rows.some((o) => BigInt(o.orderId) === id)) {
442
- 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);
443
- }
444
- // not resting: the order's own records say whether the cancel or a fill closed it
445
- const how = cancelOutcome(await this.client.orderRecords(this.owner).catch(() => []), id);
446
- if (how === 'cancelled')
447
- return { submitted: true, status: 0, refusal: null, actions: [], answer, done: true, attempts };
448
- if (how === 'filled')
449
- 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 };
450
- 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 };
451
504
  };
452
505
  let r;
453
506
  try {
454
- 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);
455
508
  }
456
509
  catch (e) {
457
- if (!(e instanceof resend_js_1.DeliveryUnknown))
510
+ if (!(e instanceof resend_js_1.DeliveryUnknown)) {
511
+ await (0, outcome_js_1.journalDone)(jid);
458
512
  throw e;
459
- if (e.neverSent)
513
+ }
514
+ if (e.neverSent) {
515
+ await (0, outcome_js_1.journalDone)(jid);
460
516
  return { submitted: false, status: 0, refusal: { code: 'not_sent', message: e.message, detail: '', retryAfter: null }, actions: [], answer: null, attempts: e.attempts };
461
- return readBack(null, e.attempts);
517
+ }
518
+ return lost(null, e.attempts);
462
519
  }
463
520
  if (r.needsReadBack)
464
- return readBack(r.body, r.attempts);
521
+ return lost(r.body, r.attempts);
522
+ await (0, outcome_js_1.journalDone)(jid);
465
523
  return (0, orders_js_1.readAnswer)(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
466
524
  }
467
525
  /** Take-profit / stop-loss on an open position (8-decimal prices; 0 leaves a leg unset). */
@@ -474,7 +532,11 @@ class Account {
474
532
  const sig = await this.sign(signer, 'SetTpSl', value);
475
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));
476
534
  }
477
- /** 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
+ */
478
540
  async batch(actions, opts = {}) {
479
541
  const max = opts.maxActions ?? orders_js_1.BATCH_MAX;
480
542
  if (actions.length < 1 || actions.length > max)
@@ -482,7 +544,44 @@ class Account {
482
544
  actions = await this.onSteps(actions);
483
545
  const nonce = opts.nonce ?? (await this.fresh('orders'));
484
546
  const sig = await this.sign(this.orderSigner(), 'BatchOrders', { owner: this.owner, nonce, actions });
485
- 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 };
486
585
  }
487
586
  /**
488
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
@@ -502,12 +601,30 @@ class Account {
502
601
  return { ...a, price, size };
503
602
  });
504
603
  }
505
- /** Cancel every open order on `pairId` (0 = every market). */
506
- 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 = {}) {
507
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);
508
613
  const nonce = await this.fresh('orders');
509
614
  const sig = await this.sign(this.orderSigner(), 'CancelAllOrders', { owner: this.owner, pairId: p, nonce });
510
- 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);
511
628
  }
512
629
  /**
513
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
@@ -733,11 +850,23 @@ class Account {
733
850
  const c = (0, ethers_1.getAddress)(a);
734
851
  return agents_js_1.LOWERCASE_ADDRESS_OPS.has(op) ? c.toLowerCase() : c;
735
852
  }
736
- /** Register an agent key with a name (the chain's name rule) and a mandate; applied once the chain lists it. */
853
+ /**
854
+ * Register an agent key with a name (the chain's name rule) and a mandate; applied once the chain lists it. The
855
+ * agent's record is read first: an agent that was ever revoked throws {@link AgentWasRevoked} (make a new key), a
856
+ * live agent may be registered again (renew / extend), and a record that cannot be read throws
857
+ * {@link NotAvailable}. Nothing is signed in either refusal.
858
+ */
737
859
  async registerAgent(a, waitMs = 30000) {
738
860
  const signer = this.needOwner('Registering an agent');
739
861
  const op = 'RegisterAgentV2';
740
- const value = { owner: this.addr(this.owner, op), agent: this.addr(a.agent, op), name: (0, agents_js_1.requireName)(a.name), mandate: a.mandate, expiresMs: a.expiresMs, nonce: await this.fresh('account') };
862
+ const agent = this.addr(a.agent, op);
863
+ const name = (0, agents_js_1.requireName)(a.name);
864
+ const held = await this.client.nodeReads().ok(`/agents/${this.owner}/${agent}`);
865
+ if (!(0, agents_js_1.agentRecordRead)(held))
866
+ throw new errors_js_1.NotAvailable("The agent's record could not be read, so it cannot be checked. Nothing was signed; try again.");
867
+ if ((0, agents_js_1.agentWasRevoked)(held))
868
+ throw new agents_js_1.AgentWasRevoked(agent);
869
+ const value = { owner: this.addr(this.owner, op), agent, name, mandate: a.mandate, expiresMs: a.expiresMs, nonce: await this.fresh('account') };
741
870
  return this.submitAgentOp(signer, op, value, (rec) => !!rec && rec.status === 'active' && rec.name === value.name, value.agent, waitMs);
742
871
  }
743
872
  /**
@@ -760,11 +889,95 @@ class Account {
760
889
  const r = await this.submitAgentOp(signer, op, value, (x) => !!x && x.name === value.name, value.agent, waitMs);
761
890
  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)' };
762
891
  }
763
- async revokeAgent(agent, waitMs = 30000) {
892
+ /**
893
+ * Revoke an agent (RevokeAgent, owner key, its nonce above the chain's mark for that agent). An agent the chain already
894
+ * lists as revoked is not signed for. A lost answer sends the same bytes again (the network applies it once). It is
895
+ * applied only when the agent's committed record reads `revoked`: even after a 2xx the state is `pending_checking`
896
+ * until then. Reads for up to `waitMs` (default 30 s; 0 returns at once); `outcome` and, while not final, `pending`.
897
+ */
898
+ async revokeAgent(agent, waitMs = outcome_js_1.SETTLE_MS) {
764
899
  const signer = this.needOwner('Revoking an agent');
765
900
  const op = 'RevokeAgent';
766
- const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), nonce: await this.fresh('account') };
767
- return this.submitAgentOp(signer, op, value, (rec) => !!rec && rec.status === 'revoked', value.agent, waitMs);
901
+ const a = this.addr(agent, op);
902
+ const reads = this.client.nodeReads();
903
+ const held = (await reads.ok(`/agents/${this.owner}/${a}`));
904
+ if (held && String(held.status ?? '').toLowerCase() === 'revoked') {
905
+ const v = await (0, outcome_js_1.judgeRevoke)(reads, this.owner, a);
906
+ const pw = new outcome_js_1.PendingWrite('revoke', async () => v, { meta: { agent: a, attempts: 0 } });
907
+ const oc = await pw.check();
908
+ return { applied: true, status: 0, answer: null, detail: 'the agent is already revoked', outcome: oc, pending: null };
909
+ }
910
+ const sg = (await reads.ok(`/signers/${this.owner}`));
911
+ const row = (Array.isArray(sg?.agents) ? sg.agents : []).find((x) => String(x?.key ?? '').toLowerCase() === a.toLowerCase());
912
+ const mark = (0, outcome_js_1.storedSessionNonce)({ last_nonce: row?.last_nonce }) ?? 0;
913
+ const value = { owner: this.addr(this.owner, op), agent: a, nonce: await this.fresh('account', undefined, mark + 1) };
914
+ const sig = await this.sign(signer, op, value);
915
+ const wire = JSON.stringify((0, agents_js_1.submitBody)(op, value, sig));
916
+ 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 });
917
+ }
918
+ /** An owner write whose effect the node's reads decide: same bytes on every copy; pending until the read shows it. */
919
+ async ownerChecked(action, path, wire, judge, settleMs, meta, entry) {
920
+ const digest = (0, outcome_js_1.bodyDigest)(wire);
921
+ const jid = await (0, outcome_js_1.journalAdd)({ ...entry, action, owner: this.owner, rest: this.client.network.api, sentAtMs: Date.now(), digest });
922
+ let r;
923
+ try {
924
+ r = await this.postForResult(path, wire);
925
+ }
926
+ catch (e) {
927
+ await (0, outcome_js_1.journalDone)(jid);
928
+ throw e;
929
+ }
930
+ if (!r.proceed) {
931
+ await (0, outcome_js_1.journalDone)(jid);
932
+ if (r.body?.status === 'not_sent')
933
+ return { applied: false, status: r.status, answer: r.body, detail: 'the network could not be reached: nothing was sent', outcome: null, pending: null };
934
+ const a = (r.body && typeof r.body === 'object' ? r.body : {});
935
+ const code = String(a.code ?? a.reason ?? (r.status ? `http_${r.status}` : 'refused'));
936
+ const meaning = String(a.meaning ?? a.error ?? a.reason ?? 'the network refused it');
937
+ const w = (0, outcome_js_1.say)(action, 'refused', { meaning: (0, outcome_js_1.clause)(meaning), action: '' });
938
+ const oc = { action, state: 'refused', text: w.text, next: w.next, applied: false, final: true, refusal: { code, meaning, action: null },
939
+ 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: {} };
940
+ return { applied: false, status: r.status, answer: r.body, detail: w.text, outcome: oc, pending: null };
941
+ }
942
+ const pw = new outcome_js_1.PendingWrite(action, judge, { meta: { ...meta, digest, attempts: 1 }, resend: () => this.client.post(path, wire), journalId: jid });
943
+ await (0, outcome_js_1.journalSet)(jid, { state: 'pending_checking' });
944
+ const oc = await (0, outcome_js_1.settle)(pw, settleMs);
945
+ 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 };
946
+ }
947
+ /** Whether this network takes StopAllSigners, asked without signing: an empty body is refused as unreadable by a
948
+ * network that has the route; a missing route (404 / 405) or `not_in_force` means it does not take it yet. Null when
949
+ * the network did not answer (not known). */
950
+ async takesStopAll() {
951
+ try {
952
+ const r = await this.client.post('/signers/stop-all', '{}');
953
+ return r.status !== 404 && r.status !== 405 && r.body?.code !== 'not_in_force';
954
+ }
955
+ catch {
956
+ return null;
957
+ }
958
+ }
959
+ /**
960
+ * Stop, on the chain, this account's trading key and every one of its agents with ONE owner signature (StopAllSigners,
961
+ * VordexSession domain, a deadline 120 s after block time — this computer's clock when block time cannot be read —, the
962
+ * session nonce above the stored one). It does not cancel resting orders. Nothing is signed where the network says it
963
+ * does not take it (`applied` false, `outcome` null). A lost
964
+ * answer sends the same bytes again. Applied only when the node reads no trading key and no live agent
965
+ * (`applied_other` when orders the wallet placed itself stay open); not_applied once its deadline passed with a key or
966
+ * an agent still live. Reads for up to `settleMs` (default 30 s; 0 returns at once).
967
+ */
968
+ async stopAll(settleMs = outcome_js_1.SETTLE_MS) {
969
+ const signer = this.needOwner('Stopping every signer');
970
+ if ((await this.takesStopAll()) === false)
971
+ return { applied: false, status: 0, answer: null, detail: 'this network does not take Stop all signers yet: nothing was signed', outcome: null, pending: null };
972
+ const reads = this.client.nodeReads();
973
+ // above the session nonce the chain stored (the session read names it, with or without a live session)
974
+ const stored = (0, outcome_js_1.storedSessionNonce)((await reads.get(`/session/get?owner=${this.owner}`)).body) ?? 0;
975
+ const nonce = await this.fresh('account', undefined, stored + 1);
976
+ const validUntil = (await this.client.nowS()) + exports.STOP_ALL_AHEAD_S;
977
+ const value = { owner: this.owner, nonce, validUntil };
978
+ const sig = await this.sign(signer, 'StopAllSigners', value);
979
+ const wire = JSON.stringify({ owner: this.owner, nonce, validUntil, signature: sig });
980
+ 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 });
768
981
  }
769
982
  /**
770
983
  * Set an agent's policy. Refused before signing when the chain would refuse it at apply (it does so silently). The
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; } });
@@ -42,3 +42,7 @@ Object.defineProperty(exports, "twapOnSteps", { enumerable: true, get: function
42
42
  Object.defineProperty(exports, "matchesSigned", { enumerable: true, get: function () { return client_js_1.matchesSigned; } });
43
43
  Object.defineProperty(exports, "twapMatches", { enumerable: true, get: function () { return client_js_1.twapMatches; } });
44
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; } });