@vordium/sdk 0.1.2 → 0.2.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.
@@ -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,26 @@ 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
+ const builder_js_1 = require("./builder.js");
25
+ /** The result of an account write by the chain's own read: applied, refused, or not known yet. */
26
+ async function outcome(r, shows, waitMs, notShown) {
27
+ if (!r.proceed) {
28
+ const notSent = r.body?.status === 'not_sent';
29
+ return { applied: false, status: r.status, answer: r.body, detail: notSent ? 'the network could not be reached: nothing was sent' : 'the network refused it' };
30
+ }
31
+ if (await waitFor(shows, waitMs))
32
+ return { applied: true, status: r.status, answer: r.body, detail: '' };
33
+ return { applied: null, unknown: true, status: r.status, answer: r.body, detail: `${notShown} yet; it may still apply: read the account again before sending it anew` };
34
+ }
19
35
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
20
36
  /** Read the chain until `fn` is true or `ms` runs out. A failed read counts as "not yet". */
21
37
  async function waitFor(fn, ms, stepMs = 1000) {
@@ -38,32 +54,50 @@ class Vordium {
38
54
  timeoutMs;
39
55
  ttlMs;
40
56
  checkedAt = Date.now();
41
- constructor(network, transport, timeoutMs, ttlMs) {
57
+ /** The network's block time for the nonce window check; null checks against this computer's clock. */
58
+ chainClock;
59
+ constructor(network, transport, timeoutMs, ttlMs, chainClock) {
42
60
  this.network = network;
43
61
  this.transport = transport;
44
62
  this.timeoutMs = timeoutMs;
45
63
  this.ttlMs = ttlMs;
46
- }
64
+ this.chainClock = chainClock ? new resend_js_1.ChainClock(async () => {
65
+ 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));
66
+ const res = r.body?.result;
67
+ return res && typeof res === 'object' ? res : null;
68
+ }, async () => {
69
+ const st = await this.transport.get(this.network.api + '/status', Math.min(this.timeoutMs, 2000));
70
+ const h = st.status === 200 ? st.body?.chain_head : null;
71
+ return typeof h === 'number' && Number.isSafeInteger(h) ? h : null;
72
+ }) : null;
73
+ }
74
+ /** The network's block time now (ms), estimated from its latest block; null when it cannot be read. */
75
+ async chainTimeMs() { return this.chainClock ? this.chainClock.time() : null; }
47
76
  /** Read and check the network (spec, node and JSON-RPC must agree) and return a client for it. Testnet by default. */
48
77
  static async connect(opts = {}) {
49
78
  const transport = opts.transport ?? http_js_1.fetchTransport;
50
79
  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);
80
+ const net = await (0, network_js_1.connectNetwork)(opts.network ?? 'testnet', { transport, timeoutMs, onPinProblem: opts.onPinProblem });
81
+ return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000, opts.chainClock ?? opts.transport === undefined);
53
82
  }
54
83
  /**
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.
84
+ * The signing domain of the node this client posts to, built from the network's pin (`PINS`) after the network's
85
+ * reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
86
+ * chain is refused, never followed.
57
87
  */
58
88
  async domain(cls) {
89
+ const pin = (0, network_js_1.signingPin)(this.network);
59
90
  if (Date.now() - this.checkedAt >= this.ttlMs) {
60
91
  const id = await (0, network_js_1.nodeIdentity)(this.network.api, this.transport, this.timeoutMs);
92
+ const d = (0, pins_js_1.pinDifferences)(pin, { "the node's /status": id.chainId }, { "the node's /status": id.genesis });
93
+ if (d.length)
94
+ throw new pins_js_1.PinMismatch((0, pins_js_1.pinRefusal)(pin, d));
61
95
  if (id.chainId !== this.network.chainId || id.genesis !== this.network.genesis) {
62
96
  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
97
  }
64
98
  this.checkedAt = Date.now();
65
99
  }
66
- return (0, domains_js_1.domain)(cls, this.network.chainId, this.network.genesis);
100
+ return (0, domains_js_1.domain)(cls, pin.chainId, pin.genesis);
67
101
  }
68
102
  // ── reads ─────────────────────────────────────────────────────────────────────────────────────────────────────────
69
103
  /** GET a path of the REST API; null on 404, raises on another failure. */
@@ -144,17 +178,43 @@ class Vordium {
144
178
  crossMargin(owner) { return this.get(`/account/cross/${owner}`); }
145
179
  /** The dead-man switch's committed state and limits. */
146
180
  scheduleCancelState(owner) { return this.get(`/schedule-cancel/${owner}`); }
181
+ // ── builder codes and referral levels ───────────────────────────────────────────────────────────────────────────
182
+ /** `GET /builder/approvals/<user>`: the builders `user` approved, the count, the most allowed, its nonce, `active`. */
183
+ async builderApprovals(user) {
184
+ const j = await this.get(`/builder/approvals/${builderAddress(user)}`);
185
+ if (!j || typeof j !== 'object')
186
+ throw new builder_js_1.BuilderNotActive('The network does not answer the builder approvals read, so nothing was signed.');
187
+ return j;
188
+ }
189
+ /** `GET /builder/stats/<builder>`: volume, fees (= unclaimed + claimed), users in 30 days, caps, claim nonce, `active`. */
190
+ async builderStats(builder) {
191
+ const j = await this.get(`/builder/stats/${builderAddress(builder)}`);
192
+ if (!j || typeof j !== 'object')
193
+ throw new builder_js_1.BuilderNotActive('The network does not answer the builder stats read, so nothing was signed.');
194
+ return j;
195
+ }
196
+ /** `GET /referral/stats/<address>` as the network answers it. */
197
+ referralStats(address) { return this.get(`/referral/stats/${(0, ethers_1.getAddress)(address)}`); }
198
+ /** The account's referral level (`L1`, `L2`, `PARTNER`) and its period progress; null where levels are not shown. */
199
+ async referralLevel(address) { return (0, builder_js_1.referralLevel)(await this.referralStats(address)); }
200
+ /** `GET /referral/tiers`: the levels table, the L2 rule, the partner bounds and the referee caps. */
201
+ referralTiers() { return this.get('/referral/tiers'); }
202
+ /** The network's block time in whole seconds, else this computer's clock. */
203
+ async nowS() {
204
+ const ms = await this.chainTimeMs().catch(() => null);
205
+ return Math.floor((typeof ms === 'number' && ms > 0 ? ms : Date.now()) / 1000);
206
+ }
147
207
  /** The TWAP route and limits from the network spec (refused when not published). */
148
208
  twapRules() { return (0, account_js_1.readTwapRules)(this.network.specRead); }
149
209
  /** A trading account: `owner` signs account operations; `sessionSigner` (a session or agent key) signs orders. */
150
210
  async account(owner, opts = {}) {
151
211
  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));
212
+ 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
213
  }
154
214
  /** An agent's own handle: places orders with the agent key for its owner, and may tighten its own policy. */
155
215
  async agentKey(owner, agentSigner, opts = {}) {
156
216
  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));
217
+ 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
218
  }
159
219
  }
160
220
  exports.Vordium = Vordium;
@@ -166,7 +226,9 @@ class Account {
166
226
  sessionSigner;
167
227
  nonce;
168
228
  specs;
169
- constructor(client, owner, ownerSigner, sessionSigner, nonce,
229
+ constructor(client, owner, ownerSigner, sessionSigner,
230
+ /** The account's client-nonce source: its persisted allocator in the `orders` space by default. */
231
+ nonce,
170
232
  /** Market rules this handle holds; null = read them from the node for each order. */
171
233
  specs = null) {
172
234
  this.client = client;
@@ -195,9 +257,62 @@ class Account {
195
257
  async sign(signer, primary, value) {
196
258
  return (0, sign_js_1.signOp)(signer, await this.client.domain((0, types_js_1.domainOf)(primary)), primary, value);
197
259
  }
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());
260
+ /**
261
+ * A fresh nonce, checked against the network's window before anything is signed ({@link ClockOutOfWindow} otherwise):
262
+ * the account's client nonce (`orders`), or the `account` nonce of `signer` (session, margin mode, agent operations).
263
+ */
264
+ async fresh(space = 'orders', signer, floor = 0) {
265
+ const src = space === 'orders' ? this.nonce : (0, nonce_js_1.nonceAllocator)(signer ?? this.owner, 'account');
266
+ if (src instanceof nonce_js_1.NonceAllocator)
267
+ return src.next(floor, await this.client.chainTimeMs());
268
+ return src.next(floor);
269
+ }
270
+ /**
271
+ * POST one signed body, the same bytes on every try. With `dedup` (a write the network applies once per nonce) a lost
272
+ * connection, a timeout or a busy gateway sends it again (never a new nonce); without it only a copy that never left
273
+ * this machine is sent again, and a lost answer throws {@link DeliveryUnknown}.
274
+ */
275
+ async postSame(path, body, nonce = null, dedup = true) {
276
+ return (0, resend_js_1.sendSame)(() => this.client.post(path, body), { nonce, dedup });
277
+ }
278
+ /**
279
+ * An account operation, for a result the chain's own read decides: `proceed` is true when the network took it (2xx),
280
+ * or when it is not known whether it arrived (then the read-back alone says whether it applied).
281
+ */
282
+ async postForResult(path, body, dedup = true) {
283
+ try {
284
+ const s = await this.postSame(path, body, null, dedup);
285
+ if (s.needsReadBack)
286
+ return { status: s.status, body: { status: 'unknown', answer: s.body }, proceed: true };
287
+ return { status: s.status, body: s.body, proceed: s.status >= 200 && s.status < 300 };
288
+ }
289
+ catch (e) {
290
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
291
+ throw e;
292
+ if (e.neverSent)
293
+ return { status: 0, body: { status: 'not_sent', detail: e.message }, proceed: false }; // nothing left this machine
294
+ return { status: 0, body: { status: 'unknown', detail: e.message }, proceed: true };
295
+ }
296
+ }
297
+ /**
298
+ * A write the network does not apply once per nonce (batch, cancel-all, modify, take-profit / stop-loss): never sent
299
+ * again after a lost answer. Unknown is `submitted: false, unknown: true` with the refusal `delivery_unknown`: read the
300
+ * account before sending a new one.
301
+ */
302
+ async send(path, body, nonce = null, dedup = false) {
303
+ try {
304
+ const s = await this.postSame(path, typeof body === 'string' ? body : JSON.stringify(body), nonce, dedup);
305
+ if (s.needsReadBack)
306
+ 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);
307
+ return { ...(0, orders_js_1.readAnswer)(s.status, s.body, s.retryAfter, this.client.refusalMeanings()), attempts: s.attempts, unknown: false };
308
+ }
309
+ catch (e) {
310
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
311
+ throw e;
312
+ if (e.neverSent)
313
+ return { submitted: false, status: 0, refusal: { code: 'not_sent', message: e.message, detail: '', retryAfter: null }, actions: [], answer: null, attempts: e.attempts, unknown: false };
314
+ return unknownResult(e.attempts, e.message, null);
315
+ }
201
316
  }
202
317
  // ── orders ────────────────────────────────────────────────────────────────────────────────────────────────────────
203
318
  /**
@@ -207,14 +322,77 @@ class Account {
207
322
  */
208
323
  async placeOrder(o) {
209
324
  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));
213
- const sig = await this.sign(signer, 'PlaceOrder', v);
214
- 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));
325
+ const { builder: wanted, worstPrice, ...plain } = o;
326
+ if (worstPrice != null && (wanted == null || o.orderType !== 'Market'))
327
+ throw new errors_js_1.InvalidRequest('worstPrice applies to a market order that names a builder.');
328
+ (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
329
+ const ob = wanted == null ? null : await this.checkedBuilder(wanted); // null or undefined: no builder
330
+ const spec = await this.pairSpec(o.pairId);
331
+ const clientNonce = o.clientNonce ?? (await this.fresh('orders'));
332
+ const v = (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce }, spec);
333
+ let body;
334
+ if (ob) {
335
+ // a buy's cap rounds down onto the price step and a sell's floor up: never worse than the caller gave
336
+ const worst8 = worstPrice == null ? 0n : (0, rounding_js_1.price8OnTick)(worstPrice, spec, o.side, true);
337
+ const v3 = (0, builder_js_1.placeOrderV3Value)(v, (0, builder_js_1.deadline)(null, await this.client.nowS()), ob, undefined, worst8);
338
+ body = (0, builder_js_1.placeOrderV3Body)(v3, await this.sign(signer, 'PlaceOrderV3', v3));
339
+ }
340
+ else {
341
+ const sig = await this.sign(signer, 'PlaceOrder', v);
342
+ body = (0, orders_js_1.placeOrderBody)(v, (0, ethers_1.getAddress)(await signer.getAddress()), (0, sign_js_1.rs64)(sig));
343
+ }
344
+ const withBuilder = ob ? { builder: ob } : {};
345
+ const signed = { pairId: v.pairId, side: v.side, size: v.size, price: v.orderType === 1 ? v.price : null };
346
+ // after the mark was set back to the clock, a nonce may repeat one handed out before: a read-back must be newer
347
+ const rewound = this.nonce instanceof nonce_js_1.NonceAllocator ? await this.nonce.rewoundBefore(clientNonce) : null;
348
+ const ours = (f) => {
349
+ if (!f || rewound === null)
350
+ return f;
351
+ const ts = [f.timestampMs, f.timestamp_ms, f.ts_ms].find((x) => typeof x === 'number');
352
+ return ts !== undefined && ts > rewound ? f : null;
353
+ };
354
+ let r;
355
+ try {
356
+ r = await this.postSame('/order/place', JSON.stringify(body), clientNonce);
357
+ }
358
+ catch (e) {
359
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
360
+ throw e;
361
+ const found = ours(await this.orderByClientNonce(clientNonce, signed));
362
+ if (!found)
363
+ throw e;
364
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
365
+ }
366
+ if (r.needsReadBack) {
367
+ // the network's nonce code means "used" (perhaps by our earlier copy), "outside the window", or "used by another
368
+ // signer": it is ours only when the order the network lists carries what was signed
369
+ const found = ours(await this.orderByClientNonce(clientNonce, signed));
370
+ if (found)
371
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
372
+ 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 };
373
+ }
216
374
  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 };
375
+ return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false, ...withBuilder };
376
+ }
377
+ /**
378
+ * The account's order with `clientNonce` as the network lists it: resting (open orders), else its record; null when
379
+ * it lists neither (or cannot be read). With `signed`, only an order that carries the signed market, side and size or
380
+ * price counts: another signer of the account may use the same millisecond nonce.
381
+ */
382
+ async orderByClientNonce(clientNonce, signed) {
383
+ try {
384
+ 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)));
385
+ if (o)
386
+ return { source: 'orders', ...o };
387
+ }
388
+ catch { /* not readable now */ }
389
+ try {
390
+ const e = (await this.client.orderRecords(this.owner)).find((x) => String(x.client_nonce) === String(clientNonce) && (!signed || matchesSigned(x, signed)));
391
+ if (e)
392
+ return { source: 'events', ...e };
393
+ }
394
+ catch { /* not readable now */ }
395
+ return null;
218
396
  }
219
397
  /**
220
398
  * Where the order with `clientNonce` stands, from the chain: `resting` while the book holds it, else what the account's
@@ -243,7 +421,41 @@ class Account {
243
421
  const signer = this.orderSigner();
244
422
  const id = (0, units_js_1.uint)(orderId, units_js_1.U64, 'orderId');
245
423
  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))));
424
+ // a cancel carries no nonce; cancelling an order twice cancels it once, so a lost answer sends the same body again.
425
+ // When an earlier copy may have arrived, the answer to a later one ("not found", a 5xx) is about that later copy:
426
+ // the account's resting orders decide.
427
+ const readBack = async (answer, attempts) => {
428
+ let rows = null;
429
+ try {
430
+ rows = await this.client.openOrders(this.owner);
431
+ }
432
+ catch {
433
+ rows = null;
434
+ }
435
+ if (!rows || rows.some((o) => BigInt(o.orderId) === id)) {
436
+ 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);
437
+ }
438
+ // not resting: the order's own records say whether the cancel or a fill closed it
439
+ const how = cancelOutcome(await this.client.orderRecords(this.owner).catch(() => []), id);
440
+ if (how === 'cancelled')
441
+ return { submitted: true, status: 0, refusal: null, actions: [], answer, done: true, attempts };
442
+ if (how === 'filled')
443
+ 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 };
444
+ return unknownResult(attempts, 'The order no longer rests: it closed (filled or cancelled). Check the fills and the position.', answer);
445
+ };
446
+ let r;
447
+ try {
448
+ 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))));
449
+ }
450
+ catch (e) {
451
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
452
+ throw e;
453
+ if (e.neverSent)
454
+ return { submitted: false, status: 0, refusal: { code: 'not_sent', message: e.message, detail: '', retryAfter: null }, actions: [], answer: null, attempts: e.attempts };
455
+ return readBack(null, e.attempts);
456
+ }
457
+ if (r.needsReadBack)
458
+ return readBack(r.body, r.attempts);
247
459
  return (0, orders_js_1.readAnswer)(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
248
460
  }
249
461
  /** Take-profit / stop-loss on an open position (8-decimal prices; 0 leaves a leg unset). */
@@ -262,9 +474,9 @@ class Account {
262
474
  if (actions.length < 1 || actions.length > max)
263
475
  throw new errors_js_1.InvalidRequest(`A batch holds 1 to ${max} actions, not ${actions.length}.`);
264
476
  actions = await this.onSteps(actions);
265
- const nonce = opts.nonce ?? this.nonce.next();
477
+ const nonce = opts.nonce ?? (await this.fresh('orders'));
266
478
  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 };
479
+ return { ...(await this.send('/order/batch-signed', (0, orders_js_1.batchBody)(this.owner, nonce, actions, sig), nonce)), nonce };
268
480
  }
269
481
  /**
270
482
  * 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 +498,10 @@ class Account {
286
498
  }
287
499
  /** Cancel every open order on `pairId` (0 = every market). */
288
500
  async cancelAll(pairId = 0) {
289
- const nonce = this.nonce.next();
290
501
  const p = (0, units_js_1.safeNumber)((0, units_js_1.uint)(pairId, units_js_1.U32, 'pairId'), 'pairId');
502
+ const nonce = await this.fresh('orders');
291
503
  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));
504
+ return this.send('/order/cancel-all', (0, orders_js_1.cancelAllBody)(this.owner, p, nonce, sig), nonce);
293
505
  }
294
506
  /**
295
507
  * 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 +525,38 @@ class Account {
313
525
  p = (0, rounding_js_1.snapPrice8)(p, spec, side);
314
526
  s = (0, rounding_js_1.snapSize18)(s, spec);
315
527
  (0, rounding_js_1.checkNotional)(s, p, spec);
316
- const clientNonce = this.nonce.next();
528
+ const clientNonce = await this.fresh('orders');
317
529
  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 };
530
+ return { ...(await this.send('/order/modify', (0, orders_js_1.modifyBody)(this.owner, id, p, s, clientNonce, sig), clientNonce)), clientNonce };
319
531
  }
320
532
  /**
321
533
  * The dead-man switch: at the first block at or past `cancelAtMs` the chain cancels every open order and TWAP of the
322
534
  * account. Call again with a later time to keep orders alive; 0 clears it.
323
535
  */
324
536
  async scheduleCancel(cancelAtMs) {
325
- const nonce = this.nonce.next();
326
537
  const at = (0, units_js_1.safeNumber)((0, units_js_1.uint)(cancelAtMs, units_js_1.U64, 'cancelAtMs'), 'cancelAtMs');
538
+ // above the switch's own last nonce (the chain refuses one that is not), like the account's other order nonces
539
+ const held = (await this.client.scheduleCancelState(this.owner).catch(() => null));
540
+ const floor = typeof held?.nonce === 'number' && Number.isSafeInteger(held.nonce) ? held.nonce + 1 : 0;
541
+ const nonce = await this.fresh('orders', undefined, floor);
327
542
  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 };
543
+ // the network applies a ScheduleCancel nonce once (a second copy is refused): a lost answer sends the same body
544
+ // again, and a nonce answer to a resent copy counts only when the switch's committed state holds this nonce
545
+ try {
546
+ const r = await this.postSame('/schedule-cancel', JSON.stringify((0, orders_js_1.scheduleCancelBody)(this.owner, at, nonce, sig)), nonce, true);
547
+ if (r.needsReadBack) {
548
+ const st = (await this.client.scheduleCancelState(this.owner).catch(() => null));
549
+ if (st && String(st.nonce) === String(nonce))
550
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, attempts: r.attempts, unknown: false, alreadyReceived: true, nonce };
551
+ 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 };
552
+ }
553
+ return { ...(0, orders_js_1.readAnswer)(r.status, r.body, r.retryAfter, this.client.refusalMeanings()), attempts: r.attempts, unknown: false, alreadyReceived: false, nonce };
554
+ }
555
+ catch (e) {
556
+ if (!(e instanceof resend_js_1.DeliveryUnknown))
557
+ throw e;
558
+ return { ...unknownResult(e.attempts, e.message, null), alreadyReceived: false, nonce };
559
+ }
329
560
  }
330
561
  // ── session key ───────────────────────────────────────────────────────────────────────────────────────────────────
331
562
  async revokeSession(waitMs = 30000) {
@@ -333,11 +564,10 @@ class Account {
333
564
  const held = await this.client.session(this.owner);
334
565
  if (!held)
335
566
  return { applied: true, status: 0, answer: null, detail: 'no session to revoke' };
336
- const n = (0, account_js_1.nextNonce)();
567
+ const n = await this.fresh('account');
337
568
  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' };
569
+ const r = await this.postForResult('/session/revoke', (0, account_js_1.sessionRevokeBody)(this.owner, held.session_key, n, sig));
570
+ return outcome(r, async () => (await this.client.session(this.owner)) === null, waitMs, 'the chain still holds the session');
341
571
  }
342
572
  /**
343
573
  * Give `sessionKey` (a session key, or a registered agent's key) this account's session until `endMs`. A session the
@@ -347,19 +577,16 @@ class Account {
347
577
  const signer = this.needOwner('A session');
348
578
  const key = (0, ethers_1.getAddress)(sessionKey);
349
579
  const held = await this.client.session(this.owner);
350
- let after = 0;
351
580
  if (held && held.session_key.toLowerCase() !== key.toLowerCase()) {
352
581
  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)();
582
+ if (r.applied !== true)
583
+ return { ...r, detail: "the account's other session could not be ended" + (r.applied === null ? ' (not known yet)' : '') };
356
584
  }
357
- const n = (0, account_js_1.nextNonce)(after), exp = (0, account_js_1.sessionEnd)(endMs);
585
+ const n = await this.fresh('account'), exp = (0, account_js_1.sessionEnd)(endMs);
358
586
  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));
587
+ const r = await this.postForResult('/session/create', (0, account_js_1.sessionCreateBody)(this.owner, key, exp, n, sig));
360
588
  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' };
589
+ return outcome(r, mine, waitMs, 'the chain does not show the session as confirmed');
363
590
  }
364
591
  // ── TWAP (owner key only) ─────────────────────────────────────────────────────────────────────────────────────────
365
592
  async placeTwap(t, waitMs = 30000) {
@@ -370,26 +597,27 @@ class Account {
370
597
  throw new errors_js_1.InvalidRequest("The slippage is above the network's TWAP limit.");
371
598
  const numSlices = t.numSlices ?? (0, account_js_1.planTwap)(t.durationMs, rules)[0];
372
599
  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)();
600
+ const clientNonce = await this.fresh('orders');
374
601
  const v = {
375
602
  owner: this.owner, pairId: t.pairId, side: t.side === 'buy' ? 0 : 1, totalSize18dec: total,
376
603
  numSlices, durationMs: t.durationMs, leverageBps: t.leverageBps ?? 10000, slippageBps: slip,
377
604
  randomize: !!t.randomize, triggerPrice8dec: 0n, triggerDir: 0, minPrice8dec: lo, maxPrice8dec: hi, clientNonce,
378
605
  };
379
606
  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 };
607
+ const r = await this.postForResult(rules.path, (0, account_js_1.twapBody)(v, sig));
608
+ // the nonce AND what was signed, among the live TWAPs or the ended ones (the account's twap_* records)
609
+ const held = async () => (await this.client.twaps(this.owner)).some((x) => twapMatches(x, v))
610
+ || (await this.client.orderRecords(this.owner)).some((e) => String(e.kind ?? '').startsWith('twap') && twapMatches(e, v));
611
+ return { ...(await outcome(r, held, waitMs, 'the chain does not list the TWAP')), clientNonce };
383
612
  }
384
613
  async cancelTwap(twapId, waitMs = 30000) {
385
614
  const signer = this.needOwner('Cancelling a TWAP');
386
615
  const rules = this.client.twapRules();
387
- const cn = (0, account_js_1.nextNonce)();
616
+ const cn = await this.fresh('orders');
388
617
  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));
618
+ const r = await this.postForResult(rules.cancelPath, (0, account_js_1.cancelTwapBody)(this.owner, twapId, cn, sig));
390
619
  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' };
620
+ return outcome(r, gone, waitMs, 'the chain still lists the TWAP');
393
621
  }
394
622
  // ── margin mode (owner key only) ──────────────────────────────────────────────────────────────────────────────────
395
623
  /** The market's margin mode as the chain reads it ("cross" | "isolated"), or null. */
@@ -401,24 +629,99 @@ class Account {
401
629
  const map = { 1: 'cross', 2: 'isolated', cross: 'cross', isolated: 'isolated' };
402
630
  return map[String(m)] ?? null;
403
631
  }
632
+ // ── builder codes ─────────────────────────────────────────────────────────────────────────────────────────────
633
+ /** An order's builder after the network's reads allow it (rule active, fee within the perps cap, approved, funded). */
634
+ async checkedBuilder(b) {
635
+ const ob = (0, builder_js_1.parseBuilder)(b);
636
+ let approvals, stats;
637
+ try {
638
+ approvals = await this.client.builderApprovals(this.owner);
639
+ stats = await this.client.builderStats(ob.address);
640
+ }
641
+ catch (e) {
642
+ if (e instanceof builder_js_1.BuilderError)
643
+ throw e;
644
+ throw new builder_js_1.BuilderNotActive('The network did not answer its builder reads, so the builder fee cannot be checked and nothing was signed. Try again, or send the order without a builder.');
645
+ }
646
+ (0, builder_js_1.requireActive)(approvals);
647
+ (0, builder_js_1.requireActive)(stats);
648
+ (0, builder_js_1.checkFee)(ob.feeCbps, 'perps', (0, builder_js_1.capsFrom)(stats));
649
+ (0, builder_js_1.checkOrderBuilder)(this.owner, ob.address, ob.feeCbps, approvals, stats);
650
+ return ob;
651
+ }
652
+ /** The builders this account approved (`approvals`, `count`, `max`, `nonce`, `active`). */
653
+ builderApprovals() { return this.client.builderApprovals(this.owner); }
654
+ /** This account's stats as a builder. */
655
+ builderStats() { return this.client.builderStats(this.owner); }
656
+ /**
657
+ * Let `builder` charge this account up to `maxFeeCbps` per order (500 cbps = 5 bps = 0.05 %); approving a builder
658
+ * again replaces its fee. Signed with the account's own key. Refused before signing when builder fees are not active,
659
+ * the fee is 0 or above the highest cap (`caps_cbps`), the builder is this account, or the account already approved
660
+ * the most builders it may (`max`).
661
+ */
662
+ async approveBuilderFee(builder, maxFeeCbps, waitMs = 30000) {
663
+ const signer = this.needOwner('A builder approval');
664
+ const b = builderAddress(builder);
665
+ const read = await this.client.builderApprovals(this.owner);
666
+ (0, builder_js_1.requireActive)(read);
667
+ const fee = (0, builder_js_1.checkMaxFee)(maxFeeCbps, (0, builder_js_1.capsFrom)(await this.client.builderStats(b)));
668
+ if (b.toLowerCase() === this.owner.toLowerCase())
669
+ throw new builder_js_1.BuilderError('builder_self', 'An account cannot be its own builder: name another builder.');
670
+ const max = read.max, count = read.count;
671
+ if (typeof max !== 'number' || typeof count !== 'number')
672
+ throw new builder_js_1.BuilderError('unreadable', "The network's approvals read gives no count or maximum, so nothing was signed.");
673
+ if ((0, builder_js_1.approvalOf)(read, b) === null && count >= max)
674
+ throw new builder_js_1.BuilderError('builder_approvals_full', `The account has approved the most builders it may (${max}): revoke one first.`);
675
+ return this.approve(signer, b, fee, read, (r) => (0, builder_js_1.approvalOf)(r, b) === fee, 'the chain does not show the approval', waitMs);
676
+ }
677
+ /** Withdraw the approval of `builder` (an approval of 0). Orders that name it are refused from then on. */
678
+ async revokeBuilderFee(builder, waitMs = 30000) {
679
+ const signer = this.needOwner('A builder approval');
680
+ const b = builderAddress(builder);
681
+ const read = await this.client.builderApprovals(this.owner);
682
+ (0, builder_js_1.requireActive)(read);
683
+ if ((0, builder_js_1.approvalOf)(read, b) === null)
684
+ return { applied: true, status: 0, answer: null, detail: 'no approval to revoke' };
685
+ return this.approve(signer, b, 0, read, (r) => (0, builder_js_1.approvalOf)(r, b) === null, 'the chain still shows the approval', waitMs);
686
+ }
687
+ async approve(signer, b, fee, read, shows, notShown, waitMs) {
688
+ const nonce = (typeof read.nonce === 'number' ? read.nonce : 0) + 1;
689
+ const v = (0, builder_js_1.approveBuilderFeeValue)(this.owner, b, fee, nonce, (0, builder_js_1.deadline)(null, await this.client.nowS()));
690
+ const sig = await this.sign(signer, 'ApproveBuilderFee', v);
691
+ const r = await this.postForResult(builder_js_1.BUILDER_ROUTES.approve, JSON.stringify((0, builder_js_1.approveBuilderFeeBody)(v, sig)));
692
+ // applied once the account's approval nonce has reached ours and the approval reads as asked
693
+ return outcome(r, async () => { const a = await this.client.builderApprovals(this.owner); return a.nonce >= nonce && shows(a); }, waitMs, notShown);
694
+ }
695
+ /** As a builder: move the unclaimed fees to this account's balance. Refused before signing when there is nothing. */
696
+ async claimBuilderFees(waitMs = 30000) {
697
+ const signer = this.needOwner('A claim of builder fees');
698
+ const st = await this.client.builderStats(this.owner);
699
+ (0, builder_js_1.requireActive)(st);
700
+ if (!(typeof st.unclaimed_6dec === 'string' && /^\d+$/.test(st.unclaimed_6dec) && BigInt(st.unclaimed_6dec) > 0n)) {
701
+ throw new builder_js_1.BuilderError('builder_nothing_to_claim', 'There are no builder fees to claim; nothing was signed.');
702
+ }
703
+ const before = typeof st.claim_nonce === 'number' ? st.claim_nonce : 0;
704
+ const v = (0, builder_js_1.claimBuilderFeesValue)(this.owner, before + 1, (0, builder_js_1.deadline)(null, await this.client.nowS()));
705
+ const sig = await this.sign(signer, 'ClaimBuilderFees', v);
706
+ const r = await this.postForResult(builder_js_1.BUILDER_ROUTES.claim, JSON.stringify((0, builder_js_1.claimBuilderFeesBody)(v, sig)));
707
+ return outcome(r, async () => (await this.client.builderStats(this.owner)).claim_nonce > before, waitMs, 'the chain does not show the claim');
708
+ }
404
709
  /** Cross or isolated for one market — only while it holds no open position and no resting order of the account. */
405
710
  async setMarginMode(pairId, mode, waitMs = 30000) {
406
711
  const signer = this.needOwner('The margin mode');
407
712
  if (!(mode in account_js_1.MODE_CODE))
408
713
  throw new errors_js_1.InvalidRequest('The mode is cross or isolated.');
409
- const n = (0, account_js_1.nextNonce)();
714
+ const n = await this.fresh('account');
410
715
  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' };
716
+ const r = await this.postForResult('/margin/mode', (0, account_js_1.marginModeBody)(this.owner, pairId, account_js_1.MODE_CODE[mode], n, sig), false);
717
+ return outcome(r, async () => (await this.marginMode(pairId)) === mode, waitMs, 'the chain does not show the new mode');
414
718
  }
415
719
  // ── agents (owner key; the agent may tighten its own policy) ──────────────────────────────────────────────────────
416
720
  async submitAgentOp(signer, op, value, shows, agent, waitMs) {
417
721
  const sig = await this.sign(signer, op, value);
418
722
  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' };
723
+ const r = await this.postForResult('/submit', JSON.stringify(body));
724
+ return outcome(r, async () => shows(await this.client.agent(this.owner, agent)), waitMs, 'the chain does not show the change');
422
725
  }
423
726
  addr(a, op) {
424
727
  const c = (0, ethers_1.getAddress)(a);
@@ -428,7 +731,7 @@ class Account {
428
731
  async registerAgent(a, waitMs = 30000) {
429
732
  const signer = this.needOwner('Registering an agent');
430
733
  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)() };
734
+ 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
735
  return this.submitAgentOp(signer, op, value, (rec) => !!rec && rec.status === 'active' && rec.name === value.name, value.agent, waitMs);
433
736
  }
434
737
  /**
@@ -439,7 +742,7 @@ class Account {
439
742
  async renameAgent(agent, name, waitMs = 30000) {
440
743
  const signer = this.needOwner('Renaming an agent');
441
744
  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)() };
745
+ 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
746
  const rec = await this.client.agent(this.owner, value.agent);
444
747
  const named = typeof rec?.named_at_ms === 'number' ? rec.named_at_ms : null;
445
748
  const wait = this.client.renameWaitMs();
@@ -454,7 +757,7 @@ class Account {
454
757
  async revokeAgent(agent, waitMs = 30000) {
455
758
  const signer = this.needOwner('Revoking an agent');
456
759
  const op = 'RevokeAgent';
457
- const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), nonce: (0, account_js_1.nextNonce)() };
760
+ const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), nonce: await this.fresh('account') };
458
761
  return this.submitAgentOp(signer, op, value, (rec) => !!rec && rec.status === 'revoked', value.agent, waitMs);
459
762
  }
460
763
  /**
@@ -480,7 +783,7 @@ class Account {
480
783
  if (wider.length)
481
784
  throw new errors_js_1.InvalidRequest(`An agent may only tighten its own policy; this ${wider.join(', ')} — only the owner may sign that.`);
482
785
  }
483
- const value = (0, agents_js_1.policyValue)(this.addr(this.owner, op), agentAddr, policy, (0, account_js_1.nextNonce)());
786
+ 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
787
  const same = (rec) => {
485
788
  const p = (0, agents_js_1.policyFromRead)(rec?.policy_v1);
486
789
  return !!p && JSON.stringify(p, (_, x) => (typeof x === 'bigint' ? x.toString() : x)) === JSON.stringify(policy, (_, x) => (typeof x === 'bigint' ? x.toString() : x));
@@ -492,7 +795,7 @@ class Account {
492
795
  const signer = this.needOwner("An agent's market limit");
493
796
  const op = 'SetAgentMarketLimit';
494
797
  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)() };
798
+ 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
799
  const shows = (rec) => (Array.isArray(rec?.market_limits) ? rec.market_limits : [])
497
800
  .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
801
  return this.submitAgentOp(signer, op, value, shows, value.agent.toLowerCase(), waitMs);
@@ -503,7 +806,7 @@ class Account {
503
806
  if (!Number.isSafeInteger(lockSinceMs) || lockSinceMs <= 0)
504
807
  throw new errors_js_1.InvalidRequest('lockSinceMs is the start of the active lock (from the agent read).');
505
808
  const op = 'ClearAgentLock';
506
- const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), lockSinceMs, nonce: (0, account_js_1.nextNonce)() };
809
+ const value = { owner: this.addr(this.owner, op), agent: this.addr(agent, op), lockSinceMs, nonce: await this.fresh('account') };
507
810
  const shows = (rec) => rec?.risk_v1?.lock_active === false;
508
811
  return this.submitAgentOp(signer, op, value, shows, value.agent, waitMs);
509
812
  }
@@ -524,3 +827,90 @@ function twapOnSteps(spec, total18, numSlices, minPrice8, maxPrice8) {
524
827
  throw new rounding_js_1.OrderValueError("The TWAP's price band holds no tick of this market.");
525
828
  return [total, lo, hi];
526
829
  }
830
+ const asBig = (v) => {
831
+ if (typeof v === 'bigint')
832
+ return v;
833
+ if (typeof v === 'number' && Number.isSafeInteger(v))
834
+ return BigInt(v);
835
+ if (typeof v === 'string' && /^\d+$/.test(v.trim()))
836
+ return BigInt(v.trim());
837
+ return null;
838
+ };
839
+ /**
840
+ * Whether an order record carries what was signed: its market and side, and its size or limit price. A field the
841
+ * record does not show is not counted; one it shows with another value is a mismatch; a record that shows neither size
842
+ * nor price is not enough.
843
+ */
844
+ function matchesSigned(rec, signed) {
845
+ const pair = asBig(rec.pair_id ?? rec.pairId);
846
+ if (pair === null || pair !== BigInt(signed.pairId))
847
+ return false;
848
+ const sd = String(rec.side ?? '').trim().toLowerCase();
849
+ const side = ['0', 'buy', 'b', 'long'].includes(sd) ? 0 : ['1', 'sell', 's', 'short'].includes(sd) ? 1 : null;
850
+ if (side === null || side !== signed.side)
851
+ return false;
852
+ let shown = 0;
853
+ for (const k of ['original_size_18dec', 'size_18dec', 'size']) { // a partly filled order's left-over size never matches: unknown
854
+ const v = asBig(rec[k]);
855
+ if (v !== null) {
856
+ if (v !== signed.size)
857
+ return false;
858
+ shown++;
859
+ break;
860
+ }
861
+ }
862
+ if (signed.price !== null) {
863
+ const v = asBig(rec.price_8dec);
864
+ if (v !== null) {
865
+ if (v !== signed.price)
866
+ return false;
867
+ shown++;
868
+ }
869
+ }
870
+ return shown > 0;
871
+ }
872
+ /** Whether a TWAP the chain lists is the one signed: its client nonce, market, side and total size. */
873
+ function twapMatches(row, v) {
874
+ if (String(row.client_nonce) !== String(v.clientNonce))
875
+ return false;
876
+ const checks = [[row.pair_id, BigInt(v.pairId)], [row.total_size_18dec ?? row.total_size, BigInt(v.totalSize18dec)]];
877
+ for (const [got, want] of checks) {
878
+ const g = asBig(got);
879
+ if (g !== null && g !== want)
880
+ return false;
881
+ }
882
+ if (row.side !== undefined && row.side !== null) {
883
+ const sd = String(row.side).toLowerCase();
884
+ const side = /^\d+$/.test(sd) ? Number(sd) : { buy: 0, b: 0, long: 0, sell: 1, s: 1, short: 1 }[sd] ?? -1;
885
+ if (side !== v.side)
886
+ return false;
887
+ }
888
+ return true;
889
+ }
890
+ /** A builder address, or BuilderError('invalid_body') with a plain sentence (never the library's own error). */
891
+ function builderAddress(a) {
892
+ try {
893
+ return (0, ethers_1.getAddress)(String(a));
894
+ }
895
+ catch {
896
+ throw new builder_js_1.BuilderError('invalid_body', 'The builder must be an address (0x and 40 hex characters).');
897
+ }
898
+ }
899
+ function unknownResult(attempts, message, answer) {
900
+ return { submitted: false, status: 0, refusal: { code: 'delivery_unknown', message, detail: '', retryAfter: null }, actions: [], answer, attempts, unknown: true };
901
+ }
902
+ /** How an order that is not resting was closed, from the account's records: `cancelled`, `filled`, or null. */
903
+ function cancelOutcome(records, orderId) {
904
+ const mine = records.filter((e) => String(e.order_id ?? e.orderId ?? e.id) === orderId.toString());
905
+ for (const e of mine) {
906
+ const kind = String(e.kind ?? '').toLowerCase(), st = String(e.status ?? '').toLowerCase();
907
+ if (kind === 'order_cancelled' || (kind === 'order_closed' && st === 'cancelled'))
908
+ return 'cancelled';
909
+ }
910
+ for (const e of mine) {
911
+ const kind = String(e.kind ?? '').toLowerCase(), st = String(e.status ?? '').toLowerCase();
912
+ if (kind === 'fill' || kind === 'order_filled' || (kind === 'order_closed' && st === 'filled'))
913
+ return 'filled';
914
+ }
915
+ return null;
916
+ }