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