@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,839 @@
|
|
|
1
|
+
/** Re-derive a simulation receipt. The check is verified and reproducible. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { GuardBlocked, GuardSession, defaultSnapshot, snapshotFromCoins, } from "./guards.js";
|
|
6
|
+
import { guardedSimulate } from "./guarded.js";
|
|
7
|
+
import { CURRENT_SIM_DEFAULTS, receiptProfile, simDefaults } from "./vendor/simDefaults.js";
|
|
8
|
+
import { studyAccounting } from "./study.js";
|
|
9
|
+
import { HL_FUNDING_INTERVAL_MS, simulate, } from "./vendor/simulate.js";
|
|
10
|
+
export const RECEIPT_STATEMENT = "verified and reproducible";
|
|
11
|
+
export const RECEIPT_KIND = "perpbrain.sim-receipt";
|
|
12
|
+
export const RECEIPT_VERSION = 5;
|
|
13
|
+
export function verifyReceipt(receipt, manifest, inputs) {
|
|
14
|
+
const mismatches = [];
|
|
15
|
+
const body = asObject(receipt);
|
|
16
|
+
if (body === null) {
|
|
17
|
+
return report(["receipt mismatch"]);
|
|
18
|
+
}
|
|
19
|
+
const version = checkIdentity(body, mismatches);
|
|
20
|
+
const limits = body.limits;
|
|
21
|
+
const limitsHash = digestField(body, "limits_hash", mismatches);
|
|
22
|
+
if (isObject(limits)) {
|
|
23
|
+
if (limitsHash !== null && sha256Json(limits) !== limitsHash) {
|
|
24
|
+
mismatches.push("limits_hash mismatch");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
mismatches.push("limits mismatch");
|
|
29
|
+
}
|
|
30
|
+
const snapshot = body.market_snapshot;
|
|
31
|
+
const snapshotId = digestField(body, "market_snapshot_id", mismatches);
|
|
32
|
+
if (Array.isArray(snapshot)) {
|
|
33
|
+
if (snapshotId !== null && sha256Json(snapshot) !== snapshotId) {
|
|
34
|
+
mismatches.push("market_snapshot_id mismatch");
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
mismatches.push("market_snapshot mismatch");
|
|
39
|
+
}
|
|
40
|
+
const claimedData = digestField(body, "data_snapshot_id", mismatches);
|
|
41
|
+
const parsedInputs = parseInputs(inputs, claimedData, body.inputs, mismatches);
|
|
42
|
+
const claimedManifest = digestField(body, "manifest_sha256", mismatches);
|
|
43
|
+
const manifestBody = parseManifest(manifest, claimedManifest, mismatches);
|
|
44
|
+
if (manifestBody !== null) {
|
|
45
|
+
checkManifest(manifestBody, body, mismatches);
|
|
46
|
+
}
|
|
47
|
+
const claimedResult = digestField(body, "result_sha256", mismatches);
|
|
48
|
+
if (claimedResult !== null && sha256Json(body.result) !== claimedResult) {
|
|
49
|
+
mismatches.push("result_sha256 mismatch");
|
|
50
|
+
}
|
|
51
|
+
if (parsedInputs !== null) {
|
|
52
|
+
checkSim(parsedInputs, body.result, mismatches, version);
|
|
53
|
+
checkStudy(body, parsedInputs, mismatches, receiptProfile(body.version, body.result));
|
|
54
|
+
checkGuard(body, parsedInputs, mismatches);
|
|
55
|
+
}
|
|
56
|
+
return report(mismatches);
|
|
57
|
+
}
|
|
58
|
+
export function canonical(value) {
|
|
59
|
+
return JSON.stringify(sortValue(value));
|
|
60
|
+
}
|
|
61
|
+
export function sha256Json(value) {
|
|
62
|
+
return createHash("sha256").update(canonical(value)).digest("hex");
|
|
63
|
+
}
|
|
64
|
+
export function costBreakdownFromReceipt(receipt) {
|
|
65
|
+
const body = asObject(receipt);
|
|
66
|
+
if (body === null) {
|
|
67
|
+
throw new Error("receipt mismatch");
|
|
68
|
+
}
|
|
69
|
+
const inputs = asObject(body.inputs);
|
|
70
|
+
if (inputs === null) {
|
|
71
|
+
throw new Error("inputs must be an object");
|
|
72
|
+
}
|
|
73
|
+
return runSim(inputs, receiptProfile(body.version, body.result)).cost_breakdown;
|
|
74
|
+
}
|
|
75
|
+
/** UTF-8 JSON with sorted keys and no extra space, plus a trailing newline. */
|
|
76
|
+
function canonicalFileBytes(value) {
|
|
77
|
+
return Buffer.from(`${canonical(value)}\n`, "utf8");
|
|
78
|
+
}
|
|
79
|
+
/** Indented JSON with a trailing newline, for the receipt and manifest files. */
|
|
80
|
+
function prettyBytes(value) {
|
|
81
|
+
return Buffer.from(`${JSON.stringify(sortValue(value), null, 2)}\n`, "utf8");
|
|
82
|
+
}
|
|
83
|
+
export function exampleInputs() {
|
|
84
|
+
const bar = { open: "100", high: "100", low: "100", close: "100" };
|
|
85
|
+
return {
|
|
86
|
+
market: "ETH",
|
|
87
|
+
decision: { bar_index: 0, side: "long", size: "0.01", stop: null, target: null },
|
|
88
|
+
bars: [bar, bar],
|
|
89
|
+
book: { bids: [{ px: "100", sz: "5" }], asks: [{ px: "100", sz: "5" }] },
|
|
90
|
+
fee_version: null,
|
|
91
|
+
funding: [],
|
|
92
|
+
funding_interval_ms: HL_FUNDING_INTERVAL_MS,
|
|
93
|
+
guard_context: { leverage: "1", open_positions: 1, daily_loss_usd: "0", age_ms: 0 },
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
export function limitsPayload(limits) {
|
|
97
|
+
return {
|
|
98
|
+
allowed_coins: [...limits.allowedCoins],
|
|
99
|
+
daily_loss_pct: limits.dailyLossPct,
|
|
100
|
+
loosened: limits.loosened,
|
|
101
|
+
max_leverage: limits.maxLeverage,
|
|
102
|
+
max_notional_usd: limits.maxNotionalUsd,
|
|
103
|
+
max_open_positions: limits.maxOpenPositions,
|
|
104
|
+
max_slippage_bps: limits.maxSlippageBps,
|
|
105
|
+
order_rate_per_sec: limits.orderRatePerSec,
|
|
106
|
+
preset: limits.preset,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
export function snapshotRows(snapshot) {
|
|
110
|
+
return snapshot.coins.map((coin) => ({
|
|
111
|
+
max_leverage: coin.maxLeverage,
|
|
112
|
+
name: coin.name,
|
|
113
|
+
open_interest: coin.openInterest,
|
|
114
|
+
}));
|
|
115
|
+
}
|
|
116
|
+
export function simulateInputs(inputs) {
|
|
117
|
+
// Receipts store the snake_case wire form; do not hash the camelCase runtime object.
|
|
118
|
+
return wireResult(runSim(inputs));
|
|
119
|
+
}
|
|
120
|
+
export function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
|
|
121
|
+
const inputsBytes = canonicalFileBytes(inputs);
|
|
122
|
+
const dataSnapshotId = sha256Bytes(inputsBytes);
|
|
123
|
+
const limitsHash = sha256Json(limits);
|
|
124
|
+
const marketSnapshotId = sha256Json(marketSnapshot);
|
|
125
|
+
const resultSha256 = sha256Json(result);
|
|
126
|
+
const manifest = {
|
|
127
|
+
data_snapshot_id: dataSnapshotId,
|
|
128
|
+
files: [{ file: "inputs.json", rows: 1, sha256: dataSnapshotId }],
|
|
129
|
+
limits_hash: limitsHash,
|
|
130
|
+
market_snapshot_id: marketSnapshotId,
|
|
131
|
+
result_sha256: resultSha256,
|
|
132
|
+
};
|
|
133
|
+
const manifestBytes = prettyBytes(manifest);
|
|
134
|
+
const receipt = {
|
|
135
|
+
data_snapshot_id: dataSnapshotId,
|
|
136
|
+
inputs,
|
|
137
|
+
kind: RECEIPT_KIND,
|
|
138
|
+
label: "SIMULATED",
|
|
139
|
+
limits,
|
|
140
|
+
limits_hash: limitsHash,
|
|
141
|
+
manifest_sha256: sha256Bytes(manifestBytes),
|
|
142
|
+
market_snapshot: marketSnapshot,
|
|
143
|
+
market_snapshot_id: marketSnapshotId,
|
|
144
|
+
raw_ref: "inputs.json",
|
|
145
|
+
result,
|
|
146
|
+
result_sha256: resultSha256,
|
|
147
|
+
statement: RECEIPT_STATEMENT,
|
|
148
|
+
version: RECEIPT_VERSION,
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
receipt,
|
|
152
|
+
manifest,
|
|
153
|
+
receiptBytes: prettyBytes(receipt),
|
|
154
|
+
manifestBytes,
|
|
155
|
+
inputsBytes,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
export function writeReceiptDir(directory, built) {
|
|
159
|
+
mkdirSync(directory, { recursive: true });
|
|
160
|
+
writeFileSync(join(directory, "inputs.json"), built.inputsBytes);
|
|
161
|
+
writeFileSync(join(directory, "manifest.json"), built.manifestBytes);
|
|
162
|
+
const receiptPath = join(directory, "receipt.json");
|
|
163
|
+
writeFileSync(receiptPath, built.receiptBytes);
|
|
164
|
+
return receiptPath;
|
|
165
|
+
}
|
|
166
|
+
function acceptInputs(inputs, session) {
|
|
167
|
+
guardedSimulate(requiredString(inputs.market, "market"), decisionOf(inputs.decision), barsOf(inputs.bars), bookOf(inputs.book), feeOf(inputs.fee_version), contextOf(inputs.guard_context), session.limits.preset, session, fundingOf(inputs.funding), intervalOf(inputs.funding_interval_ms));
|
|
168
|
+
}
|
|
169
|
+
export function buildReceiptDir(directory, inputs = exampleInputs(), limits = null, snapshot = null) {
|
|
170
|
+
const session = limits === null ? GuardSession.fromConfig() : new GuardSession(limits);
|
|
171
|
+
const market = snapshot ?? defaultSnapshot();
|
|
172
|
+
const hashed = simulateInputs(inputs);
|
|
173
|
+
acceptInputs(inputs, session);
|
|
174
|
+
return writeReceiptDir(directory, buildReceiptFiles(inputs, hashed, limitsPayload(session.limits), snapshotRows(market)));
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Write a verifiable receipt from a successful `guardedSimulate` result.
|
|
178
|
+
*
|
|
179
|
+
* Verification reruns the unguarded simulator on the raw inputs, so the
|
|
180
|
+
* hashed result is `simulateInputs`, not the guarded result object. Guard
|
|
181
|
+
* metadata attached to that object (`guardPreset`, `limits`, `limitsHash`,
|
|
182
|
+
* `effectiveLimitsPerCoin`, `loosened`, `marketSnapshotId`, `guardViolations`)
|
|
183
|
+
* must not be hashed. The market snapshot defaults to `defaultSnapshot`; an
|
|
184
|
+
* empty snapshot list would refuse coins as `coin_not_allowed`.
|
|
185
|
+
*
|
|
186
|
+
* Receipt inputs use snake_case (`bar_index`, `time_ms`), even though the
|
|
187
|
+
* TypeScript `Decision` / `Bar` types are camelCase.
|
|
188
|
+
*/
|
|
189
|
+
export function buildGuardedReceipt(directory, inputs, result, session, snapshot = null) {
|
|
190
|
+
const body = result;
|
|
191
|
+
if (body.label !== "SIMULATED") {
|
|
192
|
+
throw new Error("result must be a SIMULATED guardedSimulate outcome");
|
|
193
|
+
}
|
|
194
|
+
const violations = body.guardViolations ?? body.guard_violations;
|
|
195
|
+
if (Array.isArray(violations) && violations.length > 0) {
|
|
196
|
+
throw new Error("blocked simulate results cannot be written as a verified receipt");
|
|
197
|
+
}
|
|
198
|
+
const market = snapshot ?? defaultSnapshot();
|
|
199
|
+
const hashed = simulateInputs(inputs);
|
|
200
|
+
acceptInputs(inputs, session);
|
|
201
|
+
return writeReceiptDir(directory, buildReceiptFiles(inputs, hashed, limitsPayload(session.limits), snapshotRows(market)));
|
|
202
|
+
}
|
|
203
|
+
function insideDirectory(root, ref) {
|
|
204
|
+
if (ref === "" || ref.includes("\0")) {
|
|
205
|
+
throw new Error("raw_ref must stay inside the receipt directory");
|
|
206
|
+
}
|
|
207
|
+
const candidate = ref;
|
|
208
|
+
if (candidate.startsWith("/") || candidate.split(/[\\/]/).includes("..")) {
|
|
209
|
+
throw new Error("raw_ref must stay inside the receipt directory");
|
|
210
|
+
}
|
|
211
|
+
return join(root, candidate);
|
|
212
|
+
}
|
|
213
|
+
/** Read a receipt.json file, or a directory that contains one, and check it. */
|
|
214
|
+
export function verifyReceiptAt(path) {
|
|
215
|
+
const receiptFile = existsSync(path) && statSync(path).isDirectory() ? join(path, "receipt.json") : path;
|
|
216
|
+
if (!existsSync(receiptFile) || !statSync(receiptFile).isFile()) {
|
|
217
|
+
return report(["receipt.json missing"]);
|
|
218
|
+
}
|
|
219
|
+
let loaded;
|
|
220
|
+
try {
|
|
221
|
+
loaded = JSON.parse(readFileSync(receiptFile, "utf8"));
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
return report(["receipt json mismatch"]);
|
|
225
|
+
}
|
|
226
|
+
const receipt = asObject(loaded);
|
|
227
|
+
if (receipt === null) {
|
|
228
|
+
return report(["receipt mismatch"]);
|
|
229
|
+
}
|
|
230
|
+
const root = dirname(receiptFile);
|
|
231
|
+
const missing = [];
|
|
232
|
+
const manifestPath = join(root, "manifest.json");
|
|
233
|
+
const manifest = existsSync(manifestPath) && statSync(manifestPath).isFile() ? readFileSync(manifestPath) : null;
|
|
234
|
+
if (manifest === null) {
|
|
235
|
+
missing.push("manifest missing");
|
|
236
|
+
}
|
|
237
|
+
let inputs = Buffer.alloc(0);
|
|
238
|
+
const rawRef = receipt.raw_ref;
|
|
239
|
+
if (typeof rawRef !== "string") {
|
|
240
|
+
missing.push("raw_ref mismatch");
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
try {
|
|
244
|
+
const rawPath = insideDirectory(root, rawRef);
|
|
245
|
+
if (existsSync(rawPath) && statSync(rawPath).isFile()) {
|
|
246
|
+
inputs = readFileSync(rawPath);
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
missing.push(`${rawRef} missing`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
missing.push("raw_ref mismatch");
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const checked = verifyReceipt(receipt, manifest ?? Buffer.alloc(0), inputs);
|
|
257
|
+
return report([...missing, ...checked.mismatches]);
|
|
258
|
+
}
|
|
259
|
+
function checkIdentity(receipt, mismatches) {
|
|
260
|
+
const version = receipt.version;
|
|
261
|
+
if (typeof version !== "number" || !Number.isInteger(version) || (version !== 1 && version !== 2 && version !== 3 && version !== 4 && version !== 5)) {
|
|
262
|
+
mismatches.push("version mismatch");
|
|
263
|
+
}
|
|
264
|
+
if (receipt.kind !== RECEIPT_KIND) {
|
|
265
|
+
mismatches.push("kind mismatch");
|
|
266
|
+
}
|
|
267
|
+
if (receipt.label !== "SIMULATED") {
|
|
268
|
+
mismatches.push("label mismatch");
|
|
269
|
+
}
|
|
270
|
+
if (receipt.statement !== RECEIPT_STATEMENT) {
|
|
271
|
+
mismatches.push("statement mismatch");
|
|
272
|
+
}
|
|
273
|
+
return version === 1 || version === 2 || version === 3 || version === 4 || version === 5 ? version : null;
|
|
274
|
+
}
|
|
275
|
+
function digestField(receipt, key, mismatches) {
|
|
276
|
+
const value = receipt[key];
|
|
277
|
+
if (typeof value !== "string" || value === "") {
|
|
278
|
+
mismatches.push(`${key} mismatch`);
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
return value;
|
|
282
|
+
}
|
|
283
|
+
function parseInputs(inputs, claimed, embedded, mismatches) {
|
|
284
|
+
if (claimed !== null && sha256Bytes(inputs) !== claimed) {
|
|
285
|
+
mismatches.push("data_snapshot_id mismatch");
|
|
286
|
+
}
|
|
287
|
+
if (inputs.byteLength === 0) {
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
let loaded;
|
|
291
|
+
try {
|
|
292
|
+
loaded = JSON.parse(new TextDecoder().decode(inputs));
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
mismatches.push("inputs json mismatch");
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
if (!isObject(loaded)) {
|
|
299
|
+
mismatches.push("inputs mismatch");
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
if (!sameJson(embedded, loaded)) {
|
|
303
|
+
mismatches.push("inputs mismatch");
|
|
304
|
+
}
|
|
305
|
+
return loaded;
|
|
306
|
+
}
|
|
307
|
+
function parseManifest(manifest, claimed, mismatches) {
|
|
308
|
+
if (manifest.byteLength === 0) {
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
if (claimed !== null && sha256Bytes(manifest) !== claimed) {
|
|
312
|
+
mismatches.push("manifest_sha256 mismatch");
|
|
313
|
+
}
|
|
314
|
+
let loaded;
|
|
315
|
+
try {
|
|
316
|
+
loaded = JSON.parse(new TextDecoder().decode(manifest));
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
mismatches.push("manifest json mismatch");
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
if (!isObject(loaded)) {
|
|
323
|
+
mismatches.push("manifest mismatch");
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
return loaded;
|
|
327
|
+
}
|
|
328
|
+
function checkManifest(manifest, receipt, mismatches) {
|
|
329
|
+
for (const key of ["data_snapshot_id", "limits_hash", "market_snapshot_id", "result_sha256"]) {
|
|
330
|
+
if (manifest[key] !== receipt[key]) {
|
|
331
|
+
mismatches.push(`manifest ${key} mismatch`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const files = manifest.files;
|
|
335
|
+
const rawRef = receipt.raw_ref;
|
|
336
|
+
if (!Array.isArray(files)) {
|
|
337
|
+
mismatches.push("manifest files mismatch");
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
let found = false;
|
|
341
|
+
for (const item of files) {
|
|
342
|
+
if (!isObject(item)) {
|
|
343
|
+
mismatches.push("manifest files mismatch");
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (item.file !== rawRef) {
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
found = true;
|
|
350
|
+
if (item.sha256 !== receipt.data_snapshot_id) {
|
|
351
|
+
mismatches.push(`manifest file ${String(rawRef)} sha256 mismatch`);
|
|
352
|
+
}
|
|
353
|
+
if (item.rows !== 1) {
|
|
354
|
+
mismatches.push(`manifest file ${String(rawRef)} rows mismatch`);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
if (!found) {
|
|
358
|
+
mismatches.push("manifest files mismatch");
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
function checkStudy(receipt, inputs, mismatches, profile) {
|
|
362
|
+
let expected;
|
|
363
|
+
try {
|
|
364
|
+
expected = studyFromInputs(inputs, simDefaults(profile).numerics === "fixed18" ? "fixed18" : "float");
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
mismatches.push(`study mismatch: ${messageOf(error)}`);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
const claimed = receipt.study_accounting;
|
|
371
|
+
if (expected === null) {
|
|
372
|
+
if (claimed !== undefined) {
|
|
373
|
+
mismatches.push("study_accounting unexpected");
|
|
374
|
+
}
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (!isObject(claimed)) {
|
|
378
|
+
mismatches.push("study_accounting missing");
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
mismatches.push(...diff(claimed, expected, "study_accounting"));
|
|
382
|
+
}
|
|
383
|
+
function studyFromInputs(inputs, numerics) {
|
|
384
|
+
const raw = inputs.study;
|
|
385
|
+
if (raw === undefined || raw === null) {
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
const body = requiredObject(raw, "study");
|
|
389
|
+
const observations = studyObservationsOf(body.observations);
|
|
390
|
+
return studyAccounting(observations, whole(body.variants_tried, "variants_tried"), numerics);
|
|
391
|
+
}
|
|
392
|
+
function studyObservationsOf(value) {
|
|
393
|
+
if (!Array.isArray(value)) {
|
|
394
|
+
throw new Error("study observations must be a list");
|
|
395
|
+
}
|
|
396
|
+
return value.map((item) => {
|
|
397
|
+
const body = requiredObject(item, "observation");
|
|
398
|
+
return {
|
|
399
|
+
time_ms: whole(body.time_ms, "time_ms"),
|
|
400
|
+
outcome_r: requiredString(body.outcome_r, "outcome_r"),
|
|
401
|
+
turnover: requiredString(body.turnover ?? "0", "turnover"),
|
|
402
|
+
};
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Re-run a v4+ receipt with the stop floor its fills record (stop_floor_bps), not today's
|
|
407
|
+
* default. An explicit execution.min_stop_slippage_bps is left alone. A forged value moves
|
|
408
|
+
* the rerun's prices, so it still shows up as a mismatch. Mirrors Python
|
|
409
|
+
* receipt._with_recorded_stop_floor.
|
|
410
|
+
*/
|
|
411
|
+
function withRecordedStopFloor(inputs, result) {
|
|
412
|
+
const execution = inputs.execution;
|
|
413
|
+
if (isObject(execution) && Object.prototype.hasOwnProperty.call(execution, "min_stop_slippage_bps")) {
|
|
414
|
+
return inputs;
|
|
415
|
+
}
|
|
416
|
+
if (!isObject(result) || !Array.isArray(result.fills)) {
|
|
417
|
+
return inputs;
|
|
418
|
+
}
|
|
419
|
+
const recorded = new Set();
|
|
420
|
+
for (const item of result.fills) {
|
|
421
|
+
if (isObject(item) && typeof item.stop_floor_bps === "string") {
|
|
422
|
+
recorded.add(item.stop_floor_bps);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
const nonzero = [...recorded].filter((value) => value !== "0");
|
|
426
|
+
if (recorded.size === 0 || nonzero.length > 1) {
|
|
427
|
+
return inputs;
|
|
428
|
+
}
|
|
429
|
+
const base = isObject(execution) ? { ...execution } : {};
|
|
430
|
+
base.min_stop_slippage_bps = nonzero[0] ?? "0";
|
|
431
|
+
return { ...inputs, execution: base };
|
|
432
|
+
}
|
|
433
|
+
function checkSim(inputs, result, mismatches, version) {
|
|
434
|
+
// Re-run with the defaults of the version that wrote the receipt (stop floor, fee
|
|
435
|
+
// schedule, per-fill fee fields, funding grid). See vendor/simDefaults.ts.
|
|
436
|
+
const profile = receiptProfile(version, result);
|
|
437
|
+
const rerunInputs = simDefaults(profile).record_stop_floor ? withRecordedStopFloor(inputs, result) : inputs;
|
|
438
|
+
let rerun;
|
|
439
|
+
try {
|
|
440
|
+
rerun = wireResult(runSim(rerunInputs, profile));
|
|
441
|
+
}
|
|
442
|
+
catch (error) {
|
|
443
|
+
mismatches.push(`sim mismatch: ${messageOf(error)}`);
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
const compared = simDefaults(profile).cost_breakdown ? rerun : withoutCost(rerun);
|
|
447
|
+
if (isObject(result)) {
|
|
448
|
+
mismatches.push(...diff(result, compared, "result"));
|
|
449
|
+
}
|
|
450
|
+
else {
|
|
451
|
+
mismatches.push("result mismatch");
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
function withoutCost(result) {
|
|
455
|
+
const body = { ...result };
|
|
456
|
+
delete body.cost_breakdown;
|
|
457
|
+
if (isObject(body.receipt)) {
|
|
458
|
+
const inner = { ...body.receipt };
|
|
459
|
+
delete inner.cost_breakdown;
|
|
460
|
+
body.receipt = inner;
|
|
461
|
+
}
|
|
462
|
+
return body;
|
|
463
|
+
}
|
|
464
|
+
function checkGuard(receipt, inputs, mismatches) {
|
|
465
|
+
try {
|
|
466
|
+
const limits = asObject(receipt.limits);
|
|
467
|
+
if (limits === null) {
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const session = sessionFrom(limits, receipt.market_snapshot);
|
|
471
|
+
if (session.limits.limitsHash !== sha256Json(limits)) {
|
|
472
|
+
pushOnce(mismatches, "limits_hash mismatch");
|
|
473
|
+
}
|
|
474
|
+
guardedSimulate(requiredString(inputs.market, "market"), decisionOf(inputs.decision), barsOf(inputs.bars), bookOf(inputs.book), feeOf(inputs.fee_version), contextOf(inputs.guard_context), presetOf(limits.preset), session, fundingOf(inputs.funding), intervalOf(inputs.funding_interval_ms));
|
|
475
|
+
}
|
|
476
|
+
catch (error) {
|
|
477
|
+
if (error instanceof GuardBlocked) {
|
|
478
|
+
const codes = error.violations.map((item) => item.code).join(",");
|
|
479
|
+
mismatches.push(`guard mismatch: ${codes}`);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
mismatches.push(`limits mismatch: ${messageOf(error)}`);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
function sessionFrom(limits, snapshot) {
|
|
486
|
+
const preset = presetOf(limits.preset);
|
|
487
|
+
const rows = coinRows(snapshot);
|
|
488
|
+
const market = snapshotFromCoins(rows.map((row) => ({
|
|
489
|
+
name: requiredString(row.name, "name"),
|
|
490
|
+
maxLeverage: whole(row.max_leverage, "max_leverage"),
|
|
491
|
+
openInterest: requiredString(row.open_interest, "open_interest"),
|
|
492
|
+
})));
|
|
493
|
+
return GuardSession.fromConfig(preset, {
|
|
494
|
+
maxLeverage: limits.max_leverage,
|
|
495
|
+
maxNotionalUsd: limits.max_notional_usd,
|
|
496
|
+
dailyLossPct: limits.daily_loss_pct,
|
|
497
|
+
maxOpenPositions: limits.max_open_positions,
|
|
498
|
+
maxSlippageBps: limits.max_slippage_bps,
|
|
499
|
+
orderRatePerSec: limits.order_rate_per_sec,
|
|
500
|
+
allowedCoins: limits.allowed_coins,
|
|
501
|
+
}, limits.loosened === true, market);
|
|
502
|
+
}
|
|
503
|
+
function runSim(inputs, profile = CURRENT_SIM_DEFAULTS) {
|
|
504
|
+
const atr = inputs.atr_at_decision;
|
|
505
|
+
if (atr !== undefined && atr !== null && typeof atr !== "string") {
|
|
506
|
+
throw new Error("atr_at_decision must be a string or null");
|
|
507
|
+
}
|
|
508
|
+
const multiple = inputs.min_stop_atr_multiple ?? "1.0";
|
|
509
|
+
if (typeof multiple !== "string") {
|
|
510
|
+
throw new Error("min_stop_atr_multiple must be a string");
|
|
511
|
+
}
|
|
512
|
+
return simulate(requiredString(inputs.market, "market"), decisionOf(inputs.decision), barsOf(inputs.bars), bookOf(inputs.book), feeOf(inputs.fee_version), null, contextOf(inputs.guard_context), fundingOf(inputs.funding), intervalOf(inputs.funding_interval_ms), executionOf(inputs.execution), atr === undefined || atr === null ? null : atr, multiple, profile);
|
|
513
|
+
}
|
|
514
|
+
function executionOf(value) {
|
|
515
|
+
if (value === undefined || value === null) {
|
|
516
|
+
return null;
|
|
517
|
+
}
|
|
518
|
+
const body = requiredObject(value, "execution");
|
|
519
|
+
const config = {};
|
|
520
|
+
if ("min_stop_slippage_bps" in body) {
|
|
521
|
+
config.minStopSlippageBps = requiredString(body.min_stop_slippage_bps, "min_stop_slippage_bps");
|
|
522
|
+
}
|
|
523
|
+
if ("min_taker_slippage_bps" in body) {
|
|
524
|
+
config.minTakerSlippageBps = requiredString(body.min_taker_slippage_bps, "min_taker_slippage_bps");
|
|
525
|
+
}
|
|
526
|
+
if ("volatility_slippage_scale" in body) {
|
|
527
|
+
config.volatilitySlippageScale = requiredString(body.volatility_slippage_scale, "volatility_slippage_scale");
|
|
528
|
+
}
|
|
529
|
+
if ("book_time_mismatch" in body) {
|
|
530
|
+
const mode = body.book_time_mismatch;
|
|
531
|
+
if (mode !== "warn" && mode !== "fail") {
|
|
532
|
+
throw new Error("book_time_mismatch must be warn or fail");
|
|
533
|
+
}
|
|
534
|
+
config.bookTimeMismatch = mode;
|
|
535
|
+
}
|
|
536
|
+
return config;
|
|
537
|
+
}
|
|
538
|
+
function wireResult(result) {
|
|
539
|
+
const wire = {
|
|
540
|
+
label: result.label,
|
|
541
|
+
market: result.market,
|
|
542
|
+
fills: result.fills,
|
|
543
|
+
fill_source: result.fillSource,
|
|
544
|
+
fee_version: result.feeVersion,
|
|
545
|
+
taker_bps: result.takerBps,
|
|
546
|
+
maker_bps: result.makerBps,
|
|
547
|
+
funding_interval_ms: result.fundingIntervalMs,
|
|
548
|
+
funding_payments: result.fundingPayments,
|
|
549
|
+
unfilled_entry: result.unfilledEntry,
|
|
550
|
+
open_size: result.openSize,
|
|
551
|
+
queue_position: result.queue_position,
|
|
552
|
+
liquidation: result.liquidation,
|
|
553
|
+
cost_breakdown: result.cost_breakdown,
|
|
554
|
+
receipt: result.receipt,
|
|
555
|
+
};
|
|
556
|
+
// Python writes these only when non-empty (engine._finish); mirror that so a live-book
|
|
557
|
+
// receipt (historical: false, e.g. paper) verifies here too.
|
|
558
|
+
if (result.simLabels !== undefined && result.simLabels.length > 0) {
|
|
559
|
+
wire.sim_labels = result.simLabels;
|
|
560
|
+
}
|
|
561
|
+
if (result.simWarnings !== undefined && result.simWarnings.length > 0) {
|
|
562
|
+
wire.sim_warnings = result.simWarnings;
|
|
563
|
+
}
|
|
564
|
+
return wire;
|
|
565
|
+
}
|
|
566
|
+
function decisionOf(value) {
|
|
567
|
+
const body = requiredObject(value, "decision");
|
|
568
|
+
const side = body.side;
|
|
569
|
+
if (side !== "long" && side !== "short") {
|
|
570
|
+
throw new Error("side must be long or short");
|
|
571
|
+
}
|
|
572
|
+
const decision = {
|
|
573
|
+
barIndex: whole(body.bar_index, "bar_index"),
|
|
574
|
+
side,
|
|
575
|
+
size: requiredString(body.size, "size"),
|
|
576
|
+
stop: optionalString(body.stop, "stop"),
|
|
577
|
+
target: optionalString(body.target, "target"),
|
|
578
|
+
};
|
|
579
|
+
const liquidity = body.liquidity ?? "taker";
|
|
580
|
+
if (liquidity === "maker") {
|
|
581
|
+
decision.liquidity = "maker";
|
|
582
|
+
}
|
|
583
|
+
else if (liquidity !== "taker") {
|
|
584
|
+
throw new Error("liquidity must be taker or maker");
|
|
585
|
+
}
|
|
586
|
+
if ("entry_liquidity" in body) {
|
|
587
|
+
const entryLiq = body.entry_liquidity;
|
|
588
|
+
if (entryLiq !== "taker" && entryLiq !== "maker") {
|
|
589
|
+
throw new Error("entry_liquidity must be taker or maker");
|
|
590
|
+
}
|
|
591
|
+
decision.entryLiquidity = entryLiq;
|
|
592
|
+
}
|
|
593
|
+
if ("exit_liquidity" in body) {
|
|
594
|
+
const exitLiq = body.exit_liquidity;
|
|
595
|
+
if (exitLiq !== "taker" && exitLiq !== "maker") {
|
|
596
|
+
throw new Error("exit_liquidity must be taker or maker");
|
|
597
|
+
}
|
|
598
|
+
decision.exitLiquidity = exitLiq;
|
|
599
|
+
}
|
|
600
|
+
const entry = body.entry ?? "market";
|
|
601
|
+
if (entry !== "market" && entry !== "stop") {
|
|
602
|
+
throw new Error("entry must be market or stop");
|
|
603
|
+
}
|
|
604
|
+
if (entry === "stop") {
|
|
605
|
+
decision.entry = "stop";
|
|
606
|
+
decision.entryStop = requiredString(body.entry_stop, "entry_stop");
|
|
607
|
+
}
|
|
608
|
+
return decision;
|
|
609
|
+
}
|
|
610
|
+
function barsOf(value) {
|
|
611
|
+
if (!Array.isArray(value)) {
|
|
612
|
+
throw new Error("bars must be a list");
|
|
613
|
+
}
|
|
614
|
+
return value.map((item) => {
|
|
615
|
+
const body = requiredObject(item, "bar");
|
|
616
|
+
const bar = {
|
|
617
|
+
open: requiredString(body.open, "open"),
|
|
618
|
+
high: requiredString(body.high, "high"),
|
|
619
|
+
low: requiredString(body.low, "low"),
|
|
620
|
+
close: requiredString(body.close, "close"),
|
|
621
|
+
};
|
|
622
|
+
if ("time_ms" in body) {
|
|
623
|
+
bar.timeMs = whole(body.time_ms, "time_ms");
|
|
624
|
+
}
|
|
625
|
+
return bar;
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
function bookOf(value) {
|
|
629
|
+
const body = requiredObject(value, "book");
|
|
630
|
+
const book = { bids: levelsOf(body.bids), asks: levelsOf(body.asks) };
|
|
631
|
+
if ("time_ms" in body) {
|
|
632
|
+
book.timeMs = whole(body.time_ms, "time_ms");
|
|
633
|
+
}
|
|
634
|
+
if ("historical" in body) {
|
|
635
|
+
if (typeof body.historical !== "boolean") {
|
|
636
|
+
throw new Error("historical must be a boolean");
|
|
637
|
+
}
|
|
638
|
+
book.historical = body.historical;
|
|
639
|
+
}
|
|
640
|
+
return book;
|
|
641
|
+
}
|
|
642
|
+
function levelsOf(value) {
|
|
643
|
+
if (!Array.isArray(value)) {
|
|
644
|
+
throw new Error("levels must be a list");
|
|
645
|
+
}
|
|
646
|
+
return value.map((item) => {
|
|
647
|
+
const body = requiredObject(item, "level");
|
|
648
|
+
return { px: requiredString(body.px, "px"), sz: requiredString(body.sz, "sz") };
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
function fundingOf(value) {
|
|
652
|
+
if (value === undefined || value === null) {
|
|
653
|
+
return null;
|
|
654
|
+
}
|
|
655
|
+
if (!Array.isArray(value)) {
|
|
656
|
+
throw new Error("funding must be a list");
|
|
657
|
+
}
|
|
658
|
+
if (value.length === 0) {
|
|
659
|
+
return null;
|
|
660
|
+
}
|
|
661
|
+
return value.map((item) => {
|
|
662
|
+
const body = requiredObject(item, "funding");
|
|
663
|
+
const sample = {
|
|
664
|
+
timeMs: whole(body.time_ms, "time_ms"),
|
|
665
|
+
ratePerHour: requiredString(body.rate_per_hour, "rate_per_hour"),
|
|
666
|
+
oraclePxUsd: requiredString(body.oracle_px_usd, "oracle_px_usd"),
|
|
667
|
+
};
|
|
668
|
+
if ("published_at_ms" in body) {
|
|
669
|
+
sample.publishedAtMs = whole(body.published_at_ms, "published_at_ms");
|
|
670
|
+
}
|
|
671
|
+
return sample;
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
function contextOf(value) {
|
|
675
|
+
if (value === undefined || value === null) {
|
|
676
|
+
return null;
|
|
677
|
+
}
|
|
678
|
+
const body = requiredObject(value, "guard_context");
|
|
679
|
+
const context = {};
|
|
680
|
+
if ("leverage" in body) {
|
|
681
|
+
context.leverage = requiredString(body.leverage, "leverage");
|
|
682
|
+
}
|
|
683
|
+
if ("openPositions" in body || "open_positions" in body) {
|
|
684
|
+
context.openPositions = whole(body.open_positions, "open_positions");
|
|
685
|
+
}
|
|
686
|
+
if ("dailyLossUsd" in body || "daily_loss_usd" in body) {
|
|
687
|
+
context.dailyLossUsd = requiredString(body.daily_loss_usd, "daily_loss_usd");
|
|
688
|
+
}
|
|
689
|
+
if ("dailyLossPct" in body || "daily_loss_pct" in body) {
|
|
690
|
+
context.dailyLossPct = requiredString(body.daily_loss_pct, "daily_loss_pct");
|
|
691
|
+
}
|
|
692
|
+
if ("ageMs" in body || "age_ms" in body) {
|
|
693
|
+
context.ageMs = whole(body.age_ms, "age_ms");
|
|
694
|
+
}
|
|
695
|
+
if ("nowMs" in body || "now_ms" in body) {
|
|
696
|
+
context.nowMs = whole(body.now_ms, "now_ms");
|
|
697
|
+
}
|
|
698
|
+
return context;
|
|
699
|
+
}
|
|
700
|
+
function feeOf(value) {
|
|
701
|
+
if (value === undefined || value === null) {
|
|
702
|
+
return null;
|
|
703
|
+
}
|
|
704
|
+
if (typeof value !== "string") {
|
|
705
|
+
throw new Error("fee_version must be a string or null");
|
|
706
|
+
}
|
|
707
|
+
return value;
|
|
708
|
+
}
|
|
709
|
+
function intervalOf(value) {
|
|
710
|
+
if (value === undefined) {
|
|
711
|
+
return HL_FUNDING_INTERVAL_MS;
|
|
712
|
+
}
|
|
713
|
+
return whole(value, "funding_interval_ms");
|
|
714
|
+
}
|
|
715
|
+
function presetOf(value) {
|
|
716
|
+
if (value === "conservative" || value === "standard" || value === "pro") {
|
|
717
|
+
return value;
|
|
718
|
+
}
|
|
719
|
+
throw new Error("preset must be a known preset");
|
|
720
|
+
}
|
|
721
|
+
function coinRows(value) {
|
|
722
|
+
if (!Array.isArray(value)) {
|
|
723
|
+
throw new Error("market snapshot must be a list");
|
|
724
|
+
}
|
|
725
|
+
return value.map((item) => requiredObject(item, "market snapshot"));
|
|
726
|
+
}
|
|
727
|
+
function diff(expected, actual, path) {
|
|
728
|
+
if (isObject(expected) && isObject(actual)) {
|
|
729
|
+
const found = [];
|
|
730
|
+
const keys = [...new Set([...Object.keys(expected), ...Object.keys(actual)])].sort();
|
|
731
|
+
for (const key of keys) {
|
|
732
|
+
const child = `${path}.${key}`;
|
|
733
|
+
if (!(key in expected)) {
|
|
734
|
+
found.push(`${child} missing`);
|
|
735
|
+
}
|
|
736
|
+
else if (!(key in actual)) {
|
|
737
|
+
found.push(`${child} unexpected`);
|
|
738
|
+
}
|
|
739
|
+
else {
|
|
740
|
+
found.push(...diff(expected[key], actual[key], child));
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
return found;
|
|
744
|
+
}
|
|
745
|
+
if (Array.isArray(expected) && Array.isArray(actual)) {
|
|
746
|
+
const found = [];
|
|
747
|
+
if (expected.length !== actual.length) {
|
|
748
|
+
found.push(`${path} length mismatch`);
|
|
749
|
+
}
|
|
750
|
+
const count = Math.min(expected.length, actual.length);
|
|
751
|
+
for (let index = 0; index < count; index += 1) {
|
|
752
|
+
found.push(...diff(expected[index], actual[index], `${path}[${index}]`));
|
|
753
|
+
}
|
|
754
|
+
return found;
|
|
755
|
+
}
|
|
756
|
+
if (typeof expected !== typeof actual || expected !== actual) {
|
|
757
|
+
return [`${path} mismatch`];
|
|
758
|
+
}
|
|
759
|
+
return [];
|
|
760
|
+
}
|
|
761
|
+
function report(mismatches) {
|
|
762
|
+
const unique = dedupe(mismatches);
|
|
763
|
+
if (unique.length > 0) {
|
|
764
|
+
return { status: "MISMATCH", mismatches: unique };
|
|
765
|
+
}
|
|
766
|
+
return { status: "VERIFIED", mismatches: [] };
|
|
767
|
+
}
|
|
768
|
+
function dedupe(mismatches) {
|
|
769
|
+
const unique = [];
|
|
770
|
+
for (const item of mismatches) {
|
|
771
|
+
if (!unique.includes(item)) {
|
|
772
|
+
unique.push(item);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return unique;
|
|
776
|
+
}
|
|
777
|
+
function pushOnce(mismatches, item) {
|
|
778
|
+
if (!mismatches.includes(item)) {
|
|
779
|
+
mismatches.push(item);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
function sha256Bytes(data) {
|
|
783
|
+
return createHash("sha256").update(data).digest("hex");
|
|
784
|
+
}
|
|
785
|
+
function sameJson(left, right) {
|
|
786
|
+
return canonical(left) === canonical(right);
|
|
787
|
+
}
|
|
788
|
+
function sortValue(value) {
|
|
789
|
+
if (Array.isArray(value)) {
|
|
790
|
+
return value.map((item) => sortValue(item));
|
|
791
|
+
}
|
|
792
|
+
if (isObject(value)) {
|
|
793
|
+
const sorted = {};
|
|
794
|
+
for (const key of Object.keys(value).sort()) {
|
|
795
|
+
sorted[key] = sortValue(value[key]);
|
|
796
|
+
}
|
|
797
|
+
return sorted;
|
|
798
|
+
}
|
|
799
|
+
return value;
|
|
800
|
+
}
|
|
801
|
+
function asObject(value) {
|
|
802
|
+
if (!isObject(value)) {
|
|
803
|
+
return null;
|
|
804
|
+
}
|
|
805
|
+
return value;
|
|
806
|
+
}
|
|
807
|
+
function requiredObject(value, label) {
|
|
808
|
+
if (!isObject(value)) {
|
|
809
|
+
throw new Error(`${label} must be an object`);
|
|
810
|
+
}
|
|
811
|
+
return value;
|
|
812
|
+
}
|
|
813
|
+
function isObject(value) {
|
|
814
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
815
|
+
}
|
|
816
|
+
function requiredString(value, label) {
|
|
817
|
+
if (typeof value !== "string" || value === "") {
|
|
818
|
+
throw new Error(`${label} must be a string`);
|
|
819
|
+
}
|
|
820
|
+
return value;
|
|
821
|
+
}
|
|
822
|
+
function optionalString(value, label) {
|
|
823
|
+
if (value === undefined || value === null) {
|
|
824
|
+
return null;
|
|
825
|
+
}
|
|
826
|
+
return requiredString(value, label);
|
|
827
|
+
}
|
|
828
|
+
function whole(value, label) {
|
|
829
|
+
if (typeof value !== "number" || !Number.isInteger(value)) {
|
|
830
|
+
throw new Error(`${label} must be an integer`);
|
|
831
|
+
}
|
|
832
|
+
return value;
|
|
833
|
+
}
|
|
834
|
+
function messageOf(error) {
|
|
835
|
+
if (error instanceof Error) {
|
|
836
|
+
return error.message;
|
|
837
|
+
}
|
|
838
|
+
return "check failed";
|
|
839
|
+
}
|