@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/dist/cjs/types.js CHANGED
@@ -33,6 +33,7 @@ exports.TYPE_STRINGS = {
33
33
  // VordexSession
34
34
  SessionCreate: 'SessionCreate(address sessionKey,uint256 expiresAt,uint256 nonce)',
35
35
  SessionRevoke: 'SessionRevoke(address owner,uint256 nonce)',
36
+ StopAllSigners: 'StopAllSigners(address owner,uint256 nonce,uint256 validUntil)',
36
37
  };
37
38
  function parseTypeString(s) {
38
39
  const m = /^([A-Za-z0-9]+)\(([^()]*)\)$/.exec(s);
@@ -57,5 +58,5 @@ function typesFor(primary) {
57
58
  }
58
59
  /** Which domain each operation is signed in. */
59
60
  function domainOf(primary) {
60
- return primary === 'SessionCreate' || primary === 'SessionRevoke' ? 'VordexSession' : 'VordCore';
61
+ return primary === 'SessionCreate' || primary === 'SessionRevoke' || primary === 'StopAllSigners' ? 'VordexSession' : 'VordCore';
61
62
  }
@@ -3,8 +3,9 @@ import { type PolicyV1 } from './agents.js';
3
3
  import { type DomainClass, type TypedDomain } from './domains.js';
4
4
  import { type Transport } from './http.js';
5
5
  import { type Network, type NetworkPreset } from './network.js';
6
- import { type NonceSource } from './nonce.js';
6
+ import { type NonceSource, type NonceStore } from './nonce.js';
7
7
  import { ChainClock } from './resend.js';
8
+ import { NodeReads, PendingWrite, type Outcome } from './outcome.js';
8
9
  import { type BatchAction, type OrderInput, type Submitted } from './orders.js';
9
10
  import { type AgentRefusal, type Equity, type OpenOrder, type Position } from './reads.js';
10
11
  import { type TypedSigner } from './sign.js';
@@ -23,6 +24,15 @@ export interface Result {
23
24
  detail: string;
24
25
  /** It may have been received, and the chain's read did not show it yet: read the account before sending it anew. */
25
26
  unknown?: boolean;
27
+ /** For {@link Account.revokeAgent} and {@link Account.stopAll}: what the node's reads made of it (null when nothing was
28
+ * signed or sent), and, while that is not final, the {@link PendingWrite} that goes on reading. */
29
+ outcome?: Outcome | null;
30
+ pending?: PendingWrite | null;
31
+ }
32
+ /** What a lost write's outcome adds to an answer: the outcome, and the handle that goes on reading while it is not final. */
33
+ export interface Checked {
34
+ outcome?: Outcome;
35
+ pending?: PendingWrite | null;
26
36
  }
27
37
  export interface ConnectOptions {
28
38
  network?: 'mainnet' | 'testnet' | NetworkPreset;
@@ -37,7 +47,17 @@ export interface ConnectOptions {
37
47
  * default with the built-in transport; with a transport of your own, off unless set. Off: against this computer's clock.
38
48
  */
39
49
  chainClock?: boolean;
50
+ /** Tests only: armoured OpenPGP public keys that replace the shipped release key (see `releaseRecord.ts`). */
51
+ releaseKeys?: readonly string[];
52
+ /** Where the highest release-record sequence seen is kept (default: the nonce store, files 0600 under Node.js). */
53
+ releaseRecordStore?: NonceStore;
54
+ /** Tests only: this computer's clock in milliseconds, for the release record's expiry. */
55
+ releaseRecordNow?: () => number;
56
+ /** Tests only: the lowest record sequence accepted per chain id, instead of `MIN_RECORD_SEQUENCE`. */
57
+ releaseRecordMinSequence?: Readonly<Record<number, number>>;
40
58
  }
59
+ /** Seconds ahead a stop's deadline is set (the chain takes at most 300). */
60
+ export declare const STOP_ALL_AHEAD_S = 120;
41
61
  /** A connection to one Vordium network: reads, and the signing domains of its node. */
42
62
  export declare class Vordium {
43
63
  readonly network: Network;
@@ -53,13 +73,20 @@ export declare class Vordium {
53
73
  /** Read and check the network (spec, node and JSON-RPC must agree) and return a client for it. Testnet by default. */
54
74
  static connect(opts?: ConnectOptions): Promise<Vordium>;
55
75
  /**
56
- * The signing domain of the node this client posts to, built from the network's pin (`PINS`) after the network's
57
- * reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
76
+ * The signing domain of the node this client posts to, built from the network's identity (the signed release record's,
77
+ * 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
58
78
  * chain is refused, never followed.
59
79
  */
60
80
  domain(cls: DomainClass): Promise<TypedDomain>;
61
81
  /** GET a path of the REST API; null on 404, raises on another failure. */
62
82
  get(path: string): Promise<unknown>;
83
+ /** One read while an outcome is checked: {status, body} with its own time limit; status null when it failed. */
84
+ read(path: string): Promise<{
85
+ status: number | null;
86
+ body: unknown;
87
+ }>;
88
+ /** Reads of this client's node for an outcome check (never an explorer). */
89
+ nodeReads(): NodeReads;
63
90
  post(path: string, body: string): Promise<{
64
91
  status: number;
65
92
  body: unknown;
@@ -178,12 +205,20 @@ export declare class Account {
178
205
  * Sign and submit one order (Market or Limit). The answer is a submission; the order is on the book when
179
206
  * {@link Vordium.openOrders} lists its `clientNonce`, or filled when the account's fills show it. Use
180
207
  * {@link waitForOrder} to read it back.
208
+ *
209
+ * The order is signed ONCE; a lost answer or a busy gateway sends the same signed body again (never a new nonce). When
210
+ * an earlier copy may have arrived and no 2xx came back, the outcome is read from the node (the account's orders by
211
+ * this client nonce AND what was signed, then its records: placed, closed, refused) for up to `settleMs` (default 30 s;
212
+ * 0 returns at once): the answer carries `outcome` (`state` pending_checking, applied, refused, not_applied or
213
+ * still_unknown, with `text` and `next`) and, while it is not final, `pending` (`check()`, `wait()`). It is never
214
+ * signed again. When no copy left this machine, {@link DeliveryUnknown} is thrown (`neverSent`).
181
215
  */
182
216
  placeOrder(o: Omit<OrderInput, 'owner' | 'clientNonce'> & {
183
217
  clientNonce?: number;
184
218
  builder?: OrderBuilder | null;
185
219
  worstPrice?: string | number | null;
186
- }): Promise<Submitted & {
220
+ settleMs?: number;
221
+ }): Promise<Submitted & Checked & {
187
222
  clientNonce: number;
188
223
  attempts: number;
189
224
  alreadyReceived: boolean;
@@ -206,7 +241,16 @@ export declare class Account {
206
241
  waitForOrder(clientNonce: number, ms?: number, opts?: {
207
242
  final?: boolean;
208
243
  }): Promise<'resting' | 'filled' | 'cancelled' | 'expired' | null>;
209
- cancelOrder(orderId: bigint | number): Promise<Submitted & {
244
+ /**
245
+ * Cancel one order. A cancel carries no nonce and the network cancels an order once, so a lost answer sends the SAME
246
+ * signed body again. When an earlier copy may have arrived and no 2xx came back, the outcome is read from the node
247
+ * (the order no longer listed, and its record: cancelled, or filled first) for up to `settleMs` (default 30 s; 0
248
+ * returns at once): `done` / `filled` / `unknown`, with `outcome` and, while it is not final, `pending` (whose
249
+ * `resendSame()` sends the same signed cancel again).
250
+ */
251
+ cancelOrder(orderId: bigint | number, opts?: {
252
+ settleMs?: number;
253
+ }): Promise<Submitted & Checked & {
210
254
  done?: boolean;
211
255
  filled?: boolean;
212
256
  unknown?: boolean;
@@ -214,20 +258,37 @@ export declare class Account {
214
258
  }>;
215
259
  /** Take-profit / stop-loss on an open position (8-decimal prices; 0 leaves a leg unset). */
216
260
  setTpSl(pairId: number, positionId: bigint | number, takeProfit8: bigint, stopLoss8: bigint): Promise<Submitted>;
217
- /** Up to the published maximum of place / cancel actions in one signed batch. Cancels apply first. */
261
+ /**
262
+ * Up to the published maximum of place / cancel actions in one signed batch. Cancels apply first. A batch is never
263
+ * sent again after a lost answer; its outcome is then read from the node (each place by its client nonce, each
264
+ * cancelled order no longer listed) for up to `settleMs` (default 30 s; 0 returns at once).
265
+ */
218
266
  batch(actions: BatchAction[], opts?: {
219
267
  nonce?: number;
220
268
  maxActions?: number;
221
- }): Promise<Submitted & {
269
+ settleMs?: number;
270
+ }): Promise<Submitted & Checked & {
222
271
  nonce: number;
223
272
  }>;
273
+ /** A write the network is not known to apply once, whose answer was lost: never sent again; the node's reads decide. */
274
+ private checked;
224
275
  /**
225
276
  * The batch as it will be signed: every place action's price and size on its market's tick and lot (one rules read
226
277
  * per batch). Refuses, before signing, a size that rounds to 0 or an order below the network's minimum.
227
278
  */
228
279
  onSteps(actions: BatchAction[]): Promise<BatchAction[]>;
229
- /** Cancel every open order on `pairId` (0 = every market). */
230
- cancelAll(pairId?: number): Promise<Submitted>;
280
+ /**
281
+ * Cancel every open order on `pairId` (0 = every market). The open orders are read first. A cancel-all is never sent
282
+ * again after a lost answer (a late copy could cancel orders placed after the first applied); its outcome is then read
283
+ * from the node — none of the orders listed before is still listed — for up to `settleMs` (default 30 s; 0 returns
284
+ * at once): `outcome` and, while it is not final, `pending`.
285
+ */
286
+ cancelAll(pairId?: number, opts?: {
287
+ settleMs?: number;
288
+ }): Promise<Submitted & Checked & {
289
+ attempts: number;
290
+ unknown: boolean;
291
+ }>;
231
292
  /**
232
293
  * Cancel-and-replace at a new price and size (a new order id, no time priority). The new price and size go onto the
233
294
  * order's market tick and lot (a buy's price down, a sell's up, the size down); the market and side come from `opts`,
@@ -307,7 +368,29 @@ export declare class Account {
307
368
  * chain did not show the new name.
308
369
  */
309
370
  renameAgent(agent: string, name: string, waitMs?: number): Promise<Result>;
371
+ /**
372
+ * Revoke an agent (RevokeAgent, owner key, its nonce above the chain's mark for that agent). An agent the chain already
373
+ * lists as revoked is not signed for. A lost answer sends the same bytes again (the network applies it once). It is
374
+ * applied only when the agent's committed record reads `revoked`: even after a 2xx the state is `pending_checking`
375
+ * until then. Reads for up to `waitMs` (default 30 s; 0 returns at once); `outcome` and, while not final, `pending`.
376
+ */
310
377
  revokeAgent(agent: string, waitMs?: number): Promise<Result>;
378
+ /** An owner write whose effect the node's reads decide: same bytes on every copy; pending until the read shows it. */
379
+ private ownerChecked;
380
+ /** Whether this network takes StopAllSigners, asked without signing: an empty body is refused as unreadable by a
381
+ * network that has the route; a missing route (404 / 405) or `not_in_force` means it does not take it yet. Null when
382
+ * the network did not answer (not known). */
383
+ takesStopAll(): Promise<boolean | null>;
384
+ /**
385
+ * Stop, on the chain, this account's trading key and every one of its agents with ONE owner signature (StopAllSigners,
386
+ * VordexSession domain, a deadline 120 s after block time — this computer's clock when block time cannot be read —, the
387
+ * session nonce above the stored one). It does not cancel resting orders. Nothing is signed where the network says it
388
+ * does not take it (`applied` false, `outcome` null). A lost
389
+ * answer sends the same bytes again. Applied only when the node reads no trading key and no live agent
390
+ * (`applied_other` when orders the wallet placed itself stay open); not_applied once its deadline passed with a key or
391
+ * an agent still live. Reads for up to `settleMs` (default 30 s; 0 returns at once).
392
+ */
393
+ stopAll(settleMs?: number): Promise<Result>;
311
394
  /**
312
395
  * Set an agent's policy. Refused before signing when the chain would refuse it at apply (it does so silently). The
313
396
  * agent itself may sign only a tightening of the stored policy, with its own nonce; the owner may loosen (the chain
@@ -4,10 +4,11 @@ import { LOWERCASE_ADDRESS_OPS, loosens, policyFromRead, policyProblems, policyV
4
4
  import { domain } from './domains.js';
5
5
  import { InvalidRequest, NetworkMismatch, VordiumError } from './errors.js';
6
6
  import { fetchTransport } from './http.js';
7
- import { connectNetwork, nodeIdentity, signingPin } from './network.js';
7
+ import { connectNetwork, nodeIdentity, refreshRecord, signingPin } from './network.js';
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;
@@ -70,15 +73,19 @@ export class Vordium {
70
73
  static async connect(opts = {}) {
71
74
  const transport = opts.transport ?? fetchTransport;
72
75
  const timeoutMs = opts.timeoutMs ?? 15000;
73
- const net = await connectNetwork(opts.network ?? 'testnet', { transport, timeoutMs, onPinProblem: opts.onPinProblem });
76
+ const net = await connectNetwork(opts.network ?? 'testnet', {
77
+ transport, timeoutMs, onPinProblem: opts.onPinProblem,
78
+ releaseKeys: opts.releaseKeys, releaseRecordStore: opts.releaseRecordStore, releaseRecordNow: opts.releaseRecordNow, releaseRecordMinSequence: opts.releaseRecordMinSequence,
79
+ });
74
80
  return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000, opts.chainClock ?? opts.transport === undefined);
75
81
  }
76
82
  /**
77
- * The signing domain of the node this client posts to, built from the network's pin (`PINS`) after the network's
78
- * reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
83
+ * The signing domain of the node this client posts to, built from the network's identity (the signed release record's,
84
+ * 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
79
85
  * chain is refused, never followed.
80
86
  */
81
87
  async domain(cls) {
88
+ await refreshRecord(this.network);
82
89
  const pin = signingPin(this.network);
83
90
  if (Date.now() - this.checkedAt >= this.ttlMs) {
84
91
  const id = await nodeIdentity(this.network.api, this.transport, this.timeoutMs);
@@ -104,6 +111,18 @@ export class Vordium {
104
111
  throw new VordiumError('read_failed', `The read ${path} answered HTTP ${r.status}.`);
105
112
  return r.body;
106
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)); }
107
126
  async post(path, body) {
108
127
  return this.transport.post(this.network.api + path, body, this.timeoutMs);
109
128
  }
@@ -313,10 +332,17 @@ export class Account {
313
332
  * Sign and submit one order (Market or Limit). The answer is a submission; the order is on the book when
314
333
  * {@link Vordium.openOrders} lists its `clientNonce`, or filled when the account's fills show it. Use
315
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`).
316
342
  */
317
343
  async placeOrder(o) {
318
344
  const signer = this.orderSigner();
319
- const { builder: wanted, worstPrice, ...plain } = o;
345
+ const { builder: wanted, worstPrice, settleMs, ...plain } = o;
320
346
  if (worstPrice != null && (wanted == null || o.orderType !== 'Market'))
321
347
  throw new InvalidRequest('worstPrice applies to a market order that names a builder.');
322
348
  placeOrderValue({ ...plain, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
@@ -325,10 +351,12 @@ export class Account {
325
351
  const clientNonce = o.clientNonce ?? (await this.fresh('orders'));
326
352
  const v = placeOrderValue({ ...plain, owner: this.owner, clientNonce }, spec);
327
353
  let body;
354
+ let validUntilS = null;
328
355
  if (ob) {
329
356
  // a buy's cap rounds down onto the price step and a sell's floor up: never worse than the caller gave
330
357
  const worst8 = worstPrice == null ? 0n : price8OnTick(worstPrice, spec, o.side, true);
331
358
  const v3 = placeOrderV3Value(v, deadline(null, await this.client.nowS()), ob, undefined, worst8);
359
+ validUntilS = Number(v3.validUntil);
332
360
  body = placeOrderV3Body(v3, await this.sign(signer, 'PlaceOrderV3', v3));
333
361
  }
334
362
  else {
@@ -345,26 +373,52 @@ export class Account {
345
373
  const ts = [f.timestampMs, f.timestamp_ms, f.ts_ms].find((x) => typeof x === 'number');
346
374
  return ts !== undefined && ts > rewound ? f : null;
347
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
+ };
348
404
  let r;
349
405
  try {
350
- r = await this.postSame('/order/place', JSON.stringify(body), clientNonce);
406
+ r = await this.postSame('/order/place', wire, clientNonce);
351
407
  }
352
408
  catch (e) {
353
- if (!(e instanceof DeliveryUnknown))
409
+ if (!(e instanceof DeliveryUnknown)) {
410
+ await journalDone(jid);
354
411
  throw e;
355
- const found = ours(await this.orderByClientNonce(clientNonce, signed));
356
- if (!found)
412
+ }
413
+ if (e.neverSent) {
414
+ await journalDone(jid);
357
415
  throw e;
358
- return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
359
- }
360
- if (r.needsReadBack) {
361
- // the network's nonce code means "used" (perhaps by our earlier copy), "outside the window", or "used by another
362
- // signer": it is ours only when the order the network lists carries what was signed
363
- const found = ours(await this.orderByClientNonce(clientNonce, signed));
364
- if (found)
365
- return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
366
- 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);
367
418
  }
419
+ if (r.needsReadBack)
420
+ return lost(r.attempts, r.body);
421
+ await journalDone(jid);
368
422
  const s = readAnswer(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
369
423
  return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false, ...withBuilder };
370
424
  }
@@ -411,45 +465,53 @@ export class Account {
411
465
  }, ms);
412
466
  return state;
413
467
  }
414
- 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 = {}) {
415
476
  const signer = this.orderSigner();
416
477
  const id = uint(orderId, U64, 'orderId');
417
478
  const sig = await this.sign(signer, 'CancelOrder', { owner: this.owner, orderId: id });
418
- // 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 });
419
483
  // When an earlier copy may have arrived, the answer to a later one ("not found", a 5xx) is about that later copy:
420
- // the account's resting orders decide.
421
- const readBack = async (answer, attempts) => {
422
- let rows = null;
423
- try {
424
- rows = await this.client.openOrders(this.owner);
425
- }
426
- catch {
427
- rows = null;
428
- }
429
- if (!rows || rows.some((o) => BigInt(o.orderId) === id)) {
430
- 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);
431
- }
432
- // not resting: the order's own records say whether the cancel or a fill closed it
433
- const how = cancelOutcome(await this.client.orderRecords(this.owner).catch(() => []), id);
434
- if (how === 'cancelled')
435
- return { submitted: true, status: 0, refusal: null, actions: [], answer, done: true, attempts };
436
- if (how === 'filled')
437
- 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 };
438
- 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 };
439
496
  };
440
497
  let r;
441
498
  try {
442
- r = await this.postSame('/order/cancel', JSON.stringify(cancelOrderBody(this.owner, getAddress(await signer.getAddress()), id, rs64(sig))));
499
+ r = await sendSame(send);
443
500
  }
444
501
  catch (e) {
445
- if (!(e instanceof DeliveryUnknown))
502
+ if (!(e instanceof DeliveryUnknown)) {
503
+ await journalDone(jid);
446
504
  throw e;
447
- if (e.neverSent)
505
+ }
506
+ if (e.neverSent) {
507
+ await journalDone(jid);
448
508
  return { submitted: false, status: 0, refusal: { code: 'not_sent', message: e.message, detail: '', retryAfter: null }, actions: [], answer: null, attempts: e.attempts };
449
- return readBack(null, e.attempts);
509
+ }
510
+ return lost(null, e.attempts);
450
511
  }
451
512
  if (r.needsReadBack)
452
- return readBack(r.body, r.attempts);
513
+ return lost(r.body, r.attempts);
514
+ await journalDone(jid);
453
515
  return readAnswer(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
454
516
  }
455
517
  /** Take-profit / stop-loss on an open position (8-decimal prices; 0 leaves a leg unset). */
@@ -462,7 +524,11 @@ export class Account {
462
524
  const sig = await this.sign(signer, 'SetTpSl', value);
463
525
  return this.send('/tpsl/set', setTpSlBody(this.owner, getAddress(await signer.getAddress()), value.pairId, value.positionId, value.takeProfit8dec, value.stopLoss8dec, sig));
464
526
  }
465
- /** 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
+ */
466
532
  async batch(actions, opts = {}) {
467
533
  const max = opts.maxActions ?? BATCH_MAX;
468
534
  if (actions.length < 1 || actions.length > max)
@@ -470,7 +536,44 @@ export class Account {
470
536
  actions = await this.onSteps(actions);
471
537
  const nonce = opts.nonce ?? (await this.fresh('orders'));
472
538
  const sig = await this.sign(this.orderSigner(), 'BatchOrders', { owner: this.owner, nonce, actions });
473
- 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 };
474
577
  }
475
578
  /**
476
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
@@ -490,12 +593,30 @@ export class Account {
490
593
  return { ...a, price, size };
491
594
  });
492
595
  }
493
- /** Cancel every open order on `pairId` (0 = every market). */
494
- 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 = {}) {
495
603
  const p = safeNumber(uint(pairId, U32, 'pairId'), 'pairId');
604
+ const before = orderIds((await this.client.read(`/orders/${this.owner}`)).body, p);
496
605
  const nonce = await this.fresh('orders');
497
606
  const sig = await this.sign(this.orderSigner(), 'CancelAllOrders', { owner: this.owner, pairId: p, nonce });
498
- 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);
499
620
  }
500
621
  /**
501
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
@@ -748,11 +869,95 @@ export class Account {
748
869
  const r = await this.submitAgentOp(signer, op, value, (x) => !!x && x.name === value.name, value.agent, waitMs);
749
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)' };
750
871
  }
751
- 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) {
752
879
  const signer = this.needOwner('Revoking an agent');
753
880
  const op = 'RevokeAgent';
754
- const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), nonce: await this.fresh('account') };
755
- 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 });
756
961
  }
757
962
  /**
758
963
  * Set an agent's policy. Refused before signing when the chain would refuse it at apply (it does so silently). The
@@ -10,6 +10,12 @@ export interface Transport {
10
10
  body: unknown;
11
11
  retryAfter: string | null;
12
12
  }>;
13
+ /** The exact bytes served at `url` (the signed release record is verified over them), read no further than `limit` + 1
14
+ * bytes. A transport without it reads no release record. */
15
+ getBytes?(url: string, timeoutMs: number, limit?: number): Promise<{
16
+ status: number;
17
+ bytes: Uint8Array;
18
+ }>;
13
19
  }
14
20
  /** What a redirect answer reads as: never the redirect's own body. */
15
21
  export declare const REDIRECT_REFUSAL: Readonly<{