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