@vordium/sdk 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChainClock = exports.DeliveryUnknown = exports.RESEND_STATUS = void 0;
4
+ exports.nonceUsedAnswer = nonceUsedAnswer;
5
+ exports.neverSent = neverSent;
6
+ exports.sendSame = sendSame;
7
+ const errors_js_1 = require("./errors.js");
8
+ /** Answers that mean "try again": the write was not taken, or a gateway cannot tell. */
9
+ exports.RESEND_STATUS = new Set([429, 502, 503, 504]);
10
+ const USED = /already used|already applied|duplicate|nonce not above|not above the account's last|must be greater than/i;
11
+ const USED_CODES = new Set(['nonce', 'nonce_used', 'duplicate', 'duplicate_nonce', 'vault_nonce']);
12
+ /** Whether an answer says the nonce (of a body we sent) is already used. */
13
+ function nonceUsedAnswer(status, body) {
14
+ if (status === 409)
15
+ return true;
16
+ if (typeof body === 'string')
17
+ return USED.test(body);
18
+ if (!body || typeof body !== 'object')
19
+ return false;
20
+ const j = body;
21
+ if (typeof j.code === 'string' && USED_CODES.has(j.code.toLowerCase()))
22
+ return true;
23
+ return USED.test(['error', 'reason', 'message'].map((k) => String(j[k] ?? '')).join(' '));
24
+ }
25
+ /** The network did not answer any copy of a signed write. It may have arrived: read the account before sending a new
26
+ * one (a new one takes a new nonce). */
27
+ class DeliveryUnknown extends errors_js_1.VordiumError {
28
+ nonce;
29
+ attempts;
30
+ /** True when no copy left this machine (the connection could not be made on any try): it certainly did not arrive. */
31
+ neverSent = false;
32
+ constructor(message, nonce, attempts) {
33
+ super('delivery_unknown', message);
34
+ this.nonce = nonce;
35
+ this.attempts = attempts;
36
+ this.name = 'DeliveryUnknown';
37
+ }
38
+ }
39
+ exports.DeliveryUnknown = DeliveryUnknown;
40
+ const DNS = new Set(['ENOTFOUND', 'EAI_AGAIN']);
41
+ const AT_CONNECT = new Set(['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'ETIMEDOUT']);
42
+ /** True when the error happened while the connection was being made: the name lookup, a connect timeout, or a refused
43
+ * / unreachable error whose `syscall` is `connect`. The same refused or unreachable code on a connection that was
44
+ * already open (after a retransmit timeout), a timeout, or a gateway answer is not that: the copy may have arrived. */
45
+ function neverSent(e) {
46
+ const name = e?.name;
47
+ if (name === 'TimeoutError' || name === 'AbortError')
48
+ return false; // our own time limit: the request had left
49
+ for (let x = e, i = 0; x && i < 4; x = x.cause, i++) {
50
+ const { code, syscall } = x;
51
+ if (typeof code !== 'string')
52
+ continue;
53
+ if (DNS.has(code) || code === 'UND_ERR_CONNECT_TIMEOUT')
54
+ return true;
55
+ if (AT_CONNECT.has(code) && syscall === 'connect')
56
+ return true;
57
+ }
58
+ return false;
59
+ }
60
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
61
+ const wait = (attempt, retryAfter) => {
62
+ const ra = Number(retryAfter);
63
+ return Math.max(Math.random() * Math.min(500 * 2 ** attempt, 8000), Number.isFinite(ra) && ra > 0 ? Math.min(ra, 30) * 1000 : 0);
64
+ };
65
+ /**
66
+ * Send one signed body until the network answers it, at most `attempts` times, each time the same bytes.
67
+ *
68
+ * `dedup` says whether the network applies this write once per nonce. Then a thrown error (a lost connection, a
69
+ * timeout) or HTTP 429/502/503/504 sends it again after a short random wait (at least the server's Retry-After); when an
70
+ * earlier copy may have arrived and the final answer is not a 2xx, `needsReadBack` is set. For a write the network does
71
+ * not deduplicate (`dedup: false`) a copy is sent again only when the first never left this machine or was answered
72
+ * 429; a timeout, a dropped connection or any 5xx throws {@link DeliveryUnknown} at once, so the caller reads state
73
+ * instead of risking a second effect.
74
+ */
75
+ async function sendSame(send, opts = {}) {
76
+ const n = Math.max(1, Math.floor(opts.attempts ?? 3));
77
+ const pause = opts.sleep ?? sleep;
78
+ const dedup = opts.dedup ?? true;
79
+ let maybeArrived = false; // a copy sent in THIS call may have reached the network
80
+ let lastErr = null;
81
+ let last = null;
82
+ const unknown = (i, why) => new DeliveryUnknown(`It is not known whether the network received this write${opts.nonce != null ? ` (nonce ${opts.nonce})` : ''}: ${why} after ${i} ${i === 1 ? 'try' : 'tries'}. Read the account before sending a new one.`, opts.nonce ?? null, i);
83
+ const done = (r, i) => {
84
+ const ok = r.status >= 200 && r.status < 300;
85
+ if (!ok && r.status >= 500) {
86
+ if (!dedup)
87
+ throw unknown(i, `the network answered ${r.status}`);
88
+ return { ...r, attempts: i, needsReadBack: true }; // a gateway or node error: it may have applied
89
+ }
90
+ return { ...r, attempts: i, needsReadBack: maybeArrived && !ok };
91
+ };
92
+ for (let i = 0; i < n; i++) {
93
+ let r;
94
+ try {
95
+ r = await send();
96
+ }
97
+ catch (e) {
98
+ if (e instanceof errors_js_1.VordiumError && !(e instanceof DeliveryUnknown) && e.code !== 'unreachable')
99
+ throw e;
100
+ lastErr = e;
101
+ if (!neverSent(e)) {
102
+ maybeArrived = true;
103
+ if (!dedup)
104
+ throw unknown(i + 1, 'the answer was lost');
105
+ }
106
+ if (i < n - 1)
107
+ await pause(wait(i, null));
108
+ continue;
109
+ }
110
+ if (exports.RESEND_STATUS.has(r.status) && i < n - 1) {
111
+ if (r.status !== 429) {
112
+ maybeArrived = true;
113
+ if (!dedup)
114
+ throw unknown(i + 1, `a gateway answered ${r.status}`);
115
+ }
116
+ last = r;
117
+ lastErr = null;
118
+ await pause(wait(i, r.retryAfter));
119
+ continue;
120
+ }
121
+ return done(r, i + 1);
122
+ }
123
+ if (last && lastErr === null)
124
+ return done(last, n);
125
+ if (!maybeArrived)
126
+ throw Object.assign(new DeliveryUnknown(`The network could not be reached${opts.nonce != null ? ` (nonce ${opts.nonce})` : ''} after ${n} tries; nothing was sent.`, opts.nonce ?? null, n), { neverSent: true });
127
+ throw unknown(n, 'no copy was answered');
128
+ }
129
+ /**
130
+ * The network's block time, estimated as this computer's clock plus the offset measured at the last read: the latest
131
+ * block (JSON-RPC), cross-checked against the node's `/status` head (a JSON-RPC that serves another head is not this
132
+ * chain's clock). Null when unavailable. A reading is kept `ttlMs`; a failed one is retried after a fifth of that.
133
+ */
134
+ class ChainClock {
135
+ readBlock;
136
+ readHead;
137
+ ttlMs;
138
+ now;
139
+ maxHeadGap;
140
+ offset = null;
141
+ nextRead = 0;
142
+ constructor(readBlock, readHead, ttlMs = 300_000, now = Date.now, maxHeadGap = 10_000) {
143
+ this.readBlock = readBlock;
144
+ this.readHead = readHead;
145
+ this.ttlMs = ttlMs;
146
+ this.now = now;
147
+ this.maxHeadGap = maxHeadGap;
148
+ }
149
+ static int(v) {
150
+ if (typeof v === 'number' && Number.isSafeInteger(v))
151
+ return v;
152
+ if (typeof v === 'string' && /^(0x[0-9a-f]+|\d+)$/i.test(v))
153
+ return Number(BigInt(v));
154
+ return null;
155
+ }
156
+ /** Read the network now: block time minus this computer's clock (ms), or null. */
157
+ async measure() {
158
+ try {
159
+ const b = await this.readBlock();
160
+ const ts = ChainClock.int(b?.timestamp), num = ChainClock.int(b?.number);
161
+ if (ts === null || ts <= 0)
162
+ return null;
163
+ const head = await this.readHead().catch(() => null);
164
+ if (head !== null && (num === null || Math.abs(head - num) > this.maxHeadGap))
165
+ return null;
166
+ return ts * 1000 + 500 - Math.floor(this.now());
167
+ }
168
+ catch {
169
+ return null;
170
+ }
171
+ }
172
+ inFlight = null;
173
+ /** Block time now, or null. When a reading is due, the caller that finds it due runs ONE read and waits for it;
174
+ * every other caller meanwhile is served the last reading at once (null before the first). */
175
+ async time() {
176
+ let o = this.offset;
177
+ if (this.now() >= this.nextRead && !this.inFlight) {
178
+ this.inFlight = this.measure().then((x) => {
179
+ this.offset = x;
180
+ this.nextRead = this.now() + (x !== null ? this.ttlMs : this.ttlMs / 5);
181
+ return x;
182
+ }).finally(() => { this.inFlight = null; });
183
+ o = await this.inFlight;
184
+ }
185
+ return o === null ? null : Math.floor(this.now()) + o;
186
+ }
187
+ }
188
+ exports.ChainClock = ChainClock;
@@ -1,9 +1,10 @@
1
- import { type MarginMode, type TwapRules } from './account.js';
1
+ import { type MarginMode, type TwapRules, type TwapValue } from './account.js';
2
2
  import { type PolicyV1 } from './agents.js';
3
3
  import { type DomainClass, type TypedDomain } from './domains.js';
4
4
  import { type Transport } from './http.js';
5
5
  import { type Network, type NetworkPreset } from './network.js';
6
- import { type NonceClock } from './nonce.js';
6
+ import { type NonceSource } from './nonce.js';
7
+ import { ChainClock } from './resend.js';
7
8
  import { type BatchAction, type OrderInput, type Submitted } from './orders.js';
8
9
  import { type AgentRefusal, type Equity, type OpenOrder, type Position } from './reads.js';
9
10
  import { type TypedSigner } from './sign.js';
@@ -13,10 +14,14 @@ import { type MarketRules, type PairSpec } from './rounding.js';
13
14
  * not an application: `applied: false` with the chain's answer means the chain has not shown it (yet, or at all).
14
15
  */
15
16
  export interface Result {
16
- applied: boolean;
17
+ /** true once the chain's read shows it; false only when the network refused it (it certainly did not apply); null
18
+ * when it may have been received and the chain's read has not shown it within the wait (`unknown: true`). */
19
+ applied: boolean | null;
17
20
  status: number;
18
21
  answer: unknown;
19
22
  detail: string;
23
+ /** It may have been received, and the chain's read did not show it yet: read the account before sending it anew. */
24
+ unknown?: boolean;
20
25
  }
21
26
  export interface ConnectOptions {
22
27
  network?: 'mainnet' | 'testnet' | NetworkPreset;
@@ -24,6 +29,13 @@ export interface ConnectOptions {
24
29
  timeoutMs?: number;
25
30
  /** How long a checked node identity is trusted before it is read again (ms). */
26
31
  identityTtlMs?: number;
32
+ /** Called when the network's reports differ from its pin, or it has none (reads go on; nothing is signed). */
33
+ onPinProblem?: (message: string) => void;
34
+ /**
35
+ * Check each new nonce against the network's block time (its latest block, read at most every 5 minutes). On by
36
+ * default with the built-in transport; with a transport of your own, off unless set. Off: against this computer's clock.
37
+ */
38
+ chainClock?: boolean;
27
39
  }
28
40
  /** A connection to one Vordium network: reads, and the signing domains of its node. */
29
41
  export declare class Vordium {
@@ -32,12 +44,17 @@ export declare class Vordium {
32
44
  private readonly timeoutMs;
33
45
  private readonly ttlMs;
34
46
  private checkedAt;
47
+ /** The network's block time for the nonce window check; null checks against this computer's clock. */
48
+ readonly chainClock: ChainClock | null;
35
49
  private constructor();
50
+ /** The network's block time now (ms), estimated from its latest block; null when it cannot be read. */
51
+ chainTimeMs(): Promise<number | null>;
36
52
  /** Read and check the network (spec, node and JSON-RPC must agree) and return a client for it. Testnet by default. */
37
53
  static connect(opts?: ConnectOptions): Promise<Vordium>;
38
54
  /**
39
- * The signing domain of the node this client posts to. The node's identity is read again after the TTL; a node that
40
- * now serves another chain is refused, never followed.
55
+ * The signing domain of the node this client posts to, built from the network's pin (`PINS`) after the network's
56
+ * reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
57
+ * chain is refused, never followed.
41
58
  */
42
59
  domain(cls: DomainClass): Promise<TypedDomain>;
43
60
  /** GET a path of the REST API; null on 404, raises on another failure. */
@@ -91,7 +108,7 @@ export declare class Vordium {
91
108
  /** A trading account: `owner` signs account operations; `sessionSigner` (a session or agent key) signs orders. */
92
109
  account(owner: TypedSigner, opts?: {
93
110
  sessionSigner?: TypedSigner;
94
- nonce?: NonceClock;
111
+ nonce?: NonceSource;
95
112
  specs?: unknown;
96
113
  }): Promise<Account>;
97
114
  /** An agent's own handle: places orders with the agent key for its owner, and may tighten its own policy. */
@@ -105,10 +122,13 @@ export declare class Account {
105
122
  readonly owner: string;
106
123
  private readonly ownerSigner;
107
124
  private readonly sessionSigner;
108
- readonly nonce: NonceClock;
125
+ /** The account's client-nonce source: its persisted allocator in the `orders` space by default. */
126
+ readonly nonce: NonceSource;
109
127
  /** Market rules this handle holds; null = read them from the node for each order. */
110
128
  readonly specs: MarketRules | null;
111
- constructor(client: Vordium, owner: string, ownerSigner: TypedSigner | null, sessionSigner: TypedSigner | null, nonce: NonceClock,
129
+ constructor(client: Vordium, owner: string, ownerSigner: TypedSigner | null, sessionSigner: TypedSigner | null,
130
+ /** The account's client-nonce source: its persisted allocator in the `orders` space by default. */
131
+ nonce: NonceSource,
112
132
  /** Market rules this handle holds; null = read them from the node for each order. */
113
133
  specs?: MarketRules | null);
114
134
  /** The rules an order uses: the ones this handle holds, else read from the node now. */
@@ -119,6 +139,27 @@ export declare class Account {
119
139
  /** Orders are signed by the session (or agent) key, else by the owner key. */
120
140
  private orderSigner;
121
141
  private sign;
142
+ /**
143
+ * A fresh nonce, checked against the network's window before anything is signed ({@link ClockOutOfWindow} otherwise):
144
+ * the account's client nonce (`orders`), or the `account` nonce of `signer` (session, margin mode, agent operations).
145
+ */
146
+ private fresh;
147
+ /**
148
+ * POST one signed body, the same bytes on every try. With `dedup` (a write the network applies once per nonce) a lost
149
+ * connection, a timeout or a busy gateway sends it again (never a new nonce); without it only a copy that never left
150
+ * this machine is sent again, and a lost answer throws {@link DeliveryUnknown}.
151
+ */
152
+ private postSame;
153
+ /**
154
+ * An account operation, for a result the chain's own read decides: `proceed` is true when the network took it (2xx),
155
+ * or when it is not known whether it arrived (then the read-back alone says whether it applied).
156
+ */
157
+ private postForResult;
158
+ /**
159
+ * A write the network does not apply once per nonce (batch, cancel-all, modify, take-profit / stop-loss): never sent
160
+ * again after a lost answer. Unknown is `submitted: false, unknown: true` with the refusal `delivery_unknown`: read the
161
+ * account before sending a new one.
162
+ */
122
163
  private send;
123
164
  /**
124
165
  * Sign and submit one order (Market or Limit). The answer is a submission; the order is on the book when
@@ -129,7 +170,17 @@ export declare class Account {
129
170
  clientNonce?: number;
130
171
  }): Promise<Submitted & {
131
172
  clientNonce: number;
173
+ attempts: number;
174
+ alreadyReceived: boolean;
175
+ unknown: boolean;
176
+ found?: Record<string, unknown> | null;
132
177
  }>;
178
+ /**
179
+ * The account's order with `clientNonce` as the network lists it: resting (open orders), else its record; null when
180
+ * it lists neither (or cannot be read). With `signed`, only an order that carries the signed market, side and size or
181
+ * price counts: another signer of the account may use the same millisecond nonce.
182
+ */
183
+ orderByClientNonce(clientNonce: number, signed?: SignedOrder): Promise<Record<string, unknown> | null>;
133
184
  /**
134
185
  * Where the order with `clientNonce` stands, from the chain: `resting` while the book holds it, else what the account's
135
186
  * order records say (`filled`, `cancelled`, `expired`), or null when the chain has no record of it (a refused order
@@ -139,7 +190,12 @@ export declare class Account {
139
190
  waitForOrder(clientNonce: number, ms?: number, opts?: {
140
191
  final?: boolean;
141
192
  }): Promise<'resting' | 'filled' | 'cancelled' | 'expired' | null>;
142
- cancelOrder(orderId: bigint | number): Promise<Submitted>;
193
+ cancelOrder(orderId: bigint | number): Promise<Submitted & {
194
+ done?: boolean;
195
+ filled?: boolean;
196
+ unknown?: boolean;
197
+ attempts?: number;
198
+ }>;
143
199
  /** Take-profit / stop-loss on an open position (8-decimal prices; 0 leaves a leg unset). */
144
200
  setTpSl(pairId: number, positionId: bigint | number, takeProfit8: bigint, stopLoss8: bigint): Promise<Submitted>;
145
201
  /** Up to the published maximum of place / cancel actions in one signed batch. Cancels apply first. */
@@ -173,6 +229,9 @@ export declare class Account {
173
229
  */
174
230
  scheduleCancel(cancelAtMs: number): Promise<Submitted & {
175
231
  nonce: number;
232
+ attempts: number;
233
+ unknown: boolean;
234
+ alreadyReceived: boolean;
176
235
  }>;
177
236
  revokeSession(waitMs?: number): Promise<Result>;
178
237
  /**
@@ -237,3 +296,20 @@ export declare class Account {
237
296
  * (every slice on the lot, never more than asked), the lowest price UP and the highest DOWN (the band never widens).
238
297
  */
239
298
  export declare function twapOnSteps(spec: PairSpec, total18: bigint, numSlices: number, minPrice8: bigint, maxPrice8: bigint): [bigint, bigint, bigint];
299
+ /** The signed fields of an order, for a read-back. */
300
+ export interface SignedOrder {
301
+ pairId: number;
302
+ side: number;
303
+ size: bigint;
304
+ price: bigint | null;
305
+ }
306
+ /**
307
+ * Whether an order record carries what was signed: its market and side, and its size or limit price. A field the
308
+ * record does not show is not counted; one it shows with another value is a mismatch; a record that shows neither size
309
+ * nor price is not enough.
310
+ */
311
+ export declare function matchesSigned(rec: Record<string, unknown>, signed: SignedOrder): boolean;
312
+ /** Whether a TWAP the chain lists is the one signed: its client nonce, market, side and total size. */
313
+ export declare function twapMatches(row: Record<string, unknown>, v: TwapValue): boolean;
314
+ /** How an order that is not resting was closed, from the account's records: `cancelled`, `filled`, or null. */
315
+ export declare function cancelOutcome(records: Array<Record<string, unknown>>, orderId: bigint): 'cancelled' | 'filled' | null;