@perpbrain/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.
- package/LICENSE +21 -0
- package/README.md +25 -2
- package/dist/cjs/card.d.ts +2 -0
- package/dist/cjs/card.js +311 -0
- package/dist/cjs/cli.d.ts +3 -0
- package/dist/cjs/cli.js +33 -0
- package/dist/cjs/guarded.d.ts +12 -0
- package/dist/cjs/guarded.js +52 -0
- package/dist/cjs/guards.d.ts +154 -0
- package/dist/cjs/guards.js +855 -0
- package/dist/cjs/index.d.ts +16 -0
- package/dist/cjs/index.js +66 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/receipt.d.ts +45 -0
- package/dist/cjs/receipt.js +855 -0
- package/dist/cjs/study.d.ts +29 -0
- package/dist/cjs/study.js +259 -0
- package/dist/cjs/vendor/costs.d.ts +64 -0
- package/dist/cjs/vendor/costs.js +247 -0
- package/dist/cjs/vendor/execution.d.ts +44 -0
- package/dist/cjs/vendor/execution.js +132 -0
- package/dist/cjs/vendor/fees.d.ts +17 -0
- package/dist/cjs/vendor/fees.js +82 -0
- package/dist/cjs/vendor/funding_adapter.d.ts +11 -0
- package/dist/cjs/vendor/funding_adapter.js +33 -0
- package/dist/cjs/vendor/info.d.ts +24 -0
- package/dist/cjs/vendor/info.js +55 -0
- package/dist/cjs/vendor/queries.d.ts +69 -0
- package/dist/cjs/vendor/queries.js +210 -0
- package/dist/cjs/vendor/rateLimit.d.ts +14 -0
- package/dist/cjs/vendor/rateLimit.js +57 -0
- package/dist/cjs/vendor/simDefaults.d.ts +31 -0
- package/dist/cjs/vendor/simDefaults.js +49 -0
- package/dist/cjs/vendor/simulate.d.ts +130 -0
- package/dist/cjs/vendor/simulate.js +610 -0
- package/dist/esm/card.d.ts +2 -0
- package/dist/esm/card.js +308 -0
- package/dist/esm/cli.d.ts +3 -0
- package/dist/esm/cli.js +31 -0
- package/dist/esm/guarded.d.ts +12 -0
- package/dist/esm/guarded.js +49 -0
- package/dist/esm/guards.d.ts +154 -0
- package/dist/esm/guards.js +841 -0
- package/dist/esm/index.d.ts +16 -0
- package/dist/esm/index.js +20 -0
- package/dist/esm/receipt.d.ts +45 -0
- package/dist/esm/receipt.js +839 -0
- package/dist/esm/study.d.ts +29 -0
- package/dist/esm/study.js +249 -0
- package/dist/esm/vendor/costs.d.ts +64 -0
- package/dist/esm/vendor/costs.js +240 -0
- package/dist/esm/vendor/execution.d.ts +44 -0
- package/dist/esm/vendor/execution.js +122 -0
- package/dist/esm/vendor/fees.d.ts +17 -0
- package/dist/esm/vendor/fees.js +74 -0
- package/dist/esm/vendor/funding_adapter.d.ts +11 -0
- package/dist/esm/vendor/funding_adapter.js +30 -0
- package/dist/esm/vendor/info.d.ts +24 -0
- package/dist/esm/vendor/info.js +49 -0
- package/dist/esm/vendor/queries.d.ts +69 -0
- package/dist/esm/vendor/queries.js +196 -0
- package/dist/esm/vendor/rateLimit.d.ts +14 -0
- package/dist/esm/vendor/rateLimit.js +53 -0
- package/dist/esm/vendor/simDefaults.d.ts +31 -0
- package/dist/esm/vendor/simDefaults.js +44 -0
- package/dist/esm/vendor/simulate.d.ts +130 -0
- package/dist/esm/vendor/simulate.js +605 -0
- package/package.json +64 -4
|
@@ -0,0 +1,855 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** Owner presets and a tighten-only runtime. Losses are still possible. */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.GuardSession = exports.PRESETS = exports.GuardBlocked = exports.GuardConfigError = exports.GuardLoosenError = exports.CODES = exports.HARD_MAX_ORDER_RATE = exports.HARD_MAX_OPEN_POSITIONS = exports.HARD_MAX_SLIPPAGE_BPS = exports.HARD_MAX_DAILY_LOSS_PCT = exports.TOP_OI_COUNT = exports.STALE_HALT_MS = exports.STALE_BLOCK_MS = void 0;
|
|
5
|
+
exports.defaultSnapshot = defaultSnapshot;
|
|
6
|
+
exports.snapshotFromCoins = snapshotFromCoins;
|
|
7
|
+
exports.wireCode = wireCode;
|
|
8
|
+
exports.nextUtcMidnightMs = nextUtcMidnightMs;
|
|
9
|
+
exports.defaultGuards = defaultGuards;
|
|
10
|
+
exports.fromConfig = fromConfig;
|
|
11
|
+
exports.survivalReport = survivalReport;
|
|
12
|
+
const node_crypto_1 = require("node:crypto");
|
|
13
|
+
const SCALE = 18;
|
|
14
|
+
const SCALE_FACTOR = 10n ** BigInt(SCALE);
|
|
15
|
+
const DAY_MS = 86_400_000;
|
|
16
|
+
exports.STALE_BLOCK_MS = 2_000;
|
|
17
|
+
exports.STALE_HALT_MS = 5_000;
|
|
18
|
+
exports.TOP_OI_COUNT = 20;
|
|
19
|
+
exports.HARD_MAX_DAILY_LOSS_PCT = "25";
|
|
20
|
+
exports.HARD_MAX_SLIPPAGE_BPS = "300";
|
|
21
|
+
exports.HARD_MAX_OPEN_POSITIONS = 50;
|
|
22
|
+
exports.HARD_MAX_ORDER_RATE = 10;
|
|
23
|
+
exports.CODES = [
|
|
24
|
+
"coin_not_allowed",
|
|
25
|
+
"notional_exceeded",
|
|
26
|
+
"aggregate_notional",
|
|
27
|
+
"depth_cap",
|
|
28
|
+
"leverage_exceeded",
|
|
29
|
+
"open_positions_exceeded",
|
|
30
|
+
"daily_stop_reduce_only",
|
|
31
|
+
"slippage_exceeded",
|
|
32
|
+
"order_rate",
|
|
33
|
+
"stale_data",
|
|
34
|
+
"stale_halt",
|
|
35
|
+
"kill_switch",
|
|
36
|
+
];
|
|
37
|
+
const LIMIT_NAMES = [
|
|
38
|
+
"maxNotionalUsd",
|
|
39
|
+
"maxLeverage",
|
|
40
|
+
"maxOpenPositions",
|
|
41
|
+
"dailyLossPct",
|
|
42
|
+
"maxSlippageBps",
|
|
43
|
+
"orderRatePerSec",
|
|
44
|
+
"allowedCoins",
|
|
45
|
+
];
|
|
46
|
+
class GuardLoosenError extends Error {
|
|
47
|
+
name = "GuardLoosenError";
|
|
48
|
+
}
|
|
49
|
+
exports.GuardLoosenError = GuardLoosenError;
|
|
50
|
+
class GuardConfigError extends Error {
|
|
51
|
+
name = "GuardConfigError";
|
|
52
|
+
}
|
|
53
|
+
exports.GuardConfigError = GuardConfigError;
|
|
54
|
+
class GuardBlocked extends Error {
|
|
55
|
+
name = "GuardBlocked";
|
|
56
|
+
violations;
|
|
57
|
+
headroom;
|
|
58
|
+
result;
|
|
59
|
+
constructor(violations, headroom, result) {
|
|
60
|
+
if (violations.length === 0) {
|
|
61
|
+
throw new Error("GuardBlocked requires a violation");
|
|
62
|
+
}
|
|
63
|
+
const code = wireCode(violations[0]?.code ?? "kill_switch");
|
|
64
|
+
super(code);
|
|
65
|
+
this.violations = violations;
|
|
66
|
+
this.headroom = headroom;
|
|
67
|
+
this.result = result;
|
|
68
|
+
}
|
|
69
|
+
get code() {
|
|
70
|
+
return this.message;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
exports.GuardBlocked = GuardBlocked;
|
|
74
|
+
exports.PRESETS = Object.freeze({
|
|
75
|
+
conservative: Object.freeze({
|
|
76
|
+
maxLeverage: "3",
|
|
77
|
+
maxNotionalUsd: "10000",
|
|
78
|
+
dailyLossPct: "3",
|
|
79
|
+
maxOpenPositions: 3,
|
|
80
|
+
maxSlippageBps: "25",
|
|
81
|
+
orderRatePerSec: 2,
|
|
82
|
+
}),
|
|
83
|
+
standard: Object.freeze({
|
|
84
|
+
maxLeverage: "5",
|
|
85
|
+
maxNotionalUsd: "25000",
|
|
86
|
+
dailyLossPct: "5",
|
|
87
|
+
maxOpenPositions: 5,
|
|
88
|
+
maxSlippageBps: "50",
|
|
89
|
+
orderRatePerSec: 5,
|
|
90
|
+
}),
|
|
91
|
+
pro: Object.freeze({
|
|
92
|
+
maxLeverage: "10",
|
|
93
|
+
maxNotionalUsd: "250000",
|
|
94
|
+
dailyLossPct: "10",
|
|
95
|
+
maxOpenPositions: 15,
|
|
96
|
+
maxSlippageBps: "100",
|
|
97
|
+
orderRatePerSec: 10,
|
|
98
|
+
}),
|
|
99
|
+
});
|
|
100
|
+
const RECORDED = Object.freeze([
|
|
101
|
+
Object.freeze({ name: "BTC", maxLeverage: 40, openInterest: "42321.38294" }),
|
|
102
|
+
Object.freeze({ name: "ETH", maxLeverage: 25, openInterest: "1088724.0126" }),
|
|
103
|
+
]);
|
|
104
|
+
let cachedSnapshot = null;
|
|
105
|
+
function defaultSnapshot() {
|
|
106
|
+
cachedSnapshot ??= snapshotFromCoins(RECORDED);
|
|
107
|
+
return cachedSnapshot;
|
|
108
|
+
}
|
|
109
|
+
function snapshotFromCoins(coins) {
|
|
110
|
+
const ordered = [...coins].sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
|
|
111
|
+
const payload = ordered.map((coin) => ({
|
|
112
|
+
max_leverage: coin.maxLeverage,
|
|
113
|
+
name: coin.name,
|
|
114
|
+
open_interest: plain(parseDecimal(coin.openInterest)),
|
|
115
|
+
}));
|
|
116
|
+
const snapshotId = (0, node_crypto_1.createHash)("sha256").update(JSON.stringify(payload)).digest("hex");
|
|
117
|
+
return Object.freeze({ snapshotId, coins: Object.freeze(ordered.map((coin) => Object.freeze({ ...coin }))) });
|
|
118
|
+
}
|
|
119
|
+
function wireCode(code) {
|
|
120
|
+
return `GUARD_BLOCKED:${code.toUpperCase()}`;
|
|
121
|
+
}
|
|
122
|
+
function nextUtcMidnightMs(nowMs) {
|
|
123
|
+
if (!Number.isInteger(nowMs) || nowMs < 0) {
|
|
124
|
+
throw new Error("nowMs must be >= 0");
|
|
125
|
+
}
|
|
126
|
+
return (Math.floor(nowMs / DAY_MS) + 1) * DAY_MS;
|
|
127
|
+
}
|
|
128
|
+
function defaultGuards() {
|
|
129
|
+
return fromConfig("standard");
|
|
130
|
+
}
|
|
131
|
+
function fromConfig(preset = "standard", overrides = null, acknowledgeLoosenedLimits = false, snapshot = null) {
|
|
132
|
+
if (!isPreset(preset)) {
|
|
133
|
+
throw new GuardConfigError("unknown preset");
|
|
134
|
+
}
|
|
135
|
+
const chosen = snapshot ?? defaultSnapshot();
|
|
136
|
+
const base = exports.PRESETS[preset];
|
|
137
|
+
const values = {
|
|
138
|
+
maxLeverage: base.maxLeverage,
|
|
139
|
+
maxNotionalUsd: base.maxNotionalUsd,
|
|
140
|
+
dailyLossPct: base.dailyLossPct,
|
|
141
|
+
maxOpenPositions: base.maxOpenPositions,
|
|
142
|
+
maxSlippageBps: base.maxSlippageBps,
|
|
143
|
+
orderRatePerSec: base.orderRatePerSec,
|
|
144
|
+
allowedCoins: namesOf(chosen),
|
|
145
|
+
};
|
|
146
|
+
const supplied = overrides ?? {};
|
|
147
|
+
if (typeof supplied !== "object" || supplied === null || Array.isArray(supplied)) {
|
|
148
|
+
throw new TypeError("overrides must be an object");
|
|
149
|
+
}
|
|
150
|
+
const unknown = Object.keys(supplied)
|
|
151
|
+
.filter((key) => !LIMIT_NAMES.includes(key))
|
|
152
|
+
.sort();
|
|
153
|
+
if (unknown.length > 0) {
|
|
154
|
+
throw new TypeError(`unknown limit: ${unknown.join(", ")}`);
|
|
155
|
+
}
|
|
156
|
+
for (const name of LIMIT_NAMES) {
|
|
157
|
+
if (supplied[name] !== undefined) {
|
|
158
|
+
values[name] = applyOverride(name, values[name], supplied[name], acknowledgeLoosenedLimits, chosen);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return create({
|
|
162
|
+
preset,
|
|
163
|
+
maxLeverage: String(values.maxLeverage),
|
|
164
|
+
maxNotionalUsd: values.maxNotionalUsd === null ? null : String(values.maxNotionalUsd),
|
|
165
|
+
dailyLossPct: String(values.dailyLossPct),
|
|
166
|
+
maxOpenPositions: Number(values.maxOpenPositions),
|
|
167
|
+
maxSlippageBps: String(values.maxSlippageBps),
|
|
168
|
+
orderRatePerSec: Number(values.orderRatePerSec),
|
|
169
|
+
allowedCoins: values.allowedCoins,
|
|
170
|
+
}, chosen);
|
|
171
|
+
}
|
|
172
|
+
class GuardSession {
|
|
173
|
+
limits;
|
|
174
|
+
owner;
|
|
175
|
+
killSwitch = false;
|
|
176
|
+
reduceOnlyUntilMs = null;
|
|
177
|
+
orderTimesMs = [];
|
|
178
|
+
positions = new Map();
|
|
179
|
+
constructor(limits, owner = null, killSwitch = false) {
|
|
180
|
+
this.limits = limits;
|
|
181
|
+
this.owner = owner ?? limits;
|
|
182
|
+
this.killSwitch = killSwitch;
|
|
183
|
+
}
|
|
184
|
+
static fromConfig(preset = "standard", overrides = null, acknowledgeLoosenedLimits = false, snapshot = null) {
|
|
185
|
+
return new GuardSession(fromConfig(preset, overrides, acknowledgeLoosenedLimits, snapshot));
|
|
186
|
+
}
|
|
187
|
+
tighten(overrides = {}) {
|
|
188
|
+
this.limits = this.limits.tighten(overrides);
|
|
189
|
+
return this.limits;
|
|
190
|
+
}
|
|
191
|
+
engageKillSwitch() {
|
|
192
|
+
this.killSwitch = true;
|
|
193
|
+
}
|
|
194
|
+
restart(preset = "standard", overrides = null, acknowledgeLoosenedLimits = false, snapshot = null) {
|
|
195
|
+
const owner = fromConfig(preset, overrides, acknowledgeLoosenedLimits, snapshot);
|
|
196
|
+
const keep = this.killSwitch && owner.limitsHash === this.owner.limitsHash;
|
|
197
|
+
return new GuardSession(owner, owner, keep);
|
|
198
|
+
}
|
|
199
|
+
reduceOnly(nowMs) {
|
|
200
|
+
return this.reduceOnlyUntilMs !== null && nowMs < this.reduceOnlyUntilMs;
|
|
201
|
+
}
|
|
202
|
+
openPositionCount() {
|
|
203
|
+
return this.positions.size;
|
|
204
|
+
}
|
|
205
|
+
aggregateNotionalUsd() {
|
|
206
|
+
return plain(this.aggregateNotional());
|
|
207
|
+
}
|
|
208
|
+
coinNotional(coin) {
|
|
209
|
+
return plain(this.positions.get(coin) ?? 0n);
|
|
210
|
+
}
|
|
211
|
+
portfolio() {
|
|
212
|
+
return {
|
|
213
|
+
openPositionCount: this.openPositionCount(),
|
|
214
|
+
aggregateNotionalUsd: this.aggregateNotionalUsd(),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
check(intent, options = {}) {
|
|
218
|
+
const { record: shouldRecord = true, ...rest } = options;
|
|
219
|
+
const clock = rest.nowMs ?? intent.nowMs ?? 0;
|
|
220
|
+
const loss = decimalText(intent.dailyLossPct ?? "0", "dailyLossPct");
|
|
221
|
+
if (compare(loss, this.limits.dailyLossPct) >= 0) {
|
|
222
|
+
this.reduceOnlyUntilMs = nextUtcMidnightMs(clock);
|
|
223
|
+
}
|
|
224
|
+
const recent = this.orderTimesMs.filter((stamp) => clock - stamp < 1000 && clock >= stamp);
|
|
225
|
+
const result = this.limits.check(intent, {
|
|
226
|
+
...rest,
|
|
227
|
+
nowMs: clock,
|
|
228
|
+
killSwitch: this.killSwitch,
|
|
229
|
+
reduceOnly: this.reduceOnly(clock),
|
|
230
|
+
recentOrders: recent.length,
|
|
231
|
+
portfolioNotionalUsd: this.aggregateNotionalUsd(),
|
|
232
|
+
portfolioPositions: this.openPositionCount(),
|
|
233
|
+
portfolioCoinNotionalUsd: this.coinNotional(intent.coin),
|
|
234
|
+
});
|
|
235
|
+
if (shouldRecord && result.ok) {
|
|
236
|
+
this.remember(intent);
|
|
237
|
+
if (kindOf(intent) === "open") {
|
|
238
|
+
this.orderTimesMs.push(clock);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
243
|
+
aggregateNotional() {
|
|
244
|
+
let total = 0n;
|
|
245
|
+
for (const value of this.positions.values()) {
|
|
246
|
+
total += value;
|
|
247
|
+
}
|
|
248
|
+
return total;
|
|
249
|
+
}
|
|
250
|
+
remember(intent) {
|
|
251
|
+
const kind = kindOf(intent);
|
|
252
|
+
const coin = intent.coin;
|
|
253
|
+
const notional = parseDecimal(decimalText(intent.notionalUsd, "notionalUsd"));
|
|
254
|
+
const held = this.positions.get(coin) ?? 0n;
|
|
255
|
+
switch (kind) {
|
|
256
|
+
case "open":
|
|
257
|
+
if (notional === 0n) {
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
this.positions.set(coin, held + notional);
|
|
261
|
+
return;
|
|
262
|
+
case "reduce": {
|
|
263
|
+
const left = held - notional;
|
|
264
|
+
if (left <= 0n) {
|
|
265
|
+
this.positions.delete(coin);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
this.positions.set(coin, left);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
case "close":
|
|
272
|
+
this.positions.delete(coin);
|
|
273
|
+
return;
|
|
274
|
+
default: {
|
|
275
|
+
const unexpected = kind;
|
|
276
|
+
throw new Error(`unexpected intent kind: ${String(unexpected)}`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
headroom(nowMs = 0, snapshot = null) {
|
|
281
|
+
const coin = this.limits.allowedCoins[0] ?? "BTC";
|
|
282
|
+
return this.check({
|
|
283
|
+
coin,
|
|
284
|
+
notionalUsd: "0",
|
|
285
|
+
leverage: "0",
|
|
286
|
+
openPositions: 0,
|
|
287
|
+
dailyLossPct: "0",
|
|
288
|
+
slippageBps: "0",
|
|
289
|
+
ageMs: 0,
|
|
290
|
+
opening: false,
|
|
291
|
+
intentKind: "close",
|
|
292
|
+
orderSide: "sell",
|
|
293
|
+
}, { snapshot, nowMs, record: false }).headroom;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
exports.GuardSession = GuardSession;
|
|
297
|
+
function survivalReport(days) {
|
|
298
|
+
const grouped = new Map();
|
|
299
|
+
for (const day of days) {
|
|
300
|
+
const rows = grouped.get(day.account) ?? [];
|
|
301
|
+
rows.push(day);
|
|
302
|
+
grouped.set(day.account, rows);
|
|
303
|
+
}
|
|
304
|
+
const counts = new Map();
|
|
305
|
+
for (const name of Object.keys(exports.PRESETS)) {
|
|
306
|
+
counts.set(name, { accounts: 0, survived: 0 });
|
|
307
|
+
}
|
|
308
|
+
for (const rows of grouped.values()) {
|
|
309
|
+
if (rows.length !== 30) {
|
|
310
|
+
throw new Error("each account needs 30 days");
|
|
311
|
+
}
|
|
312
|
+
const preset = rows[0]?.preset;
|
|
313
|
+
if (!isPreset(preset)) {
|
|
314
|
+
throw new Error("unknown preset");
|
|
315
|
+
}
|
|
316
|
+
if (rows.some((day) => day.preset !== preset)) {
|
|
317
|
+
throw new Error("an account stays on one preset");
|
|
318
|
+
}
|
|
319
|
+
const tally = counts.get(preset);
|
|
320
|
+
if (tally === undefined) {
|
|
321
|
+
throw new Error("unknown preset");
|
|
322
|
+
}
|
|
323
|
+
tally.accounts += 1;
|
|
324
|
+
if (survived(preset, rows)) {
|
|
325
|
+
tally.survived += 1;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const byPreset = {};
|
|
329
|
+
for (const [name, tally] of counts) {
|
|
330
|
+
const share = tally.accounts === 0 ? "0" : plain((BigInt(tally.survived) * SCALE_FACTOR) / BigInt(tally.accounts));
|
|
331
|
+
byPreset[name] = { accounts: tally.accounts, survived: tally.survived, share };
|
|
332
|
+
}
|
|
333
|
+
return { windowDays: 30, byPreset };
|
|
334
|
+
}
|
|
335
|
+
function survived(preset, days) {
|
|
336
|
+
const stop = exports.PRESETS[preset].dailyLossPct;
|
|
337
|
+
return days.every((day) => !day.killSwitch && compare(decimalText(day.lossPct, "lossPct"), stop) < 0);
|
|
338
|
+
}
|
|
339
|
+
function create(values, snapshot = defaultSnapshot()) {
|
|
340
|
+
assertAbsolute(values);
|
|
341
|
+
assertSnapshotCeiling(values, snapshot);
|
|
342
|
+
const stored = Object.freeze({
|
|
343
|
+
...values,
|
|
344
|
+
maxLeverage: decimalText(values.maxLeverage, "maxLeverage"),
|
|
345
|
+
maxNotionalUsd: values.maxNotionalUsd === null ? null : decimalText(values.maxNotionalUsd, "maxNotionalUsd"),
|
|
346
|
+
dailyLossPct: decimalText(values.dailyLossPct, "dailyLossPct"),
|
|
347
|
+
maxOpenPositions: whole(values.maxOpenPositions, "maxOpenPositions"),
|
|
348
|
+
maxSlippageBps: decimalText(values.maxSlippageBps, "maxSlippageBps"),
|
|
349
|
+
orderRatePerSec: whole(values.orderRatePerSec, "orderRatePerSec"),
|
|
350
|
+
allowedCoins: Object.freeze(coins(values.allowedCoins)),
|
|
351
|
+
});
|
|
352
|
+
const guards = {
|
|
353
|
+
...stored,
|
|
354
|
+
get loosened() {
|
|
355
|
+
return isLoosened(stored);
|
|
356
|
+
},
|
|
357
|
+
get limitsHash() {
|
|
358
|
+
return hashLimits(stored, isLoosened(stored));
|
|
359
|
+
},
|
|
360
|
+
tighten(overrides = {}) {
|
|
361
|
+
return create(applyTighten(stored, overrides), snapshot);
|
|
362
|
+
},
|
|
363
|
+
check(intent, options = {}) {
|
|
364
|
+
return evaluate(stored, intent, options, snapshot);
|
|
365
|
+
},
|
|
366
|
+
receipt(market = snapshot) {
|
|
367
|
+
return receiptOf(stored, market);
|
|
368
|
+
},
|
|
369
|
+
effectiveLimits(market = snapshot) {
|
|
370
|
+
return effectiveOf(stored, market);
|
|
371
|
+
},
|
|
372
|
+
};
|
|
373
|
+
return Object.freeze(guards);
|
|
374
|
+
}
|
|
375
|
+
function isLoosened(limits) {
|
|
376
|
+
const base = exports.PRESETS[limits.preset];
|
|
377
|
+
if (compare(limits.maxLeverage, base.maxLeverage) > 0) {
|
|
378
|
+
return true;
|
|
379
|
+
}
|
|
380
|
+
if (limits.maxNotionalUsd === null || compare(limits.maxNotionalUsd, base.maxNotionalUsd) > 0) {
|
|
381
|
+
return true;
|
|
382
|
+
}
|
|
383
|
+
if (compare(limits.dailyLossPct, base.dailyLossPct) > 0) {
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
if (limits.maxOpenPositions > base.maxOpenPositions) {
|
|
387
|
+
return true;
|
|
388
|
+
}
|
|
389
|
+
if (compare(limits.maxSlippageBps, base.maxSlippageBps) > 0) {
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
return limits.orderRatePerSec > base.orderRatePerSec;
|
|
393
|
+
}
|
|
394
|
+
function hashLimits(limits, loosened) {
|
|
395
|
+
const payload = {
|
|
396
|
+
allowed_coins: [...limits.allowedCoins],
|
|
397
|
+
daily_loss_pct: limits.dailyLossPct,
|
|
398
|
+
loosened,
|
|
399
|
+
max_leverage: limits.maxLeverage,
|
|
400
|
+
max_notional_usd: limits.maxNotionalUsd,
|
|
401
|
+
max_open_positions: limits.maxOpenPositions,
|
|
402
|
+
max_slippage_bps: limits.maxSlippageBps,
|
|
403
|
+
order_rate_per_sec: limits.orderRatePerSec,
|
|
404
|
+
preset: limits.preset,
|
|
405
|
+
};
|
|
406
|
+
return (0, node_crypto_1.createHash)("sha256").update(canonical(payload)).digest("hex");
|
|
407
|
+
}
|
|
408
|
+
function receiptOf(limits, snapshot) {
|
|
409
|
+
return {
|
|
410
|
+
guardPreset: limits.preset,
|
|
411
|
+
limits: publicLimits(limits),
|
|
412
|
+
effectiveLimitsPerCoin: effectiveOf(limits, snapshot),
|
|
413
|
+
loosened: isLoosened(limits),
|
|
414
|
+
limitsHash: hashLimits(limits, isLoosened(limits)),
|
|
415
|
+
marketSnapshotId: snapshot.snapshotId,
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
function publicLimits(limits) {
|
|
419
|
+
return {
|
|
420
|
+
preset: limits.preset,
|
|
421
|
+
maxLeverage: limits.maxLeverage,
|
|
422
|
+
maxNotionalUsd: limits.maxNotionalUsd,
|
|
423
|
+
dailyLossPct: limits.dailyLossPct,
|
|
424
|
+
maxOpenPositions: limits.maxOpenPositions,
|
|
425
|
+
maxSlippageBps: limits.maxSlippageBps,
|
|
426
|
+
orderRatePerSec: limits.orderRatePerSec,
|
|
427
|
+
allowedCoins: [...limits.allowedCoins],
|
|
428
|
+
staleBlockMs: exports.STALE_BLOCK_MS,
|
|
429
|
+
staleHaltMs: exports.STALE_HALT_MS,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
function effectiveOf(limits, snapshot) {
|
|
433
|
+
const rendered = {};
|
|
434
|
+
for (const name of limits.allowedCoins) {
|
|
435
|
+
const meta = coinOf(snapshot, name);
|
|
436
|
+
rendered[name] = {
|
|
437
|
+
maxLeverage: plain(effectiveLeverage(limits, name, snapshot)),
|
|
438
|
+
hlMaxLeverage: meta === null ? null : String(meta.maxLeverage),
|
|
439
|
+
oiRank: oiRank(snapshot, name),
|
|
440
|
+
maxNotionalUsd: limits.maxNotionalUsd,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
return rendered;
|
|
444
|
+
}
|
|
445
|
+
function evaluate(limits, intent, options, fallback) {
|
|
446
|
+
if (typeof intent !== "object" || intent === null) {
|
|
447
|
+
throw new Error("intent must be an object");
|
|
448
|
+
}
|
|
449
|
+
const kind = kindOf(intent);
|
|
450
|
+
const coin = requiredString(intent.coin, "coin");
|
|
451
|
+
const notional = parseDecimal(decimalText(intent.notionalUsd, "notionalUsd"));
|
|
452
|
+
const leverage = parseDecimal(decimalText(intent.leverage, "leverage"));
|
|
453
|
+
const openPositions = whole(intent.openPositions, "openPositions");
|
|
454
|
+
const slippage = parseDecimal(decimalText(intent.slippageBps, "slippageBps"));
|
|
455
|
+
const ageMs = whole(intent.ageMs, "ageMs");
|
|
456
|
+
const side = intent.orderSide ?? "buy";
|
|
457
|
+
if (side !== "buy" && side !== "sell") {
|
|
458
|
+
throw new Error("orderSide must be buy or sell");
|
|
459
|
+
}
|
|
460
|
+
const snapshot = options.snapshot ?? fallback;
|
|
461
|
+
const depth = visibleDepth(options.book ?? null, side, parseDecimal(limits.maxSlippageBps));
|
|
462
|
+
const share = (depth * 20n) / 100n;
|
|
463
|
+
const allowed = effectiveLeverage(limits, coin, snapshot);
|
|
464
|
+
const found = [];
|
|
465
|
+
if (kind !== "close") {
|
|
466
|
+
if (!limits.allowedCoins.includes(coin) || coinOf(snapshot, coin) === null) {
|
|
467
|
+
found.push({ code: "coin_not_allowed", limit: limits.allowedCoins.join(","), actual: coin });
|
|
468
|
+
}
|
|
469
|
+
if (limits.maxNotionalUsd !== null && notional > parseDecimal(limits.maxNotionalUsd)) {
|
|
470
|
+
found.push({ code: "notional_exceeded", limit: limits.maxNotionalUsd, actual: plain(notional) });
|
|
471
|
+
}
|
|
472
|
+
if (kind === "open" && options.portfolioNotionalUsd !== undefined && limits.maxNotionalUsd !== null) {
|
|
473
|
+
const used = parseDecimal(decimalText(options.portfolioNotionalUsd, "portfolioNotionalUsd"));
|
|
474
|
+
const projectedNotional = used + notional;
|
|
475
|
+
const cap = parseDecimal(limits.maxNotionalUsd);
|
|
476
|
+
if (projectedNotional > cap) {
|
|
477
|
+
found.push({
|
|
478
|
+
code: "aggregate_notional",
|
|
479
|
+
limit: limits.maxNotionalUsd,
|
|
480
|
+
actual: plain(projectedNotional),
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
if (depth === 0n || notional > share) {
|
|
485
|
+
found.push({ code: "depth_cap", limit: plain(share), actual: plain(notional) });
|
|
486
|
+
}
|
|
487
|
+
if (coinOf(snapshot, coin) !== null && leverage > allowed) {
|
|
488
|
+
found.push({ code: "leverage_exceeded", limit: plain(allowed), actual: plain(leverage) });
|
|
489
|
+
}
|
|
490
|
+
if (kind === "open") {
|
|
491
|
+
let projected = openPositions;
|
|
492
|
+
if (options.portfolioPositions !== undefined) {
|
|
493
|
+
const held = parseDecimal(decimalText(options.portfolioCoinNotionalUsd ?? "0", "portfolioCoinNotionalUsd"));
|
|
494
|
+
const extra = notional > 0n && held === 0n ? 1 : 0;
|
|
495
|
+
projected = Math.max(openPositions, whole(options.portfolioPositions, "portfolioPositions") + extra);
|
|
496
|
+
}
|
|
497
|
+
if (projected > limits.maxOpenPositions) {
|
|
498
|
+
found.push({
|
|
499
|
+
code: "open_positions_exceeded",
|
|
500
|
+
limit: String(limits.maxOpenPositions),
|
|
501
|
+
actual: String(projected),
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
const loss = parseDecimal(decimalText(intent.dailyLossPct ?? "0", "dailyLossPct"));
|
|
506
|
+
if (kind === "open" && (options.reduceOnly === true || loss >= parseDecimal(limits.dailyLossPct))) {
|
|
507
|
+
found.push({ code: "daily_stop_reduce_only", limit: limits.dailyLossPct, actual: plain(loss) });
|
|
508
|
+
}
|
|
509
|
+
if (slippage > parseDecimal(limits.maxSlippageBps)) {
|
|
510
|
+
found.push({ code: "slippage_exceeded", limit: limits.maxSlippageBps, actual: plain(slippage) });
|
|
511
|
+
}
|
|
512
|
+
const recent = options.recentOrders ?? 0;
|
|
513
|
+
if (kind === "open" && recent >= limits.orderRatePerSec) {
|
|
514
|
+
found.push({ code: "order_rate", limit: String(limits.orderRatePerSec), actual: String(recent + 1) });
|
|
515
|
+
}
|
|
516
|
+
if (kind === "open" && ageMs > exports.STALE_HALT_MS) {
|
|
517
|
+
found.push({ code: "stale_halt", limit: String(exports.STALE_HALT_MS), actual: String(ageMs) });
|
|
518
|
+
}
|
|
519
|
+
else if (kind === "open" && ageMs > exports.STALE_BLOCK_MS) {
|
|
520
|
+
found.push({ code: "stale_data", limit: String(exports.STALE_BLOCK_MS), actual: String(ageMs) });
|
|
521
|
+
}
|
|
522
|
+
if (kind === "open" && options.killSwitch === true) {
|
|
523
|
+
found.push({ code: "kill_switch", limit: "latched", actual: "engaged" });
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
const ordered = [...found].sort((left, right) => exports.CODES.indexOf(left.code) - exports.CODES.indexOf(right.code));
|
|
527
|
+
const dollar = limits.maxNotionalUsd === null ? share : minBig(parseDecimal(limits.maxNotionalUsd), share);
|
|
528
|
+
const counted = options.portfolioPositions ?? openPositions;
|
|
529
|
+
const aggregateNotionalUsd = limits.maxNotionalUsd === null
|
|
530
|
+
? "none"
|
|
531
|
+
: plain(room(parseDecimal(limits.maxNotionalUsd), options.portfolioNotionalUsd === undefined
|
|
532
|
+
? 0n
|
|
533
|
+
: parseDecimal(decimalText(options.portfolioNotionalUsd, "portfolioNotionalUsd"))));
|
|
534
|
+
const headroom = Object.freeze({
|
|
535
|
+
notionalUsd: plain(room(dollar, notional)),
|
|
536
|
+
aggregateNotionalUsd,
|
|
537
|
+
depthCapUsd: plain(share),
|
|
538
|
+
leverage: plain(room(allowed, leverage)),
|
|
539
|
+
openPositions: String(Math.max(0, limits.maxOpenPositions - counted)),
|
|
540
|
+
dailyLossPct: plain(room(parseDecimal(limits.dailyLossPct), parseDecimal(decimalText(intent.dailyLossPct ?? "0", "dailyLossPct")))),
|
|
541
|
+
slippageBps: plain(room(parseDecimal(limits.maxSlippageBps), slippage)),
|
|
542
|
+
orderRatePerSec: String(Math.max(0, limits.orderRatePerSec - (options.recentOrders ?? 0))),
|
|
543
|
+
staleBlockMsRemaining: String(Math.max(0, exports.STALE_BLOCK_MS - ageMs)),
|
|
544
|
+
staleHaltMsRemaining: String(Math.max(0, exports.STALE_HALT_MS - ageMs)),
|
|
545
|
+
});
|
|
546
|
+
return Object.freeze({ ok: ordered.length === 0, violations: Object.freeze(ordered), headroom });
|
|
547
|
+
}
|
|
548
|
+
function visibleDepth(book, side, slippage) {
|
|
549
|
+
const levels = book === null ? [] : side === "buy" ? book.asks : book.bids;
|
|
550
|
+
if (levels.length === 0) {
|
|
551
|
+
return 0n;
|
|
552
|
+
}
|
|
553
|
+
const parsed = levels.map((level) => ({
|
|
554
|
+
price: parseDecimal(decimalText(level.px, "px")),
|
|
555
|
+
size: parseDecimal(decimalText(level.sz, "sz")),
|
|
556
|
+
}));
|
|
557
|
+
const best = side === "buy" ? parsed.reduce((min, level) => (level.price < min ? level.price : min), parsed[0]?.price ?? 0n) : parsed.reduce((max, level) => (level.price > max ? level.price : max), parsed[0]?.price ?? 0n);
|
|
558
|
+
const band = (best * slippage) / (10000n * SCALE_FACTOR);
|
|
559
|
+
const limit = side === "buy" ? best + band : best - band;
|
|
560
|
+
return parsed
|
|
561
|
+
.filter((level) => (side === "buy" ? level.price <= limit : level.price >= limit))
|
|
562
|
+
.reduce((total, level) => total + (level.price * level.size) / SCALE_FACTOR, 0n);
|
|
563
|
+
}
|
|
564
|
+
function effectiveLeverage(limits, coin, snapshot) {
|
|
565
|
+
const meta = coinOf(snapshot, coin);
|
|
566
|
+
if (meta === null) {
|
|
567
|
+
return 0n;
|
|
568
|
+
}
|
|
569
|
+
const cap = minBig(parseDecimal(limits.maxLeverage), parseDecimal(String(meta.maxLeverage)));
|
|
570
|
+
const rank = oiRank(snapshot, coin);
|
|
571
|
+
if (rank !== null && rank > exports.TOP_OI_COUNT) {
|
|
572
|
+
return cap / 2n;
|
|
573
|
+
}
|
|
574
|
+
return cap;
|
|
575
|
+
}
|
|
576
|
+
function applyTighten(current, overrides) {
|
|
577
|
+
if (typeof overrides !== "object" || overrides === null || Array.isArray(overrides)) {
|
|
578
|
+
throw new TypeError("overrides must be an object");
|
|
579
|
+
}
|
|
580
|
+
const unknown = Object.keys(overrides)
|
|
581
|
+
.filter((key) => !LIMIT_NAMES.includes(key))
|
|
582
|
+
.sort();
|
|
583
|
+
if (unknown.length > 0) {
|
|
584
|
+
throw new TypeError(`unknown limit: ${unknown.join(", ")}`);
|
|
585
|
+
}
|
|
586
|
+
return {
|
|
587
|
+
preset: current.preset,
|
|
588
|
+
maxLeverage: tighterDecimal("maxLeverage", current.maxLeverage, overrides.maxLeverage),
|
|
589
|
+
maxNotionalUsd: tighterNotional(current.maxNotionalUsd, overrides.maxNotionalUsd),
|
|
590
|
+
dailyLossPct: tighterDecimal("dailyLossPct", current.dailyLossPct, overrides.dailyLossPct),
|
|
591
|
+
maxOpenPositions: tighterInt("maxOpenPositions", current.maxOpenPositions, overrides.maxOpenPositions),
|
|
592
|
+
maxSlippageBps: tighterDecimal("maxSlippageBps", current.maxSlippageBps, overrides.maxSlippageBps),
|
|
593
|
+
orderRatePerSec: tighterInt("orderRatePerSec", current.orderRatePerSec, overrides.orderRatePerSec),
|
|
594
|
+
allowedCoins: tighterCoins(current.allowedCoins, overrides.allowedCoins),
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
function applyOverride(name, current, raw, acknowledge, snapshot) {
|
|
598
|
+
if (name === "allowedCoins") {
|
|
599
|
+
const parsed = coins(raw);
|
|
600
|
+
if (parsed.some((coin) => !namesOf(snapshot).includes(coin))) {
|
|
601
|
+
throw new GuardConfigError("allowedCoins is past the listed perps");
|
|
602
|
+
}
|
|
603
|
+
const currentCoins = coins(current);
|
|
604
|
+
if (parsed.some((coin) => !currentCoins.includes(coin)) && !acknowledge) {
|
|
605
|
+
throw new GuardLoosenError("allowedCoins cannot be loosened");
|
|
606
|
+
}
|
|
607
|
+
return parsed;
|
|
608
|
+
}
|
|
609
|
+
if (name === "maxNotionalUsd") {
|
|
610
|
+
return overrideNotional(current, raw, acknowledge);
|
|
611
|
+
}
|
|
612
|
+
if (name === "maxOpenPositions" || name === "orderRatePerSec") {
|
|
613
|
+
const parsed = whole(raw, name);
|
|
614
|
+
const baseline = whole(current, name);
|
|
615
|
+
if (parsed > baseline && !acknowledge) {
|
|
616
|
+
throw new GuardLoosenError(`${name} cannot be loosened`);
|
|
617
|
+
}
|
|
618
|
+
if (name === "maxOpenPositions" && parsed > exports.HARD_MAX_OPEN_POSITIONS) {
|
|
619
|
+
throw new GuardConfigError("maxOpenPositions is past the hard ceiling");
|
|
620
|
+
}
|
|
621
|
+
if (name === "orderRatePerSec" && parsed > exports.HARD_MAX_ORDER_RATE) {
|
|
622
|
+
throw new GuardConfigError("orderRatePerSec is past the hard ceiling");
|
|
623
|
+
}
|
|
624
|
+
return parsed;
|
|
625
|
+
}
|
|
626
|
+
const parsed = decimalText(raw, name);
|
|
627
|
+
const baseline = decimalText(current, name);
|
|
628
|
+
if (compare(parsed, baseline) > 0 && !acknowledge) {
|
|
629
|
+
throw new GuardLoosenError(`${name} cannot be loosened`);
|
|
630
|
+
}
|
|
631
|
+
if (name === "maxLeverage" && compare(parsed, highestLeverage(snapshot)) > 0) {
|
|
632
|
+
throw new GuardConfigError("maxLeverage is past the hard ceiling");
|
|
633
|
+
}
|
|
634
|
+
if (name === "dailyLossPct" && compare(parsed, exports.HARD_MAX_DAILY_LOSS_PCT) > 0) {
|
|
635
|
+
throw new GuardConfigError("dailyLossPct is past the hard ceiling");
|
|
636
|
+
}
|
|
637
|
+
if (name === "maxSlippageBps" && compare(parsed, exports.HARD_MAX_SLIPPAGE_BPS) > 0) {
|
|
638
|
+
throw new GuardConfigError("maxSlippageBps is past the hard ceiling");
|
|
639
|
+
}
|
|
640
|
+
return parsed;
|
|
641
|
+
}
|
|
642
|
+
function overrideNotional(current, raw, acknowledge) {
|
|
643
|
+
if (raw === null) {
|
|
644
|
+
if (current !== null && !acknowledge) {
|
|
645
|
+
throw new GuardLoosenError("maxNotionalUsd cannot be loosened");
|
|
646
|
+
}
|
|
647
|
+
return null;
|
|
648
|
+
}
|
|
649
|
+
const parsed = decimalText(raw, "maxNotionalUsd");
|
|
650
|
+
if (current === null) {
|
|
651
|
+
return parsed;
|
|
652
|
+
}
|
|
653
|
+
if (compare(parsed, decimalText(current, "maxNotionalUsd")) > 0 && !acknowledge) {
|
|
654
|
+
throw new GuardLoosenError("maxNotionalUsd cannot be loosened");
|
|
655
|
+
}
|
|
656
|
+
return parsed;
|
|
657
|
+
}
|
|
658
|
+
function tighterDecimal(name, current, value) {
|
|
659
|
+
if (value === undefined) {
|
|
660
|
+
return current;
|
|
661
|
+
}
|
|
662
|
+
const parsed = decimalText(value, name);
|
|
663
|
+
if (compare(parsed, current) > 0) {
|
|
664
|
+
throw new GuardLoosenError(`${name} cannot be loosened`);
|
|
665
|
+
}
|
|
666
|
+
return parsed;
|
|
667
|
+
}
|
|
668
|
+
function tighterNotional(current, value) {
|
|
669
|
+
if (value === undefined) {
|
|
670
|
+
return current;
|
|
671
|
+
}
|
|
672
|
+
if (value === null) {
|
|
673
|
+
if (current !== null) {
|
|
674
|
+
throw new GuardLoosenError("maxNotionalUsd cannot be loosened");
|
|
675
|
+
}
|
|
676
|
+
return null;
|
|
677
|
+
}
|
|
678
|
+
const parsed = decimalText(value, "maxNotionalUsd");
|
|
679
|
+
if (current === null || compare(parsed, current) <= 0) {
|
|
680
|
+
return parsed;
|
|
681
|
+
}
|
|
682
|
+
throw new GuardLoosenError("maxNotionalUsd cannot be loosened");
|
|
683
|
+
}
|
|
684
|
+
function tighterInt(name, current, value) {
|
|
685
|
+
if (value === undefined) {
|
|
686
|
+
return current;
|
|
687
|
+
}
|
|
688
|
+
const parsed = whole(value, name);
|
|
689
|
+
if (parsed > current) {
|
|
690
|
+
throw new GuardLoosenError(`${name} cannot be loosened`);
|
|
691
|
+
}
|
|
692
|
+
return parsed;
|
|
693
|
+
}
|
|
694
|
+
function tighterCoins(current, value) {
|
|
695
|
+
if (value === undefined) {
|
|
696
|
+
return current;
|
|
697
|
+
}
|
|
698
|
+
const parsed = coins(value);
|
|
699
|
+
if (parsed.some((coin) => !current.includes(coin))) {
|
|
700
|
+
throw new GuardLoosenError("allowedCoins cannot be loosened");
|
|
701
|
+
}
|
|
702
|
+
return parsed;
|
|
703
|
+
}
|
|
704
|
+
function assertAbsolute(values) {
|
|
705
|
+
if (!isPreset(values.preset)) {
|
|
706
|
+
throw new GuardConfigError("unknown preset");
|
|
707
|
+
}
|
|
708
|
+
if (compare(decimalText(values.dailyLossPct, "dailyLossPct"), exports.HARD_MAX_DAILY_LOSS_PCT) > 0) {
|
|
709
|
+
throw new GuardConfigError("dailyLossPct is past the hard ceiling");
|
|
710
|
+
}
|
|
711
|
+
if (whole(values.maxOpenPositions, "maxOpenPositions") > exports.HARD_MAX_OPEN_POSITIONS) {
|
|
712
|
+
throw new GuardConfigError("maxOpenPositions is past the hard ceiling");
|
|
713
|
+
}
|
|
714
|
+
if (compare(decimalText(values.maxSlippageBps, "maxSlippageBps"), exports.HARD_MAX_SLIPPAGE_BPS) > 0) {
|
|
715
|
+
throw new GuardConfigError("maxSlippageBps is past the hard ceiling");
|
|
716
|
+
}
|
|
717
|
+
if (whole(values.orderRatePerSec, "orderRatePerSec") > exports.HARD_MAX_ORDER_RATE) {
|
|
718
|
+
throw new GuardConfigError("orderRatePerSec is past the hard ceiling");
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
function assertSnapshotCeiling(values, snapshot) {
|
|
722
|
+
if (compare(decimalText(values.maxLeverage, "maxLeverage"), highestLeverage(snapshot)) > 0) {
|
|
723
|
+
throw new GuardConfigError("maxLeverage is past the hard ceiling");
|
|
724
|
+
}
|
|
725
|
+
if (coins(values.allowedCoins).some((coin) => !namesOf(snapshot).includes(coin))) {
|
|
726
|
+
throw new GuardConfigError("allowedCoins is past the listed perps");
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
function kindOf(intent) {
|
|
730
|
+
if (intent.intentKind === "open" || intent.intentKind === "reduce" || intent.intentKind === "close") {
|
|
731
|
+
return intent.intentKind;
|
|
732
|
+
}
|
|
733
|
+
return intent.opening === false ? "close" : "open";
|
|
734
|
+
}
|
|
735
|
+
function namesOf(snapshot) {
|
|
736
|
+
return [...snapshot.coins.map((coin) => coin.name)].sort();
|
|
737
|
+
}
|
|
738
|
+
function coinOf(snapshot, name) {
|
|
739
|
+
return snapshot.coins.find((coin) => coin.name === name) ?? null;
|
|
740
|
+
}
|
|
741
|
+
function oiRank(snapshot, name) {
|
|
742
|
+
const ordered = [...snapshot.coins].sort((left, right) => {
|
|
743
|
+
const interest = compare(right.openInterest, left.openInterest);
|
|
744
|
+
if (interest !== 0) {
|
|
745
|
+
return interest;
|
|
746
|
+
}
|
|
747
|
+
return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;
|
|
748
|
+
});
|
|
749
|
+
const index = ordered.findIndex((coin) => coin.name === name);
|
|
750
|
+
return index < 0 ? null : index + 1;
|
|
751
|
+
}
|
|
752
|
+
function highestLeverage(snapshot) {
|
|
753
|
+
return snapshot.coins.reduce((max, coin) => {
|
|
754
|
+
const text = String(coin.maxLeverage);
|
|
755
|
+
return compare(text, max) > 0 ? text : max;
|
|
756
|
+
}, "0");
|
|
757
|
+
}
|
|
758
|
+
function isPreset(value) {
|
|
759
|
+
return value === "conservative" || value === "standard" || value === "pro";
|
|
760
|
+
}
|
|
761
|
+
function room(limit, actual) {
|
|
762
|
+
return actual >= limit ? 0n : limit - actual;
|
|
763
|
+
}
|
|
764
|
+
function minBig(left, right) {
|
|
765
|
+
return left < right ? left : right;
|
|
766
|
+
}
|
|
767
|
+
function canonical(value) {
|
|
768
|
+
return JSON.stringify(sortValue(value));
|
|
769
|
+
}
|
|
770
|
+
function sortValue(value) {
|
|
771
|
+
if (Array.isArray(value)) {
|
|
772
|
+
return value.map((item) => sortValue(item));
|
|
773
|
+
}
|
|
774
|
+
if (typeof value === "object" && value !== null) {
|
|
775
|
+
const entries = Object.entries(value).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
|
|
776
|
+
return Object.fromEntries(entries.map(([key, item]) => [key, sortValue(item)]));
|
|
777
|
+
}
|
|
778
|
+
return value;
|
|
779
|
+
}
|
|
780
|
+
function requiredString(value, label) {
|
|
781
|
+
if (typeof value !== "string") {
|
|
782
|
+
throw new Error(`${label} must be a string`);
|
|
783
|
+
}
|
|
784
|
+
return value;
|
|
785
|
+
}
|
|
786
|
+
function decimalText(value, label) {
|
|
787
|
+
if (typeof value === "number") {
|
|
788
|
+
if (!Number.isInteger(value)) {
|
|
789
|
+
throw new Error(`${label} must be a decimal`);
|
|
790
|
+
}
|
|
791
|
+
return decimalText(String(value), label);
|
|
792
|
+
}
|
|
793
|
+
if (typeof value === "bigint") {
|
|
794
|
+
return plain(value);
|
|
795
|
+
}
|
|
796
|
+
if (typeof value !== "string" || !/^\d+(\.\d+)?$/.test(value)) {
|
|
797
|
+
throw new Error(`${label} must be a decimal`);
|
|
798
|
+
}
|
|
799
|
+
return plain(parseDecimal(value));
|
|
800
|
+
}
|
|
801
|
+
function whole(value, label) {
|
|
802
|
+
if (typeof value === "string" && /^\d+$/.test(value)) {
|
|
803
|
+
return whole(Number(value), label);
|
|
804
|
+
}
|
|
805
|
+
if (typeof value !== "number" || !Number.isInteger(value)) {
|
|
806
|
+
throw new Error(`${label} must be an integer`);
|
|
807
|
+
}
|
|
808
|
+
if (value < 0) {
|
|
809
|
+
throw new Error(`${label} must be >= 0`);
|
|
810
|
+
}
|
|
811
|
+
return value;
|
|
812
|
+
}
|
|
813
|
+
function coins(value) {
|
|
814
|
+
if (!Array.isArray(value)) {
|
|
815
|
+
throw new Error("allowedCoins must be a list of coins");
|
|
816
|
+
}
|
|
817
|
+
const found = [];
|
|
818
|
+
for (const item of value) {
|
|
819
|
+
if (typeof item !== "string" || item === "") {
|
|
820
|
+
throw new Error("allowedCoins must be a list of coins");
|
|
821
|
+
}
|
|
822
|
+
if (!found.includes(item)) {
|
|
823
|
+
found.push(item);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
found.sort();
|
|
827
|
+
return Object.freeze(found);
|
|
828
|
+
}
|
|
829
|
+
function compare(left, right) {
|
|
830
|
+
const a = parseDecimal(left);
|
|
831
|
+
const b = parseDecimal(right);
|
|
832
|
+
if (a > b) {
|
|
833
|
+
return 1;
|
|
834
|
+
}
|
|
835
|
+
if (a < b) {
|
|
836
|
+
return -1;
|
|
837
|
+
}
|
|
838
|
+
return 0;
|
|
839
|
+
}
|
|
840
|
+
function parseDecimal(text) {
|
|
841
|
+
const [wholePart, frac = ""] = text.split(".");
|
|
842
|
+
if (frac.length > SCALE) {
|
|
843
|
+
throw new Error("decimal scale exceeded");
|
|
844
|
+
}
|
|
845
|
+
const padded = frac + "0".repeat(SCALE - frac.length);
|
|
846
|
+
return BigInt(wholePart ?? "0") * SCALE_FACTOR + BigInt(padded);
|
|
847
|
+
}
|
|
848
|
+
function plain(value) {
|
|
849
|
+
const negative = value < 0n;
|
|
850
|
+
const absolute = negative ? -value : value;
|
|
851
|
+
const wholePart = absolute / SCALE_FACTOR;
|
|
852
|
+
const frac = (absolute % SCALE_FACTOR).toString().padStart(SCALE, "0").replace(/0+$/, "");
|
|
853
|
+
const text = frac.length === 0 ? wholePart.toString() : `${wholePart.toString()}.${frac}`;
|
|
854
|
+
return negative ? `-${text}` : text;
|
|
855
|
+
}
|