@vordium/sdk 0.0.0-stage → 0.1.2

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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/dist/cjs/account.js +126 -0
  4. package/dist/cjs/agents.js +237 -0
  5. package/dist/cjs/client.js +526 -0
  6. package/dist/cjs/domains.js +37 -0
  7. package/dist/cjs/errors.js +39 -0
  8. package/dist/cjs/feeds.js +278 -0
  9. package/dist/cjs/http.js +97 -0
  10. package/dist/cjs/index.js +37 -0
  11. package/dist/cjs/network.js +114 -0
  12. package/dist/cjs/nonce.js +36 -0
  13. package/dist/cjs/orders.js +260 -0
  14. package/dist/cjs/package.json +1 -0
  15. package/dist/cjs/reads.js +121 -0
  16. package/dist/cjs/rounding.js +252 -0
  17. package/dist/cjs/sign.js +49 -0
  18. package/dist/cjs/types.js +57 -0
  19. package/dist/cjs/units.js +78 -0
  20. package/dist/esm/account.d.ts +61 -0
  21. package/dist/esm/account.js +114 -0
  22. package/dist/esm/agents.d.ts +71 -0
  23. package/dist/esm/agents.js +225 -0
  24. package/dist/esm/client.d.ts +239 -0
  25. package/dist/esm/client.js +520 -0
  26. package/dist/esm/domains.d.ts +21 -0
  27. package/dist/esm/domains.js +30 -0
  28. package/dist/esm/errors.d.ts +18 -0
  29. package/dist/esm/errors.js +32 -0
  30. package/dist/esm/feeds.d.ts +97 -0
  31. package/dist/esm/feeds.js +267 -0
  32. package/dist/esm/http.d.ts +24 -0
  33. package/dist/esm/http.js +93 -0
  34. package/dist/esm/index.d.ts +15 -0
  35. package/dist/esm/index.js +15 -0
  36. package/dist/esm/network.d.ts +44 -0
  37. package/dist/esm/network.js +107 -0
  38. package/dist/esm/nonce.d.ts +15 -0
  39. package/dist/esm/nonce.js +31 -0
  40. package/dist/esm/orders.d.ts +141 -0
  41. package/dist/esm/orders.js +238 -0
  42. package/dist/esm/reads.d.ts +59 -0
  43. package/dist/esm/reads.js +113 -0
  44. package/dist/esm/rounding.d.ts +70 -0
  45. package/dist/esm/rounding.js +229 -0
  46. package/dist/esm/sign.d.ts +27 -0
  47. package/dist/esm/sign.js +43 -0
  48. package/dist/esm/types.d.ts +41 -0
  49. package/dist/esm/types.js +51 -0
  50. package/dist/esm/units.d.ts +16 -0
  51. package/dist/esm/units.js +70 -0
  52. package/package.json +53 -4
@@ -0,0 +1,260 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MESSAGES = exports.BATCH_MAX = exports.BATCH_ORDER_TYPE = exports.ACTION_KIND = exports.STOP_REFUSAL = exports.PRICE_STEP_8DEC = exports.SIZE_DECIMALS = exports.PRICE_DECIMALS = exports.ORDER_TYPE = exports.SIDE = void 0;
4
+ exports.limitPrice8 = limitPrice8;
5
+ exports.size18 = size18;
6
+ exports.leverageBps = leverageBps;
7
+ exports.placeOrderValue = placeOrderValue;
8
+ exports.placeOrderBody = placeOrderBody;
9
+ exports.cancelOrderBody = cancelOrderBody;
10
+ exports.setTpSlBody = setTpSlBody;
11
+ exports.batchPlace = batchPlace;
12
+ exports.batchCancel = batchCancel;
13
+ exports.batchCancelByClientNonce = batchCancelByClientNonce;
14
+ exports.batchActionBody = batchActionBody;
15
+ exports.batchBody = batchBody;
16
+ exports.cancelAllBody = cancelAllBody;
17
+ exports.modifyBody = modifyBody;
18
+ exports.scheduleCancelBody = scheduleCancelBody;
19
+ exports.roundPrice = roundPrice;
20
+ exports.roundSize = roundSize;
21
+ exports.refusal = refusal;
22
+ exports.readAnswer = readAnswer;
23
+ const errors_js_1 = require("./errors.js");
24
+ const units_js_1 = require("./units.js");
25
+ const rounding_js_1 = require("./rounding.js");
26
+ /**
27
+ * Orders on the Vordex central limit order book.
28
+ *
29
+ * Units — signed fields use two scales: prices are 8-decimal integers (`price8`), sizes 18-decimal integers (`size18`).
30
+ * The chain keeps a limit price at 6 decimals, so a signed price must be a multiple of 100.
31
+ *
32
+ * Single orders (`/order/place`) carry `side` and `orderType` by NAME ("buy"/"sell"; "Market"/"Limit", case-sensitive)
33
+ * and the limit price as a decimal number; the signed digest carries the numbers. Stop orders are not available.
34
+ */
35
+ exports.SIDE = { buy: 0, sell: 1 };
36
+ exports.ORDER_TYPE = { Market: 0, Limit: 1 };
37
+ exports.PRICE_DECIMALS = 8;
38
+ exports.SIZE_DECIMALS = 18;
39
+ exports.PRICE_STEP_8DEC = 100n;
40
+ exports.STOP_REFUSAL = 'Stop orders are not available: set a take-profit or stop-loss on the position instead.';
41
+ /** A limit price as signed: at most 6 decimals (the precision the chain keeps), as the 8-decimal integer. */
42
+ function limitPrice8(price) {
43
+ const p = (0, units_js_1.toUnits)(price, 6, 'A limit price') * exports.PRICE_STEP_8DEC;
44
+ if (p <= 0n || p > units_js_1.U64)
45
+ throw new errors_js_1.InvalidRequest('A limit price must be above zero.');
46
+ return p;
47
+ }
48
+ function size18(size) {
49
+ const s = (0, units_js_1.toUnits)(size, exports.SIZE_DECIMALS, 'A size');
50
+ if (s <= 0n || s > units_js_1.U128)
51
+ throw new errors_js_1.InvalidRequest('A size must be above zero.');
52
+ return s;
53
+ }
54
+ /** Leverage as basis points, exactly from its decimal form (10x = 100000). */
55
+ function leverageBps(leverage) {
56
+ if (typeof leverage === 'number' && !Number.isFinite(leverage))
57
+ throw new errors_js_1.InvalidRequest('Leverage is at least 1x.');
58
+ const b = (0, rounding_js_1.leverageBpsExact)(leverage);
59
+ if (b < 10000n || b > units_js_1.U32)
60
+ throw new errors_js_1.InvalidRequest('Leverage is at least 1x.');
61
+ return Number(b);
62
+ }
63
+ /**
64
+ * The signed PlaceOrder value. Refuses stop orders, a priced market order and an unpriced limit order. The size and a
65
+ * limit price go onto the market's lot and tick (`spec`; none = only the signed units): a buy's price rounds down and a
66
+ * sell's up (at most 6 decimals), the size rounds down. A size that rounds to 0, below the market's smallest size, or a
67
+ * limit order below the network's smallest order value is refused before signing.
68
+ */
69
+ function placeOrderValue(o, spec = null) {
70
+ if (!(o.side in exports.SIDE))
71
+ throw new errors_js_1.InvalidRequest(`side is buy or sell, not ${String(o.side)}.`);
72
+ if (!(o.orderType in exports.ORDER_TYPE))
73
+ throw new errors_js_1.NotAvailable(exports.STOP_REFUSAL);
74
+ const priced = o.orderType === 'Limit';
75
+ if (priced && (o.price === undefined || o.price === null))
76
+ throw new errors_js_1.InvalidRequest('A limit order needs a price.');
77
+ if (!priced && o.price !== undefined && o.price !== null)
78
+ throw new errors_js_1.InvalidRequest('A market order carries no price (it is signed with price 0).');
79
+ if (o.postOnly && !priced)
80
+ throw new errors_js_1.InvalidRequest('Post-only applies to a limit order.');
81
+ const size = (0, rounding_js_1.size18OnLot)(o.size, spec);
82
+ const price = priced ? (0, rounding_js_1.price8OnTick)(o.price, spec, o.side, true) : 0n;
83
+ (0, rounding_js_1.checkNotional)(size, price, spec);
84
+ return {
85
+ owner: o.owner,
86
+ pairId: (0, units_js_1.safeNumber)((0, units_js_1.uint)(o.pairId, units_js_1.U32, 'pairId'), 'pairId'),
87
+ side: exports.SIDE[o.side],
88
+ size,
89
+ price,
90
+ leverageBps: leverageBps(o.leverage ?? 1),
91
+ orderType: exports.ORDER_TYPE[o.orderType],
92
+ reduceOnly: !!o.reduceOnly,
93
+ postOnly: !!o.postOnly,
94
+ triggerPrice8dec: 0n,
95
+ triggerDir: 0,
96
+ clientNonce: (0, units_js_1.safeNumber)((0, units_js_1.uint)(o.clientNonce, units_js_1.U64, 'clientNonce'), 'clientNonce'),
97
+ };
98
+ }
99
+ const SIDE_NAME = ['buy', 'sell'];
100
+ const TYPE_NAME = ['Market', 'Limit'];
101
+ /** The `/order/place` body for a signed PlaceOrder (`signature` = the 64-byte r‖s form). */
102
+ function placeOrderBody(v, sessionKey, signature) {
103
+ if (v.orderType !== 0 && v.orderType !== 1)
104
+ throw new errors_js_1.NotAvailable(exports.STOP_REFUSAL);
105
+ if (v.triggerPrice8dec !== 0n || v.triggerDir !== 0)
106
+ throw new errors_js_1.NotAvailable('Trigger price and direction belong to stop orders, which are not available; send 0 for both.');
107
+ const body = {
108
+ owner: v.owner,
109
+ pairId: v.pairId,
110
+ side: SIDE_NAME[v.side],
111
+ size_18dec: v.size.toString(),
112
+ orderType: TYPE_NAME[v.orderType],
113
+ reduceOnly: v.reduceOnly,
114
+ leverageBps: v.leverageBps,
115
+ clientNonce: v.clientNonce,
116
+ sessionKey,
117
+ post_only: v.postOnly,
118
+ trigger_price_8dec: 0,
119
+ trigger_dir: 0,
120
+ signature,
121
+ };
122
+ if (v.orderType === 1) {
123
+ if (v.price <= 0n || v.price % exports.PRICE_STEP_8DEC !== 0n)
124
+ throw new errors_js_1.InvalidRequest('A limit price has at most 6 decimals.');
125
+ body.price = Number((0, units_js_1.fromUnits)(v.price, exports.PRICE_DECIMALS));
126
+ }
127
+ else if (v.price !== 0n) {
128
+ throw new errors_js_1.InvalidRequest('A market order carries no price (it is signed with price 0).');
129
+ }
130
+ return body;
131
+ }
132
+ function cancelOrderBody(owner, sessionKey, orderId, signature) {
133
+ return { order_id: (0, units_js_1.safeNumber)((0, units_js_1.uint)(orderId, units_js_1.U64, 'orderId'), 'orderId'), owner, session_key: sessionKey, signature };
134
+ }
135
+ /** The `/tpsl/set` body (prices are 8-decimal integers; 0 leaves a leg unset). */
136
+ function setTpSlBody(owner, sessionKey, pairId, positionId, tp8, sl8, signature) {
137
+ return {
138
+ action: 'perp_tpsl', owner, pair_id: pairId, position_id: (0, units_js_1.safeNumber)((0, units_js_1.uint)(positionId, units_js_1.U64, 'positionId'), 'positionId'),
139
+ take_profit_8dec: (0, units_js_1.safeNumber)((0, units_js_1.uint)(tp8, units_js_1.U64, 'takeProfit'), 'takeProfit'), stop_loss_8dec: (0, units_js_1.safeNumber)((0, units_js_1.uint)(sl8, units_js_1.U64, 'stopLoss'), 'stopLoss'),
140
+ session_key: sessionKey, signature,
141
+ };
142
+ }
143
+ // ── Batches (market makers) ─────────────────────────────────────────────────────────────────────────────────────────
144
+ exports.ACTION_KIND = { place: 0, cancel: 1, cancelByClientNonce: 2 };
145
+ /** Batch order types: limit (good till cancelled), ioc, fok, market. */
146
+ exports.BATCH_ORDER_TYPE = { market: 0, limit: 1, ioc: 4, fok: 5 };
147
+ exports.BATCH_MAX = 50;
148
+ function batchPlace(a) {
149
+ const ot = a.orderType ?? 'limit';
150
+ if (!(a.side in exports.SIDE))
151
+ throw new errors_js_1.InvalidRequest(`side is buy or sell, not ${String(a.side)}.`);
152
+ if (!(ot in exports.BATCH_ORDER_TYPE))
153
+ throw new errors_js_1.InvalidRequest(`order type is one of fok, ioc, limit, market; not ${String(ot)}.`);
154
+ if (a.postOnly && ot !== 'limit')
155
+ throw new errors_js_1.InvalidRequest('Post-only applies to a resting limit order only.');
156
+ const size = (0, units_js_1.uint)(a.size18, units_js_1.U128, 'size18');
157
+ if (size === 0n)
158
+ throw new errors_js_1.InvalidRequest('size18 is zero.');
159
+ const price = (0, units_js_1.uint)(a.price8, units_js_1.U64, 'price8');
160
+ if (ot === 'market' && price !== 0n)
161
+ throw new errors_js_1.InvalidRequest('A market order carries no price (price8 0).');
162
+ if (ot !== 'market' && price === 0n)
163
+ throw new errors_js_1.InvalidRequest(`A ${ot} order needs a price.`);
164
+ return {
165
+ kind: 0, pairId: (0, units_js_1.safeNumber)((0, units_js_1.uint)(a.pairId, units_js_1.U32, 'pairId'), 'pairId'), side: exports.SIDE[a.side], size, price,
166
+ leverageBps: (0, units_js_1.safeNumber)((0, units_js_1.uint)(a.leverageBps ?? 10000, units_js_1.U32, 'leverageBps'), 'leverageBps'), orderType: exports.BATCH_ORDER_TYPE[ot],
167
+ reduceOnly: !!a.reduceOnly, postOnly: !!a.postOnly, clientNonce: (0, units_js_1.safeNumber)((0, units_js_1.uint)(a.clientNonce, units_js_1.U64, 'clientNonce'), 'clientNonce'), orderId: 0n,
168
+ };
169
+ }
170
+ function batchCancel(orderId) {
171
+ return { kind: 1, pairId: 0, side: 0, size: 0n, price: 0n, leverageBps: 0, orderType: 0, reduceOnly: false, postOnly: false, clientNonce: 0, orderId: (0, units_js_1.uint)(orderId, units_js_1.U64, 'orderId') };
172
+ }
173
+ function batchCancelByClientNonce(clientNonce) {
174
+ return { kind: 2, pairId: 0, side: 0, size: 0n, price: 0n, leverageBps: 0, orderType: 0, reduceOnly: false, postOnly: false, clientNonce: (0, units_js_1.safeNumber)((0, units_js_1.uint)(clientNonce, units_js_1.U64, 'clientNonce'), 'clientNonce'), orderId: 0n };
175
+ }
176
+ const BATCH_TYPE_NAME = { 0: 'market', 1: 'limit', 4: 'ioc', 5: 'fok' };
177
+ function batchActionBody(a) {
178
+ if (a.kind === 1)
179
+ return { kind: 'cancel', orderId: (0, units_js_1.safeNumber)(a.orderId, 'orderId') };
180
+ if (a.kind === 2)
181
+ return { kind: 'cancelByClientNonce', clientNonce: a.clientNonce };
182
+ return {
183
+ kind: 'place', pairId: a.pairId, side: SIDE_NAME[a.side], size_18dec: a.size.toString(), price_8dec: (0, units_js_1.safeNumber)(a.price, 'price8'),
184
+ leverageBps: a.leverageBps, orderType: BATCH_TYPE_NAME[a.orderType], postOnly: a.postOnly, reduceOnly: a.reduceOnly, clientNonce: a.clientNonce,
185
+ };
186
+ }
187
+ function batchBody(owner, nonce, actions, signature) {
188
+ return { owner, nonce, signature, actions: actions.map(batchActionBody) };
189
+ }
190
+ function cancelAllBody(owner, pairId, nonce, signature) {
191
+ return { owner, pairId, nonce, signature };
192
+ }
193
+ function modifyBody(owner, orderId, newPrice8, newSize18, clientNonce, signature) {
194
+ return { owner, orderId: (0, units_js_1.safeNumber)(orderId, 'orderId'), newPrice8dec: (0, units_js_1.safeNumber)(newPrice8, 'newPrice8'), newSize18dec: newSize18.toString(), clientNonce, signature };
195
+ }
196
+ function scheduleCancelBody(owner, cancelAtMs, nonce, signature) {
197
+ return { owner, cancel_at_ms: cancelAtMs, nonce, signature };
198
+ }
199
+ // ── Tick and lot ────────────────────────────────────────────────────────────────────────────────────────────────────
200
+ /** A price onto the pair's tick: a bid rounds down, an ask up (never more aggressive). Tick 0 = not enforced. */
201
+ function roundPrice(price8, tick8, side) {
202
+ if (tick8 <= 0n || price8 === 0n)
203
+ return price8;
204
+ const r = price8 % tick8;
205
+ if (r === 0n)
206
+ return price8;
207
+ return side === 'buy' ? price8 - r : price8 - r + tick8;
208
+ }
209
+ /** A size down onto the pair's lot (never more than asked). Lot 0 = not enforced. */
210
+ function roundSize(size18v, lot18) {
211
+ return lot18 <= 0n ? size18v : size18v - (size18v % lot18);
212
+ }
213
+ // ── Answers ─────────────────────────────────────────────────────────────────────────────────────────────────────────
214
+ exports.MESSAGES = {
215
+ invalid_body: 'The request was refused before any signature check; a field is missing or malformed.',
216
+ batch_size: 'A batch holds between 1 and the published maximum of actions.',
217
+ unknown_order: 'That order is not open on this account.',
218
+ insufficient_balance: "The account's free balance is too small for this.",
219
+ bad_signature: 'The signature does not belong to the account or to a live session key of it.',
220
+ not_active: 'This is not active on this network yet.',
221
+ mempool_full: 'The network is busy; try again in a moment.',
222
+ rate_limited: 'Order rate limit reached; this order was not placed. Cancels are never limited.',
223
+ rate_burst: 'Too many orders in one block; spread them over the next blocks.',
224
+ min_notional: 'The order is below the smallest order size.',
225
+ too_many_open_orders: 'The account has reached its open-order limit.',
226
+ price_band: 'The price is too far from the mark price.',
227
+ price: 'The price is not accepted (it may be too far from the mark price or off the tick size).',
228
+ };
229
+ function refusal(code, error = '', retryAfter = null) {
230
+ const text = error === null || error === undefined ? '' : String(error);
231
+ if ((code ?? '') === 'price_band' || /too far from (the )?mark/i.test(text))
232
+ return { code: 'price_band', message: exports.MESSAGES.price_band, detail: text, retryAfter };
233
+ const c = code || (text ? 'refused' : 'http_error');
234
+ return { code: c, message: exports.MESSAGES[c] ?? (text || 'The request was refused.'), detail: text, retryAfter };
235
+ }
236
+ /** Read a write's answer by its published shape. Anything else is a refusal, never a success. */
237
+ function readAnswer(status, body, retryAfter = null, meanings) {
238
+ const j = body && typeof body === 'object' && !Array.isArray(body) ? body : {};
239
+ const ra = retryAfter !== null && Number.isFinite(Number(retryAfter)) ? Number(retryAfter) : null;
240
+ if (status === 202 && j.status === 'submitted') {
241
+ const actions = [];
242
+ for (const a of Array.isArray(j.actions) ? j.actions : []) {
243
+ if (!a || typeof a !== 'object' || typeof a.index !== 'number')
244
+ continue;
245
+ const x = a;
246
+ actions.push(x.status === 'accepted' ? { index: x.index, accepted: true, refusal: null } : { index: x.index, accepted: false, refusal: refusal(x.code, x.error) });
247
+ }
248
+ return { submitted: true, status, refusal: null, actions, answer: body };
249
+ }
250
+ let code = typeof j.code === 'string' ? j.code : null;
251
+ if (status === 429 && !code)
252
+ code = 'mempool_full';
253
+ if (code === 'agent_refused') { // an agent check at intake: the reason key and its meaning, as the chain gives them
254
+ const reason = typeof j.reason === 'string' ? j.reason : '';
255
+ const meaning = typeof j.meaning === 'string' ? j.meaning : (meanings?.get(reason) ?? '');
256
+ return { submitted: false, status, refusal: { code: 'agent_refused', message: meaning || `The agent's action was refused (${reason || 'no reason given'}).`, detail: reason, retryAfter: ra }, actions: [], answer: body };
257
+ }
258
+ const err = j.error ?? j.reason ?? (status ? `HTTP ${status}` : '');
259
+ return { submitted: false, status, refusal: refusal(code, err, ra), actions: [], answer: body };
260
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readOpenOrders = readOpenOrders;
4
+ exports.readPositions = readPositions;
5
+ exports.saneLiquidationPrice = saneLiquidationPrice;
6
+ exports.readEquity = readEquity;
7
+ exports.refusalMeanings = refusalMeanings;
8
+ exports.readAgentRefusals = readAgentRefusals;
9
+ const errors_js_1 = require("./errors.js");
10
+ /** Parsers for the account reads. Anything without the published shape raises, never a guess. */
11
+ const big = (v, what, allowNull = false) => {
12
+ if (v === null || v === undefined) {
13
+ if (allowNull)
14
+ return null;
15
+ throw new errors_js_1.VordiumError('bad_read', `${what} is missing from the read.`);
16
+ }
17
+ if (typeof v === 'number' && Number.isSafeInteger(v))
18
+ return BigInt(v);
19
+ if (typeof v === 'string' && /^-?\d+$/.test(v))
20
+ return BigInt(v);
21
+ throw new errors_js_1.VordiumError('bad_read', `${what} is not a whole number in the read.`);
22
+ };
23
+ function readOpenOrders(j) {
24
+ if (!Array.isArray(j))
25
+ throw new errors_js_1.VordiumError('bad_read', 'The open-orders read is not a list.');
26
+ return j.map((o) => {
27
+ if (!o || typeof o !== 'object')
28
+ throw new errors_js_1.VordiumError('bad_read', 'An open order is not an object.');
29
+ const r = o;
30
+ const side = String(r.side ?? '').toLowerCase();
31
+ if (side !== 'buy' && side !== 'sell')
32
+ throw new errors_js_1.VordiumError('bad_read', `An open order has no side (${String(r.side)}).`);
33
+ const cn = big(r.client_nonce, 'client_nonce', true);
34
+ const ts = big(r.timestamp_ms, 'timestamp_ms', true);
35
+ return {
36
+ orderId: big(r.id, 'id'), clientNonce: cn === null ? null : Number(cn), pairId: Number(big(r.pair_id, 'pair_id')), side,
37
+ size18: big(r.size, 'size'), price8: big(r.price_8dec ?? 0, 'price_8dec'),
38
+ status: typeof r.status === 'string' ? r.status.toLowerCase() : null, signer: typeof r.agent === 'string' ? r.agent : null,
39
+ timestampMs: ts === null ? null : Number(ts),
40
+ };
41
+ });
42
+ }
43
+ function readPositions(j) {
44
+ if (!Array.isArray(j))
45
+ throw new errors_js_1.VordiumError('bad_read', 'The positions read is not a list.');
46
+ return j.map((p) => {
47
+ if (!p || typeof p !== 'object' || typeof p.is_long !== 'boolean')
48
+ throw new errors_js_1.VordiumError('bad_read', 'A position does not have the published shape.');
49
+ const r = p;
50
+ return {
51
+ positionId: big(r.id, 'id'), pairId: Number(big(r.pair_id, 'pair_id')), isLong: r.is_long, size18: big(r.size, 'size'),
52
+ entryPrice: big(r.entry_price, 'entry_price'), leverage: big(r.leverage, 'leverage'), margin6: big(r.margin, 'margin'),
53
+ unrealizedPnl6: big(r.unrealized_pnl, 'unrealized_pnl'), liquidationPrice: big(r.liquidation_price, 'liquidation_price'),
54
+ };
55
+ });
56
+ }
57
+ /**
58
+ * The chain's liquidation price, only when it makes sense for the position: below the entry for a long (and no lower
59
+ * than the entry at its leverage less 5%), above it for a short. Otherwise null — "not available", never a guess.
60
+ */
61
+ function saneLiquidationPrice(p) {
62
+ const lev = p.leverage >= 1n ? p.leverage : 1n;
63
+ const e = p.entryPrice, l = p.liquidationPrice;
64
+ if (e <= 0n || l <= 0n)
65
+ return null;
66
+ // long: entry × (1 − 1/lev) − 5% ≤ liq < entry ; short: entry < liq ≤ entry × (1 + 1/lev) + 5%
67
+ if (p.isLong) {
68
+ const floor = (e * (lev - 1n) * 100n) / (lev * 100n) - e / 20n;
69
+ return l < e && l >= floor ? l : null;
70
+ }
71
+ const ceil = (e * (lev + 1n)) / lev + e / 20n;
72
+ return l > e && l <= ceil ? l : null;
73
+ }
74
+ function readEquity(j) {
75
+ if (!j || typeof j !== 'object')
76
+ throw new errors_js_1.VordiumError('bad_read', 'The equity read is not an object.');
77
+ const r = j;
78
+ return {
79
+ usdcBalance6: big(r.usdc_balance, 'usdc_balance'), reservedOrders6: big(r.reserved_orders, 'reserved_orders'),
80
+ inPositions6: big(r.in_positions, 'in_positions'), freeBalance6: big(r.free_balance, 'free_balance'),
81
+ unrealizedPnl6: big(r.unrealized_pnl, 'unrealized_pnl'), totalEquity6: big(r.total_equity, 'total_equity'),
82
+ };
83
+ }
84
+ /**
85
+ * The meaning of each agent refusal reason, from the network spec's `agents.refusalCodes.reasons` (key → plain
86
+ * sentence). Empty when the network does not publish them; a reason without a published meaning is then shown as the
87
+ * chain wrote it.
88
+ */
89
+ function refusalMeanings(spec) {
90
+ const out = new Map();
91
+ const rc = spec && typeof spec === 'object' ? spec.agents?.refusalCodes : undefined;
92
+ const reasons = rc && typeof rc === 'object' ? rc.reasons : undefined;
93
+ if (Array.isArray(reasons)) {
94
+ for (const r of reasons) {
95
+ if (r && typeof r === 'object' && typeof r.key === 'string' && typeof r.meaning === 'string') {
96
+ out.set(r.key, r.meaning);
97
+ }
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+ function readAgentRefusals(j, meanings = new Map()) {
103
+ const list = j && typeof j === 'object' ? (j.events ?? j.records ?? j.items) : null;
104
+ if (!Array.isArray(list))
105
+ return [];
106
+ const out = [];
107
+ for (const e of list) {
108
+ if (!e || typeof e !== 'object')
109
+ continue;
110
+ const r = e;
111
+ if (r.kind !== 'agent_refused')
112
+ continue;
113
+ const data = (r.data && typeof r.data === 'object' ? r.data : r);
114
+ const reason = String(data.reason ?? r.reason ?? '');
115
+ out.push({
116
+ reason, meaning: meanings.get(reason) ?? null, height: typeof r.height === 'number' ? r.height : null,
117
+ timestampMs: typeof r.at_ms === 'number' ? r.at_ms : typeof r.timestamp_ms === 'number' ? r.timestamp_ms : null, record: r,
118
+ });
119
+ }
120
+ return out;
121
+ }
@@ -0,0 +1,252 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NO_RULES = exports.PLACE_PRICE_STEP_8DEC = exports.SpecsUnavailable = exports.OrderValueError = void 0;
4
+ exports.scaled = scaled;
5
+ exports.whole = whole;
6
+ exports.onStep = onStep;
7
+ exports.priceStep = priceStep;
8
+ exports.sizeStep = sizeStep;
9
+ exports.price8OnTick = price8OnTick;
10
+ exports.size18OnLot = size18OnLot;
11
+ exports.trigger8OnTick = trigger8OnTick;
12
+ exports.snapPrice8 = snapPrice8;
13
+ exports.snapSize18 = snapSize18;
14
+ exports.snapTrigger8 = snapTrigger8;
15
+ exports.checkSize = checkSize;
16
+ exports.notional6 = notional6;
17
+ exports.checkNotional = checkNotional;
18
+ exports.leverageBpsExact = leverageBpsExact;
19
+ exports.pairSpecs = pairSpecs;
20
+ exports.selectSpec = selectSpec;
21
+ exports.marketRules = marketRules;
22
+ const errors_js_1 = require("./errors.js");
23
+ const units_js_1 = require("./units.js");
24
+ /**
25
+ * Exact order units on each market's tick and lot.
26
+ *
27
+ * The chain keeps a price step (`tick_8dec`) and a size step (`lot_18dec`) per market, published in `GET /markets/specs`,
28
+ * and does not apply an order that is off them. Every order this SDK signs is put on them first:
29
+ *
30
+ * - a number is read exactly from its decimal form: a decimal string ("2420.5", ".5", "1e-4"), a bigint, or a number from
31
+ * its shortest decimal form (0.1 is 0.1). Nothing is multiplied as a floating-point number;
32
+ * - a limit price rounds toward the passive side: a buy's DOWN, a sell's UP onto the tick (never a worse price than
33
+ * asked). On `/order/place` it is also kept at 6 decimals (a multiple of 100 in 8-decimal units);
34
+ * - a take-profit / stop-loss trigger goes to the NEAREST tick (a half tick rounds up);
35
+ * - a size rounds DOWN onto the lot (never more than asked);
36
+ * - a tick or lot of 0 means the network sets none: only the signed unit applies.
37
+ *
38
+ * Refused before anything is signed ({@link OrderValueError}): a size that rounds to 0 or is below the market's smallest
39
+ * size, a limit price that rounds to 0, a priced order below the network's smallest order value, a market the network does
40
+ * not list.
41
+ */
42
+ class OrderValueError extends errors_js_1.InvalidRequest {
43
+ constructor(message) {
44
+ super(message);
45
+ this.name = 'OrderValueError';
46
+ }
47
+ }
48
+ exports.OrderValueError = OrderValueError;
49
+ /** The market rules (`GET /markets/specs`) could not be read, so no order value can be put on its step. */
50
+ class SpecsUnavailable extends OrderValueError {
51
+ constructor(message) {
52
+ super(message);
53
+ this.name = 'SpecsUnavailable';
54
+ }
55
+ }
56
+ exports.SpecsUnavailable = SpecsUnavailable;
57
+ const PRICE_DECIMALS = 8;
58
+ const SIZE_DECIMALS = 18;
59
+ exports.PLACE_PRICE_STEP_8DEC = 100n;
60
+ const PLAIN = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
61
+ /** `x` × 10^`decimals` as an exact fraction [numerator, denominator]. */
62
+ function scaled(x, decimals, what = 'a value') {
63
+ let s;
64
+ if (typeof x === 'bigint') {
65
+ if (x < 0n)
66
+ throw new OrderValueError(`${what} cannot be negative (${x}).`);
67
+ return [x * 10n ** BigInt(decimals), 1n];
68
+ }
69
+ else if (typeof x === 'number') {
70
+ if (!Number.isFinite(x))
71
+ throw new OrderValueError(`${what} is not a finite number (${x}).`);
72
+ if (x < 0)
73
+ throw new OrderValueError(`${what} cannot be negative (${x}).`);
74
+ s = (0, units_js_1.numberToDecimal)(x);
75
+ }
76
+ else if (typeof x === 'string') {
77
+ if (!PLAIN.test(x))
78
+ throw new OrderValueError(`${what} is not a plain decimal number (${JSON.stringify(x)}).`);
79
+ s = x;
80
+ }
81
+ else {
82
+ throw new OrderValueError(`${what} is not a number (${String(x)}).`);
83
+ }
84
+ const [mant, expS] = s.toLowerCase().split('e');
85
+ const [ip, fp = ''] = mant.split('.');
86
+ let n = BigInt((ip || '0') + fp || '0');
87
+ let exp = BigInt(decimals) - BigInt(fp.length) + (expS === undefined ? 0n : BigInt(expS));
88
+ let d = 1n;
89
+ if (exp >= 0n)
90
+ n *= 10n ** exp;
91
+ else
92
+ d = 10n ** -exp;
93
+ return [n, d];
94
+ }
95
+ /** A count of base units: a whole number (bigint, safe-integer number, digit string, or an integral decimal). */
96
+ function whole(x, what = 'a value') {
97
+ const [n, d] = scaled(x, 0, what);
98
+ if (n % d !== 0n)
99
+ throw new OrderValueError(`${what} is a count of base units and must be a whole number (${String(x)}).`);
100
+ return n / d;
101
+ }
102
+ function gcd(a, b) {
103
+ while (b)
104
+ [a, b] = [b, a % b];
105
+ return a;
106
+ }
107
+ /** num/den onto a multiple of `step`: down, up, or nearest (a half step rounds up). */
108
+ function onStep(num, den, step, mode) {
109
+ if (step <= 0n)
110
+ throw new RangeError('a step is at least 1');
111
+ const q = num / (den * step), r = num % (den * step);
112
+ if (r === 0n || mode === 'down')
113
+ return q * step;
114
+ if (mode === 'up')
115
+ return (q + 1n) * step;
116
+ return 2n * r >= den * step ? (q + 1n) * step : q * step;
117
+ }
118
+ function sideOf(side) {
119
+ if (side === 'buy' || side === 0)
120
+ return 'buy';
121
+ if (side === 'sell' || side === 1)
122
+ return 'sell';
123
+ throw new OrderValueError(`side is buy or sell, not ${String(side)}.`);
124
+ }
125
+ function priceStep(spec, placeRoute = true) {
126
+ const tick = spec?.tick8 ?? 0n;
127
+ const base = placeRoute ? exports.PLACE_PRICE_STEP_8DEC : 1n;
128
+ return tick > 0n ? (tick * base) / gcd(tick, base) : base;
129
+ }
130
+ function sizeStep(spec) {
131
+ const lot = spec?.lot18 ?? 0n;
132
+ return lot > 0n ? lot : 1n;
133
+ }
134
+ function inPrice(out, what) {
135
+ if (out <= 0n)
136
+ throw new OrderValueError(`${what} rounds to 0 on this market's tick.`);
137
+ if (out > units_js_1.U64)
138
+ throw new OrderValueError(`${what} is out of range.`);
139
+ return out;
140
+ }
141
+ /** A limit price as the signed 8-decimal integer on the tick: a buy's rounds down, a sell's up. */
142
+ function price8OnTick(price, spec, side, placeRoute = true) {
143
+ const [n, d] = scaled(price, PRICE_DECIMALS, 'a limit price');
144
+ return inPrice(onStep(n, d, priceStep(spec, placeRoute), sideOf(side) === 'buy' ? 'down' : 'up'), `the limit price ${String(price)}`);
145
+ }
146
+ /** A size as the signed 18-decimal integer, down onto the lot. */
147
+ function size18OnLot(size, spec) {
148
+ const [n, d] = scaled(size, SIZE_DECIMALS, 'a size');
149
+ return checkSize(onStep(n, d, sizeStep(spec), 'down'), spec, size);
150
+ }
151
+ /** A take-profit / stop-loss trigger as the 8-decimal integer, to the nearest tick (0 = no trigger). */
152
+ function trigger8OnTick(price, spec) {
153
+ const [n, d] = scaled(price, PRICE_DECIMALS, 'a trigger price');
154
+ if (n === 0n)
155
+ return 0n;
156
+ return inPrice(onStep(n, d, priceStep(spec, false), 'nearest'), `the trigger price ${String(price)}`);
157
+ }
158
+ /** A signed 8-decimal price already in base units, onto the tick by the passive rule (0 stays 0: no price). */
159
+ function snapPrice8(price8, spec, side, placeRoute = false) {
160
+ const p = whole(price8, 'price8');
161
+ if (p === 0n)
162
+ return 0n;
163
+ return inPrice(onStep(p, 1n, priceStep(spec, placeRoute), sideOf(side) === 'buy' ? 'down' : 'up'), `the price ${p}`);
164
+ }
165
+ function snapSize18(size18, spec) {
166
+ const s = whole(size18, 'size18');
167
+ return checkSize(s - (s % sizeStep(spec)), spec, size18);
168
+ }
169
+ function snapTrigger8(price8, spec) {
170
+ const p = whole(price8, 'trigger price');
171
+ if (p === 0n)
172
+ return 0n;
173
+ return inPrice(onStep(p, 1n, priceStep(spec, false), 'nearest'), `the trigger price ${p}`);
174
+ }
175
+ function checkSize(size18, spec, asked) {
176
+ if (size18 <= 0n) {
177
+ const lot = sizeStep(spec);
178
+ throw new OrderValueError(lot > 1n ? `the size ${String(asked)} rounds to 0 on this market's lot (${lot} base units).` : `the size ${String(asked)} is below one base unit.`);
179
+ }
180
+ if (size18 > units_js_1.U128)
181
+ throw new OrderValueError('the size is out of range.');
182
+ const min = spec?.minSize18 ?? 0n;
183
+ if (min > 0n && size18 < min)
184
+ throw new OrderValueError(`the size is below this market's smallest order (${min} base units).`);
185
+ return size18;
186
+ }
187
+ /** size × price in USDC base units (6 decimals), rounded down. */
188
+ function notional6(size18, price8) {
189
+ return (size18 * price8) / 10n ** 20n;
190
+ }
191
+ function checkNotional(size18, price8, spec) {
192
+ const min = spec?.minNotional6 ?? 0n;
193
+ if (min > 0n && price8 > 0n && notional6(size18, price8) < min) {
194
+ throw new OrderValueError(`the order's value is below the smallest order the network takes (${Number(min) / 1e6} USDC).`);
195
+ }
196
+ }
197
+ /** Leverage (2 or "2.5") as basis points, exactly (half to even). */
198
+ function leverageBpsExact(leverage) {
199
+ const [n, d] = scaled(leverage, 4, 'leverage');
200
+ const q = n / d, r = n % d;
201
+ return q + (2n * r > d || (2n * r === d && q % 2n === 1n) ? 1n : 0n);
202
+ }
203
+ // ── the market rules ────────────────────────────────────────────────────────────────────────────────────────────
204
+ /** Every market without a tick, lot or minimum: for dry runs and offline tests. Never what a network publishes. */
205
+ exports.NO_RULES = Object.freeze({ noRules: true });
206
+ function count(v) {
207
+ if (typeof v === 'bigint' && v >= 0n)
208
+ return v;
209
+ if (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0)
210
+ return BigInt(v);
211
+ if (typeof v === 'string' && /^\d+$/.test(v))
212
+ return BigInt(v);
213
+ if (v === undefined || v === null || v === '')
214
+ return 0n;
215
+ throw new OrderValueError(`a market rule is not a whole number (${String(v)}).`);
216
+ }
217
+ /** Each market's tick, lot and smallest size from a `/markets/specs` read, with the network's smallest order value. */
218
+ function pairSpecs(read) {
219
+ const s = read && typeof read === 'object' ? read.specs : null;
220
+ if (!s || typeof s !== 'object')
221
+ throw new OrderValueError('the market rules read has no specs; nothing was signed.');
222
+ const sp = s;
223
+ const minNotional6 = count(sp.min_order_notional_6dec);
224
+ const out = new Map();
225
+ for (const p of Array.isArray(sp.pairs) ? sp.pairs : []) {
226
+ const pr = (p && typeof p === 'object' ? p.pair : null);
227
+ const pid = pr?.pair_id;
228
+ if (typeof pid !== 'number' || !Number.isSafeInteger(pid))
229
+ continue;
230
+ const q = p;
231
+ out.set(pid, { pairId: pid, symbol: String(pr?.symbol ?? pr?.name ?? pid), tick8: count(q.tick_8dec), lot18: count(q.lot_18dec),
232
+ minSize18: count(pr?.min_size_18dec), minNotional6 });
233
+ }
234
+ return out;
235
+ }
236
+ /** One market's rules; a market the read does not list is refused. */
237
+ function selectSpec(rules, pairId) {
238
+ if ('noRules' in rules)
239
+ return { pairId, symbol: String(pairId), tick8: 0n, lot18: 0n, minSize18: 0n, minNotional6: 0n };
240
+ const s = rules.get(pairId);
241
+ if (!s)
242
+ throw new OrderValueError(`the network lists no market ${pairId} (GET /markets/specs).`);
243
+ return s;
244
+ }
245
+ /** A /markets/specs read, a parsed map, or NO_RULES, as market rules. */
246
+ function marketRules(x) {
247
+ if (x === exports.NO_RULES)
248
+ return exports.NO_RULES;
249
+ if (x instanceof Map)
250
+ return x;
251
+ return pairSpecs(x);
252
+ }