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