@vordium/sdk 0.1.1 → 0.1.3

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,8 +19,21 @@ 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. Every signature is bound to that genesis (the EIP-712 domain's `salt`), so a
23
- signature made for one network can never be used on another.
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.
27
+
28
+ 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
+ signed for it (`UnpinnedNetwork`):
30
+
31
+ ```ts
32
+ const mine = await Vordium.connect({ network: { ...NETWORKS.mainnet, spec: 'https://node.example/network-spec.json',
33
+ rpc: 'https://node.example', api: 'https://node.example' } }) // held to the mainnet pin
34
+ const dev = await Vordium.connect({ network: { name: 'devnet', spec: '…', rpc: '…', api: '…',
35
+ pin: { chainId: 777001, genesis: '<64 hex>' } } }) // a network of your own
36
+ ```
24
37
 
25
38
  ## Trade
26
39
 
@@ -2,6 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Account = exports.Vordium = void 0;
4
4
  exports.twapOnSteps = twapOnSteps;
5
+ exports.matchesSigned = matchesSigned;
6
+ exports.twapMatches = twapMatches;
7
+ exports.cancelOutcome = cancelOutcome;
5
8
  const ethers_1 = require("ethers");
6
9
  const account_js_1 = require("./account.js");
7
10
  const agents_js_1 = require("./agents.js");
@@ -9,13 +12,25 @@ const domains_js_1 = require("./domains.js");
9
12
  const errors_js_1 = require("./errors.js");
10
13
  const http_js_1 = require("./http.js");
11
14
  const network_js_1 = require("./network.js");
15
+ const pins_js_1 = require("./pins.js");
12
16
  const nonce_js_1 = require("./nonce.js");
17
+ const resend_js_1 = require("./resend.js");
13
18
  const orders_js_1 = require("./orders.js");
14
19
  const reads_js_1 = require("./reads.js");
15
20
  const sign_js_1 = require("./sign.js");
16
21
  const units_js_1 = require("./units.js");
17
22
  const rounding_js_1 = require("./rounding.js");
18
23
  const types_js_1 = require("./types.js");
24
+ /** The result of an account write by the chain's own read: applied, refused, or not known yet. */
25
+ async function outcome(r, shows, waitMs, notShown) {
26
+ if (!r.proceed) {
27
+ const notSent = r.body?.status === 'not_sent';
28
+ return { applied: false, status: r.status, answer: r.body, detail: notSent ? 'the network could not be reached: nothing was sent' : 'the network refused it' };
29
+ }
30
+ if (await waitFor(shows, waitMs))
31
+ return { applied: true, status: r.status, answer: r.body, detail: '' };
32
+ 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` };
33
+ }
19
34
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
20
35
  /** Read the chain until `fn` is true or `ms` runs out. A failed read counts as "not yet". */
21
36
  async function waitFor(fn, ms, stepMs = 1000) {
@@ -38,32 +53,50 @@ class Vordium {
38
53
  timeoutMs;
39
54
  ttlMs;
40
55
  checkedAt = Date.now();
41
- constructor(network, transport, timeoutMs, ttlMs) {
56
+ /** The network's block time for the nonce window check; null checks against this computer's clock. */
57
+ chainClock;
58
+ constructor(network, transport, timeoutMs, ttlMs, chainClock) {
42
59
  this.network = network;
43
60
  this.transport = transport;
44
61
  this.timeoutMs = timeoutMs;
45
62
  this.ttlMs = ttlMs;
46
- }
63
+ this.chainClock = chainClock ? new resend_js_1.ChainClock(async () => {
64
+ const r = await this.transport.post(this.network.rpc, JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_getBlockByNumber', params: ['latest', false] }), Math.min(this.timeoutMs, 2000));
65
+ const res = r.body?.result;
66
+ return res && typeof res === 'object' ? res : null;
67
+ }, async () => {
68
+ const st = await this.transport.get(this.network.api + '/status', Math.min(this.timeoutMs, 2000));
69
+ const h = st.status === 200 ? st.body?.chain_head : null;
70
+ return typeof h === 'number' && Number.isSafeInteger(h) ? h : null;
71
+ }) : null;
72
+ }
73
+ /** The network's block time now (ms), estimated from its latest block; null when it cannot be read. */
74
+ async chainTimeMs() { return this.chainClock ? this.chainClock.time() : null; }
47
75
  /** Read and check the network (spec, node and JSON-RPC must agree) and return a client for it. Testnet by default. */
48
76
  static async connect(opts = {}) {
49
77
  const transport = opts.transport ?? http_js_1.fetchTransport;
50
78
  const timeoutMs = opts.timeoutMs ?? 15000;
51
- const net = await (0, network_js_1.connectNetwork)(opts.network ?? 'testnet', { transport, timeoutMs });
52
- return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000);
79
+ const net = await (0, network_js_1.connectNetwork)(opts.network ?? 'testnet', { transport, timeoutMs, onPinProblem: opts.onPinProblem });
80
+ return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000, opts.chainClock ?? opts.transport === undefined);
53
81
  }
54
82
  /**
55
- * The signing domain of the node this client posts to. The node's identity is read again after the TTL; a node that
56
- * now serves another chain is refused, never followed.
83
+ * The signing domain of the node this client posts to, built from the network's pin (`PINS`) after the network's
84
+ * reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
85
+ * chain is refused, never followed.
57
86
  */
58
87
  async domain(cls) {
88
+ const pin = (0, network_js_1.signingPin)(this.network);
59
89
  if (Date.now() - this.checkedAt >= this.ttlMs) {
60
90
  const id = await (0, network_js_1.nodeIdentity)(this.network.api, this.transport, this.timeoutMs);
91
+ const d = (0, pins_js_1.pinDifferences)(pin, { "the node's /status": id.chainId }, { "the node's /status": id.genesis });
92
+ if (d.length)
93
+ throw new pins_js_1.PinMismatch((0, pins_js_1.pinRefusal)(pin, d));
61
94
  if (id.chainId !== this.network.chainId || id.genesis !== this.network.genesis) {
62
95
  throw new errors_js_1.NetworkMismatch(`The node now serves chain ${id.chainId} genesis ${id.genesis.slice(0, 8)}…, not the chain this client signs for; refusing to sign.`);
63
96
  }
64
97
  this.checkedAt = Date.now();
65
98
  }
66
- return (0, domains_js_1.domain)(cls, this.network.chainId, this.network.genesis);
99
+ return (0, domains_js_1.domain)(cls, pin.chainId, pin.genesis);
67
100
  }
68
101
  // ── reads ─────────────────────────────────────────────────────────────────────────────────────────────────────────
69
102
  /** GET a path of the REST API; null on 404, raises on another failure. */
@@ -149,12 +182,12 @@ class Vordium {
149
182
  /** A trading account: `owner` signs account operations; `sessionSigner` (a session or agent key) signs orders. */
150
183
  async account(owner, opts = {}) {
151
184
  const address = (0, ethers_1.getAddress)(await owner.getAddress());
152
- return new Account(this, address, owner, opts.sessionSigner ?? null, opts.nonce ?? (0, nonce_js_1.nonceClock)(address), opts.specs === undefined ? null : (0, rounding_js_1.marketRules)(opts.specs));
185
+ return new Account(this, address, owner, opts.sessionSigner ?? null, opts.nonce ?? (0, nonce_js_1.nonceAllocator)(address, 'orders'), opts.specs === undefined ? null : (0, rounding_js_1.marketRules)(opts.specs));
153
186
  }
154
187
  /** An agent's own handle: places orders with the agent key for its owner, and may tighten its own policy. */
155
188
  async agentKey(owner, agentSigner, opts = {}) {
156
189
  const o = (0, ethers_1.getAddress)(owner);
157
- return new Account(this, o, null, agentSigner, (0, nonce_js_1.nonceClock)(o), opts.specs === undefined ? null : (0, rounding_js_1.marketRules)(opts.specs));
190
+ return new Account(this, o, null, agentSigner, (0, nonce_js_1.nonceAllocator)(o, 'orders'), opts.specs === undefined ? null : (0, rounding_js_1.marketRules)(opts.specs));
158
191
  }
159
192
  }
160
193
  exports.Vordium = Vordium;
@@ -166,7 +199,9 @@ class Account {
166
199
  sessionSigner;
167
200
  nonce;
168
201
  specs;
169
- constructor(client, owner, ownerSigner, sessionSigner, nonce,
202
+ constructor(client, owner, ownerSigner, sessionSigner,
203
+ /** The account's client-nonce source: its persisted allocator in the `orders` space by default. */
204
+ nonce,
170
205
  /** Market rules this handle holds; null = read them from the node for each order. */
171
206
  specs = null) {
172
207
  this.client = client;
@@ -195,9 +230,62 @@ class Account {
195
230
  async sign(signer, primary, value) {
196
231
  return (0, sign_js_1.signOp)(signer, await this.client.domain((0, types_js_1.domainOf)(primary)), primary, value);
197
232
  }
198
- async send(path, body) {
199
- const r = await this.client.post(path, typeof body === 'string' ? body : JSON.stringify(body));
200
- return (0, orders_js_1.readAnswer)(r.status, r.body, r.retryAfter, this.client.refusalMeanings());
233
+ /**
234
+ * A fresh nonce, checked against the network's window before anything is signed ({@link ClockOutOfWindow} otherwise):
235
+ * the account's client nonce (`orders`), or the `account` nonce of `signer` (session, margin mode, agent operations).
236
+ */
237
+ async fresh(space = 'orders', signer, floor = 0) {
238
+ const src = space === 'orders' ? this.nonce : (0, nonce_js_1.nonceAllocator)(signer ?? this.owner, 'account');
239
+ if (src instanceof nonce_js_1.NonceAllocator)
240
+ return src.next(floor, await this.client.chainTimeMs());
241
+ return src.next(floor);
242
+ }
243
+ /**
244
+ * POST one signed body, the same bytes on every try. With `dedup` (a write the network applies once per nonce) a lost
245
+ * connection, a timeout or a busy gateway sends it again (never a new nonce); without it only a copy that never left
246
+ * this machine is sent again, and a lost answer throws {@link DeliveryUnknown}.
247
+ */
248
+ async postSame(path, body, nonce = null, dedup = true) {
249
+ return (0, resend_js_1.sendSame)(() => this.client.post(path, body), { nonce, dedup });
250
+ }
251
+ /**
252
+ * An account operation, for a result the chain's own read decides: `proceed` is true when the network took it (2xx),
253
+ * or when it is not known whether it arrived (then the read-back alone says whether it applied).
254
+ */
255
+ async postForResult(path, body, dedup = true) {
256
+ try {
257
+ const s = await this.postSame(path, body, null, dedup);
258
+ if (s.needsReadBack)
259
+ return { status: s.status, body: { status: 'unknown', answer: s.body }, proceed: true };
260
+ return { status: s.status, body: s.body, proceed: s.status >= 200 && s.status < 300 };
261
+ }
262
+ catch (e) {
263
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
264
+ throw e;
265
+ if (e.neverSent)
266
+ return { status: 0, body: { status: 'not_sent', detail: e.message }, proceed: false }; // nothing left this machine
267
+ return { status: 0, body: { status: 'unknown', detail: e.message }, proceed: true };
268
+ }
269
+ }
270
+ /**
271
+ * A write the network does not apply once per nonce (batch, cancel-all, modify, take-profit / stop-loss): never sent
272
+ * again after a lost answer. Unknown is `submitted: false, unknown: true` with the refusal `delivery_unknown`: read the
273
+ * account before sending a new one.
274
+ */
275
+ async send(path, body, nonce = null, dedup = false) {
276
+ try {
277
+ const s = await this.postSame(path, typeof body === 'string' ? body : JSON.stringify(body), nonce, dedup);
278
+ if (s.needsReadBack)
279
+ return unknownResult(s.attempts, `An earlier copy may have arrived (its answer was lost) and the network answered ${s.status}. Read the account before sending a new one.`, s.body);
280
+ return { ...(0, orders_js_1.readAnswer)(s.status, s.body, s.retryAfter, this.client.refusalMeanings()), attempts: s.attempts, unknown: false };
281
+ }
282
+ catch (e) {
283
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
284
+ throw e;
285
+ if (e.neverSent)
286
+ return { submitted: false, status: 0, refusal: { code: 'not_sent', message: e.message, detail: '', retryAfter: null }, actions: [], answer: null, attempts: e.attempts, unknown: false };
287
+ return unknownResult(e.attempts, e.message, null);
288
+ }
201
289
  }
202
290
  // ── orders ────────────────────────────────────────────────────────────────────────────────────────────────────────
203
291
  /**
@@ -207,14 +295,63 @@ class Account {
207
295
  */
208
296
  async placeOrder(o) {
209
297
  const signer = this.orderSigner();
210
- const clientNonce = o.clientNonce ?? this.nonce.next();
211
- (0, orders_js_1.placeOrderValue)({ ...o, owner: this.owner, clientNonce }); // refusals that need no market rules come first
212
- const v = (0, orders_js_1.placeOrderValue)({ ...o, owner: this.owner, clientNonce }, await this.pairSpec(o.pairId));
298
+ (0, orders_js_1.placeOrderValue)({ ...o, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
299
+ const spec = await this.pairSpec(o.pairId);
300
+ const clientNonce = o.clientNonce ?? (await this.fresh('orders'));
301
+ const v = (0, orders_js_1.placeOrderValue)({ ...o, owner: this.owner, clientNonce }, spec);
213
302
  const sig = await this.sign(signer, 'PlaceOrder', v);
214
303
  const body = (0, orders_js_1.placeOrderBody)(v, (0, ethers_1.getAddress)(await signer.getAddress()), (0, sign_js_1.rs64)(sig));
215
- const r = await this.client.post('/order/place', JSON.stringify(body));
304
+ const signed = { pairId: v.pairId, side: v.side, size: v.size, price: v.orderType === 1 ? v.price : null };
305
+ // after the mark was set back to the clock, a nonce may repeat one handed out before: a read-back must be newer
306
+ const rewound = this.nonce instanceof nonce_js_1.NonceAllocator ? await this.nonce.rewoundBefore(clientNonce) : null;
307
+ const ours = (f) => {
308
+ if (!f || rewound === null)
309
+ return f;
310
+ const ts = [f.timestampMs, f.timestamp_ms, f.ts_ms].find((x) => typeof x === 'number');
311
+ return ts !== undefined && ts > rewound ? f : null;
312
+ };
313
+ let r;
314
+ try {
315
+ r = await this.postSame('/order/place', JSON.stringify(body), clientNonce);
316
+ }
317
+ catch (e) {
318
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
319
+ throw e;
320
+ const found = ours(await this.orderByClientNonce(clientNonce, signed));
321
+ if (!found)
322
+ throw e;
323
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found };
324
+ }
325
+ if (r.needsReadBack) {
326
+ // the network's nonce code means "used" (perhaps by our earlier copy), "outside the window", or "used by another
327
+ // signer": it is ours only when the order the network lists carries what was signed
328
+ const found = ours(await this.orderByClientNonce(clientNonce, signed));
329
+ if (found)
330
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found };
331
+ 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 };
332
+ }
216
333
  const s = (0, orders_js_1.readAnswer)(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
217
- return { ...s, status: r.status, clientNonce };
334
+ return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false };
335
+ }
336
+ /**
337
+ * The account's order with `clientNonce` as the network lists it: resting (open orders), else its record; null when
338
+ * it lists neither (or cannot be read). With `signed`, only an order that carries the signed market, side and size or
339
+ * price counts: another signer of the account may use the same millisecond nonce.
340
+ */
341
+ async orderByClientNonce(clientNonce, signed) {
342
+ try {
343
+ const o = (await this.client.openOrders(this.owner)).find((x) => x.clientNonce === clientNonce && (!signed || matchesSigned({ pair_id: x.pairId, side: x.side, size: x.size18, price_8dec: x.price8 }, signed)));
344
+ if (o)
345
+ return { source: 'orders', ...o };
346
+ }
347
+ catch { /* not readable now */ }
348
+ try {
349
+ const e = (await this.client.orderRecords(this.owner)).find((x) => String(x.client_nonce) === String(clientNonce) && (!signed || matchesSigned(x, signed)));
350
+ if (e)
351
+ return { source: 'events', ...e };
352
+ }
353
+ catch { /* not readable now */ }
354
+ return null;
218
355
  }
219
356
  /**
220
357
  * Where the order with `clientNonce` stands, from the chain: `resting` while the book holds it, else what the account's
@@ -243,7 +380,41 @@ class Account {
243
380
  const signer = this.orderSigner();
244
381
  const id = (0, units_js_1.uint)(orderId, units_js_1.U64, 'orderId');
245
382
  const sig = await this.sign(signer, 'CancelOrder', { owner: this.owner, orderId: id });
246
- const r = await this.client.post('/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))));
383
+ // a cancel carries no nonce; cancelling an order twice cancels it once, so a lost answer sends the same body again.
384
+ // When an earlier copy may have arrived, the answer to a later one ("not found", a 5xx) is about that later copy:
385
+ // the account's resting orders decide.
386
+ const readBack = async (answer, attempts) => {
387
+ let rows = null;
388
+ try {
389
+ rows = await this.client.openOrders(this.owner);
390
+ }
391
+ catch {
392
+ rows = null;
393
+ }
394
+ if (!rows || rows.some((o) => BigInt(o.orderId) === id)) {
395
+ 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);
396
+ }
397
+ // not resting: the order's own records say whether the cancel or a fill closed it
398
+ const how = cancelOutcome(await this.client.orderRecords(this.owner).catch(() => []), id);
399
+ if (how === 'cancelled')
400
+ return { submitted: true, status: 0, refusal: null, actions: [], answer, done: true, attempts };
401
+ if (how === 'filled')
402
+ 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 };
403
+ return unknownResult(attempts, 'The order no longer rests: it closed (filled or cancelled). Check the fills and the position.', answer);
404
+ };
405
+ let r;
406
+ try {
407
+ 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))));
408
+ }
409
+ catch (e) {
410
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
411
+ throw e;
412
+ if (e.neverSent)
413
+ return { submitted: false, status: 0, refusal: { code: 'not_sent', message: e.message, detail: '', retryAfter: null }, actions: [], answer: null, attempts: e.attempts };
414
+ return readBack(null, e.attempts);
415
+ }
416
+ if (r.needsReadBack)
417
+ return readBack(r.body, r.attempts);
247
418
  return (0, orders_js_1.readAnswer)(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
248
419
  }
249
420
  /** Take-profit / stop-loss on an open position (8-decimal prices; 0 leaves a leg unset). */
@@ -262,9 +433,9 @@ class Account {
262
433
  if (actions.length < 1 || actions.length > max)
263
434
  throw new errors_js_1.InvalidRequest(`A batch holds 1 to ${max} actions, not ${actions.length}.`);
264
435
  actions = await this.onSteps(actions);
265
- const nonce = opts.nonce ?? this.nonce.next();
436
+ const nonce = opts.nonce ?? (await this.fresh('orders'));
266
437
  const sig = await this.sign(this.orderSigner(), 'BatchOrders', { owner: this.owner, nonce, actions });
267
- return { ...(await this.send('/order/batch-signed', (0, orders_js_1.batchBody)(this.owner, nonce, actions, sig))), nonce };
438
+ return { ...(await this.send('/order/batch-signed', (0, orders_js_1.batchBody)(this.owner, nonce, actions, sig), nonce)), nonce };
268
439
  }
269
440
  /**
270
441
  * The batch as it will be signed: every place action's price and size on its market's tick and lot (one rules read
@@ -286,10 +457,10 @@ class Account {
286
457
  }
287
458
  /** Cancel every open order on `pairId` (0 = every market). */
288
459
  async cancelAll(pairId = 0) {
289
- const nonce = this.nonce.next();
290
460
  const p = (0, units_js_1.safeNumber)((0, units_js_1.uint)(pairId, units_js_1.U32, 'pairId'), 'pairId');
461
+ const nonce = await this.fresh('orders');
291
462
  const sig = await this.sign(this.orderSigner(), 'CancelAllOrders', { owner: this.owner, pairId: p, nonce });
292
- return this.send('/order/cancel-all', (0, orders_js_1.cancelAllBody)(this.owner, p, nonce, sig));
463
+ return this.send('/order/cancel-all', (0, orders_js_1.cancelAllBody)(this.owner, p, nonce, sig), nonce);
293
464
  }
294
465
  /**
295
466
  * Cancel-and-replace at a new price and size (a new order id, no time priority). The new price and size go onto the
@@ -313,19 +484,38 @@ class Account {
313
484
  p = (0, rounding_js_1.snapPrice8)(p, spec, side);
314
485
  s = (0, rounding_js_1.snapSize18)(s, spec);
315
486
  (0, rounding_js_1.checkNotional)(s, p, spec);
316
- const clientNonce = this.nonce.next();
487
+ const clientNonce = await this.fresh('orders');
317
488
  const sig = await this.sign(this.orderSigner(), 'ModifyOrderV2', { owner: this.owner, orderId: id, newPrice: p, newSize: s, clientNonce });
318
- return { ...(await this.send('/order/modify', (0, orders_js_1.modifyBody)(this.owner, id, p, s, clientNonce, sig))), clientNonce };
489
+ return { ...(await this.send('/order/modify', (0, orders_js_1.modifyBody)(this.owner, id, p, s, clientNonce, sig), clientNonce)), clientNonce };
319
490
  }
320
491
  /**
321
492
  * The dead-man switch: at the first block at or past `cancelAtMs` the chain cancels every open order and TWAP of the
322
493
  * account. Call again with a later time to keep orders alive; 0 clears it.
323
494
  */
324
495
  async scheduleCancel(cancelAtMs) {
325
- const nonce = this.nonce.next();
326
496
  const at = (0, units_js_1.safeNumber)((0, units_js_1.uint)(cancelAtMs, units_js_1.U64, 'cancelAtMs'), 'cancelAtMs');
497
+ // above the switch's own last nonce (the chain refuses one that is not), like the account's other order nonces
498
+ const held = (await this.client.scheduleCancelState(this.owner).catch(() => null));
499
+ const floor = typeof held?.nonce === 'number' && Number.isSafeInteger(held.nonce) ? held.nonce + 1 : 0;
500
+ const nonce = await this.fresh('orders', undefined, floor);
327
501
  const sig = await this.sign(this.orderSigner(), 'ScheduleCancel', { owner: this.owner, cancelAtMs: at, nonce });
328
- return { ...(await this.send('/schedule-cancel', (0, orders_js_1.scheduleCancelBody)(this.owner, at, nonce, sig))), nonce };
502
+ // the network applies a ScheduleCancel nonce once (a second copy is refused): a lost answer sends the same body
503
+ // again, and a nonce answer to a resent copy counts only when the switch's committed state holds this nonce
504
+ try {
505
+ const r = await this.postSame('/schedule-cancel', JSON.stringify((0, orders_js_1.scheduleCancelBody)(this.owner, at, nonce, sig)), nonce, true);
506
+ if (r.needsReadBack) {
507
+ const st = (await this.client.scheduleCancelState(this.owner).catch(() => null));
508
+ if (st && String(st.nonce) === String(nonce))
509
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, attempts: r.attempts, unknown: false, alreadyReceived: true, nonce };
510
+ return { ...unknownResult(r.attempts, `An earlier copy may have arrived (its answer was lost) and the network answered ${r.status}; the switch does not show this nonce. Read it before sending a new one.`, r.body), alreadyReceived: false, nonce };
511
+ }
512
+ return { ...(0, orders_js_1.readAnswer)(r.status, r.body, r.retryAfter, this.client.refusalMeanings()), attempts: r.attempts, unknown: false, alreadyReceived: false, nonce };
513
+ }
514
+ catch (e) {
515
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
516
+ throw e;
517
+ return { ...unknownResult(e.attempts, e.message, null), alreadyReceived: false, nonce };
518
+ }
329
519
  }
330
520
  // ── session key ───────────────────────────────────────────────────────────────────────────────────────────────────
331
521
  async revokeSession(waitMs = 30000) {
@@ -333,11 +523,10 @@ class Account {
333
523
  const held = await this.client.session(this.owner);
334
524
  if (!held)
335
525
  return { applied: true, status: 0, answer: null, detail: 'no session to revoke' };
336
- const n = (0, account_js_1.nextNonce)();
526
+ const n = await this.fresh('account');
337
527
  const sig = await this.sign(signer, 'SessionRevoke', { owner: this.owner, nonce: n });
338
- const r = await this.client.post('/session/revoke', (0, account_js_1.sessionRevokeBody)(this.owner, held.session_key, n, sig));
339
- const ok = r.status >= 200 && r.status < 300 && (await waitFor(async () => (await this.client.session(this.owner)) === null, waitMs));
340
- return { applied: ok, status: r.status, answer: r.body, detail: ok ? '' : 'the chain still holds the session' };
528
+ const r = await this.postForResult('/session/revoke', (0, account_js_1.sessionRevokeBody)(this.owner, held.session_key, n, sig));
529
+ return outcome(r, async () => (await this.client.session(this.owner)) === null, waitMs, 'the chain still holds the session');
341
530
  }
342
531
  /**
343
532
  * Give `sessionKey` (a session key, or a registered agent's key) this account's session until `endMs`. A session the
@@ -347,19 +536,16 @@ class Account {
347
536
  const signer = this.needOwner('A session');
348
537
  const key = (0, ethers_1.getAddress)(sessionKey);
349
538
  const held = await this.client.session(this.owner);
350
- let after = 0;
351
539
  if (held && held.session_key.toLowerCase() !== key.toLowerCase()) {
352
540
  const r = await this.revokeSession();
353
- if (!r.applied)
354
- return { ...r, applied: false, detail: "the account's other session could not be ended" };
355
- after = (0, account_js_1.nextNonce)();
541
+ if (r.applied !== true)
542
+ return { ...r, detail: "the account's other session could not be ended" + (r.applied === null ? ' (not known yet)' : '') };
356
543
  }
357
- const n = (0, account_js_1.nextNonce)(after), exp = (0, account_js_1.sessionEnd)(endMs);
544
+ const n = await this.fresh('account'), exp = (0, account_js_1.sessionEnd)(endMs);
358
545
  const sig = await this.sign(signer, 'SessionCreate', { sessionKey: key, expiresAt: exp, nonce: n });
359
- const r = await this.client.post('/session/create', (0, account_js_1.sessionCreateBody)(this.owner, key, exp, n, sig));
546
+ const r = await this.postForResult('/session/create', (0, account_js_1.sessionCreateBody)(this.owner, key, exp, n, sig));
360
547
  const mine = async () => { const s = await this.client.session(this.owner); return !!s && s.session_key.toLowerCase() === key.toLowerCase() && s.confirmed === true; };
361
- const ok = r.status >= 200 && r.status < 300 && (await waitFor(mine, waitMs));
362
- return { applied: ok, status: r.status, answer: r.body, detail: ok ? '' : 'the chain does not show the session as confirmed' };
548
+ return outcome(r, mine, waitMs, 'the chain does not show the session as confirmed');
363
549
  }
364
550
  // ── TWAP (owner key only) ─────────────────────────────────────────────────────────────────────────────────────────
365
551
  async placeTwap(t, waitMs = 30000) {
@@ -370,26 +556,27 @@ class Account {
370
556
  throw new errors_js_1.InvalidRequest("The slippage is above the network's TWAP limit.");
371
557
  const numSlices = t.numSlices ?? (0, account_js_1.planTwap)(t.durationMs, rules)[0];
372
558
  const [total, lo, hi] = twapOnSteps(await this.pairSpec(t.pairId), (0, units_js_1.uint)(t.totalSize18, units_js_1.U128, 'totalSize18'), numSlices, t.minPrice8 ?? 0n, t.maxPrice8 ?? 0n);
373
- const clientNonce = (0, account_js_1.nextNonce)();
559
+ const clientNonce = await this.fresh('orders');
374
560
  const v = {
375
561
  owner: this.owner, pairId: t.pairId, side: t.side === 'buy' ? 0 : 1, totalSize18dec: total,
376
562
  numSlices, durationMs: t.durationMs, leverageBps: t.leverageBps ?? 10000, slippageBps: slip,
377
563
  randomize: !!t.randomize, triggerPrice8dec: 0n, triggerDir: 0, minPrice8dec: lo, maxPrice8dec: hi, clientNonce,
378
564
  };
379
565
  const sig = await this.sign(signer, 'PlaceTwap', v);
380
- const r = await this.client.post(rules.path, (0, account_js_1.twapBody)(v, sig));
381
- const ok = r.status >= 200 && r.status < 300 && (await waitFor(async () => (await this.client.twaps(this.owner)).some((x) => String(x.client_nonce) === String(clientNonce)), waitMs));
382
- return { applied: ok, status: r.status, answer: r.body, detail: ok ? '' : 'the chain does not list the TWAP', clientNonce };
566
+ const r = await this.postForResult(rules.path, (0, account_js_1.twapBody)(v, sig));
567
+ // the nonce AND what was signed, among the live TWAPs or the ended ones (the account's twap_* records)
568
+ const held = async () => (await this.client.twaps(this.owner)).some((x) => twapMatches(x, v))
569
+ || (await this.client.orderRecords(this.owner)).some((e) => String(e.kind ?? '').startsWith('twap') && twapMatches(e, v));
570
+ return { ...(await outcome(r, held, waitMs, 'the chain does not list the TWAP')), clientNonce };
383
571
  }
384
572
  async cancelTwap(twapId, waitMs = 30000) {
385
573
  const signer = this.needOwner('Cancelling a TWAP');
386
574
  const rules = this.client.twapRules();
387
- const cn = (0, account_js_1.nextNonce)();
575
+ const cn = await this.fresh('orders');
388
576
  const sig = await this.sign(signer, 'CancelTwap', { owner: this.owner, twapId: (0, units_js_1.uint)(twapId, units_js_1.U64, 'twapId'), clientNonce: cn });
389
- const r = await this.client.post(rules.cancelPath, (0, account_js_1.cancelTwapBody)(this.owner, twapId, cn, sig));
577
+ const r = await this.postForResult(rules.cancelPath, (0, account_js_1.cancelTwapBody)(this.owner, twapId, cn, sig));
390
578
  const gone = async () => (await this.client.twaps(this.owner)).every((x) => String(x.twap_id ?? x.id) !== String(twapId));
391
- const ok = r.status >= 200 && r.status < 300 && (await waitFor(gone, waitMs));
392
- return { applied: ok, status: r.status, answer: r.body, detail: ok ? '' : 'the chain still lists the TWAP' };
579
+ return outcome(r, gone, waitMs, 'the chain still lists the TWAP');
393
580
  }
394
581
  // ── margin mode (owner key only) ──────────────────────────────────────────────────────────────────────────────────
395
582
  /** The market's margin mode as the chain reads it ("cross" | "isolated"), or null. */
@@ -406,19 +593,17 @@ class Account {
406
593
  const signer = this.needOwner('The margin mode');
407
594
  if (!(mode in account_js_1.MODE_CODE))
408
595
  throw new errors_js_1.InvalidRequest('The mode is cross or isolated.');
409
- const n = (0, account_js_1.nextNonce)();
596
+ const n = await this.fresh('account');
410
597
  const sig = await this.sign(signer, 'SetMarginMode', { owner: this.owner, pairId, mode: account_js_1.MODE_CODE[mode], nonce: n });
411
- const r = await this.client.post('/margin/mode', (0, account_js_1.marginModeBody)(this.owner, pairId, account_js_1.MODE_CODE[mode], n, sig));
412
- const ok = r.status === 202 && (await waitFor(async () => (await this.marginMode(pairId)) === mode, waitMs));
413
- return { applied: ok, status: r.status, answer: r.body, detail: ok ? '' : 'the chain does not show the new mode' };
598
+ const r = await this.postForResult('/margin/mode', (0, account_js_1.marginModeBody)(this.owner, pairId, account_js_1.MODE_CODE[mode], n, sig), false);
599
+ return outcome(r, async () => (await this.marginMode(pairId)) === mode, waitMs, 'the chain does not show the new mode');
414
600
  }
415
601
  // ── agents (owner key; the agent may tighten its own policy) ──────────────────────────────────────────────────────
416
602
  async submitAgentOp(signer, op, value, shows, agent, waitMs) {
417
603
  const sig = await this.sign(signer, op, value);
418
604
  const body = (0, agents_js_1.submitBody)(op, value, sig);
419
- const r = await this.client.post('/submit', JSON.stringify(body));
420
- const ok = r.status >= 200 && r.status < 300 && (await waitFor(async () => shows(await this.client.agent(this.owner, agent)), waitMs));
421
- return { applied: ok, status: r.status, answer: r.body, detail: ok ? '' : 'the chain does not show the change' };
605
+ const r = await this.postForResult('/submit', JSON.stringify(body));
606
+ return outcome(r, async () => shows(await this.client.agent(this.owner, agent)), waitMs, 'the chain does not show the change');
422
607
  }
423
608
  addr(a, op) {
424
609
  const c = (0, ethers_1.getAddress)(a);
@@ -428,7 +613,7 @@ class Account {
428
613
  async registerAgent(a, waitMs = 30000) {
429
614
  const signer = this.needOwner('Registering an agent');
430
615
  const op = 'RegisterAgentV2';
431
- 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: (0, account_js_1.nextNonce)() };
616
+ 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') };
432
617
  return this.submitAgentOp(signer, op, value, (rec) => !!rec && rec.status === 'active' && rec.name === value.name, value.agent, waitMs);
433
618
  }
434
619
  /**
@@ -439,7 +624,7 @@ class Account {
439
624
  async renameAgent(agent, name, waitMs = 30000) {
440
625
  const signer = this.needOwner('Renaming an agent');
441
626
  const op = 'SetAgentName';
442
- const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), name: (0, agents_js_1.requireName)(name), nonce: (0, account_js_1.nextNonce)() };
627
+ const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), name: (0, agents_js_1.requireName)(name), nonce: await this.fresh('account') };
443
628
  const rec = await this.client.agent(this.owner, value.agent);
444
629
  const named = typeof rec?.named_at_ms === 'number' ? rec.named_at_ms : null;
445
630
  const wait = this.client.renameWaitMs();
@@ -454,7 +639,7 @@ class Account {
454
639
  async revokeAgent(agent, waitMs = 30000) {
455
640
  const signer = this.needOwner('Revoking an agent');
456
641
  const op = 'RevokeAgent';
457
- const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), nonce: (0, account_js_1.nextNonce)() };
642
+ const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), nonce: await this.fresh('account') };
458
643
  return this.submitAgentOp(signer, op, value, (rec) => !!rec && rec.status === 'revoked', value.agent, waitMs);
459
644
  }
460
645
  /**
@@ -480,7 +665,7 @@ class Account {
480
665
  if (wider.length)
481
666
  throw new errors_js_1.InvalidRequest(`An agent may only tighten its own policy; this ${wider.join(', ')} — only the owner may sign that.`);
482
667
  }
483
- const value = (0, agents_js_1.policyValue)(this.addr(this.owner, op), agentAddr, policy, (0, account_js_1.nextNonce)());
668
+ const value = (0, agents_js_1.policyValue)(this.addr(this.owner, op), agentAddr, policy, await this.fresh('account', (0, ethers_1.getAddress)(await signer.getAddress())));
484
669
  const same = (rec) => {
485
670
  const p = (0, agents_js_1.policyFromRead)(rec?.policy_v1);
486
671
  return !!p && JSON.stringify(p, (_, x) => (typeof x === 'bigint' ? x.toString() : x)) === JSON.stringify(policy, (_, x) => (typeof x === 'bigint' ? x.toString() : x));
@@ -492,7 +677,7 @@ class Account {
492
677
  const signer = this.needOwner("An agent's market limit");
493
678
  const op = 'SetAgentMarketLimit';
494
679
  const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), pair: m.pair, allowed: m.allowed,
495
- maxOrder18dec: (0, units_js_1.uint)(m.maxOrder18, units_js_1.U128, 'maxOrder18'), maxPosition18dec: (0, units_js_1.uint)(m.maxPosition18, units_js_1.U128, 'maxPosition18'), maxLeverageBps: m.maxLeverageBps, nonce: (0, account_js_1.nextNonce)() };
680
+ maxOrder18dec: (0, units_js_1.uint)(m.maxOrder18, units_js_1.U128, 'maxOrder18'), maxPosition18dec: (0, units_js_1.uint)(m.maxPosition18, units_js_1.U128, 'maxPosition18'), maxLeverageBps: m.maxLeverageBps, nonce: await this.fresh('account') };
496
681
  const shows = (rec) => (Array.isArray(rec?.market_limits) ? rec.market_limits : [])
497
682
  .some((l) => l.pair === m.pair && l.allowed === m.allowed && String(l.max_order_18dec) === value.maxOrder18dec.toString() && String(l.max_position_18dec) === value.maxPosition18dec.toString());
498
683
  return this.submitAgentOp(signer, op, value, shows, value.agent.toLowerCase(), waitMs);
@@ -503,7 +688,7 @@ class Account {
503
688
  if (!Number.isSafeInteger(lockSinceMs) || lockSinceMs <= 0)
504
689
  throw new errors_js_1.InvalidRequest('lockSinceMs is the start of the active lock (from the agent read).');
505
690
  const op = 'ClearAgentLock';
506
- const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), lockSinceMs, nonce: (0, account_js_1.nextNonce)() };
691
+ const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), lockSinceMs, nonce: await this.fresh('account') };
507
692
  const shows = (rec) => rec?.risk_v1?.lock_active === false;
508
693
  return this.submitAgentOp(signer, op, value, shows, value.agent, waitMs);
509
694
  }
@@ -524,3 +709,81 @@ function twapOnSteps(spec, total18, numSlices, minPrice8, maxPrice8) {
524
709
  throw new rounding_js_1.OrderValueError("The TWAP's price band holds no tick of this market.");
525
710
  return [total, lo, hi];
526
711
  }
712
+ const asBig = (v) => {
713
+ if (typeof v === 'bigint')
714
+ return v;
715
+ if (typeof v === 'number' && Number.isSafeInteger(v))
716
+ return BigInt(v);
717
+ if (typeof v === 'string' && /^\d+$/.test(v.trim()))
718
+ return BigInt(v.trim());
719
+ return null;
720
+ };
721
+ /**
722
+ * Whether an order record carries what was signed: its market and side, and its size or limit price. A field the
723
+ * record does not show is not counted; one it shows with another value is a mismatch; a record that shows neither size
724
+ * nor price is not enough.
725
+ */
726
+ function matchesSigned(rec, signed) {
727
+ const pair = asBig(rec.pair_id ?? rec.pairId);
728
+ if (pair === null || pair !== BigInt(signed.pairId))
729
+ return false;
730
+ const sd = String(rec.side ?? '').trim().toLowerCase();
731
+ const side = ['0', 'buy', 'b', 'long'].includes(sd) ? 0 : ['1', 'sell', 's', 'short'].includes(sd) ? 1 : null;
732
+ if (side === null || side !== signed.side)
733
+ return false;
734
+ let shown = 0;
735
+ for (const k of ['original_size_18dec', 'size_18dec', 'size']) { // a partly filled order's left-over size never matches: unknown
736
+ const v = asBig(rec[k]);
737
+ if (v !== null) {
738
+ if (v !== signed.size)
739
+ return false;
740
+ shown++;
741
+ break;
742
+ }
743
+ }
744
+ if (signed.price !== null) {
745
+ const v = asBig(rec.price_8dec);
746
+ if (v !== null) {
747
+ if (v !== signed.price)
748
+ return false;
749
+ shown++;
750
+ }
751
+ }
752
+ return shown > 0;
753
+ }
754
+ /** Whether a TWAP the chain lists is the one signed: its client nonce, market, side and total size. */
755
+ function twapMatches(row, v) {
756
+ if (String(row.client_nonce) !== String(v.clientNonce))
757
+ return false;
758
+ const checks = [[row.pair_id, BigInt(v.pairId)], [row.total_size_18dec ?? row.total_size, BigInt(v.totalSize18dec)]];
759
+ for (const [got, want] of checks) {
760
+ const g = asBig(got);
761
+ if (g !== null && g !== want)
762
+ return false;
763
+ }
764
+ if (row.side !== undefined && row.side !== null) {
765
+ const sd = String(row.side).toLowerCase();
766
+ const side = /^\d+$/.test(sd) ? Number(sd) : { buy: 0, b: 0, long: 0, sell: 1, s: 1, short: 1 }[sd] ?? -1;
767
+ if (side !== v.side)
768
+ return false;
769
+ }
770
+ return true;
771
+ }
772
+ function unknownResult(attempts, message, answer) {
773
+ return { submitted: false, status: 0, refusal: { code: 'delivery_unknown', message, detail: '', retryAfter: null }, actions: [], answer, attempts, unknown: true };
774
+ }
775
+ /** How an order that is not resting was closed, from the account's records: `cancelled`, `filled`, or null. */
776
+ function cancelOutcome(records, orderId) {
777
+ const mine = records.filter((e) => String(e.order_id ?? e.orderId ?? e.id) === orderId.toString());
778
+ for (const e of mine) {
779
+ const kind = String(e.kind ?? '').toLowerCase(), st = String(e.status ?? '').toLowerCase();
780
+ if (kind === 'order_cancelled' || (kind === 'order_closed' && st === 'cancelled'))
781
+ return 'cancelled';
782
+ }
783
+ for (const e of mine) {
784
+ const kind = String(e.kind ?? '').toLowerCase(), st = String(e.status ?? '').toLowerCase();
785
+ if (kind === 'fill' || kind === 'order_filled' || (kind === 'order_closed' && st === 'filled'))
786
+ return 'filled';
787
+ }
788
+ return null;
789
+ }