@perpbrain/sdk 0.1.3 → 0.2.1
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/dist/cjs/calibration.d.ts +31 -0
- package/dist/cjs/calibration.js +180 -0
- package/dist/cjs/clientMeta.d.ts +12 -0
- package/dist/cjs/clientMeta.js +83 -0
- package/dist/cjs/fillLink.d.ts +77 -0
- package/dist/cjs/fillLink.js +328 -0
- package/dist/cjs/fixedDecimal.d.ts +11 -0
- package/dist/cjs/fixedDecimal.js +39 -0
- package/dist/cjs/fundingRecon.d.ts +16 -0
- package/dist/cjs/fundingRecon.js +261 -0
- package/dist/cjs/holding.d.ts +48 -0
- package/dist/cjs/holding.js +263 -0
- package/dist/cjs/index.d.ts +11 -1
- package/dist/cjs/index.js +46 -1
- package/dist/cjs/receipt.d.ts +49 -2
- package/dist/cjs/receipt.js +160 -10
- package/dist/esm/calibration.d.ts +31 -0
- package/dist/esm/calibration.js +174 -0
- package/dist/esm/clientMeta.d.ts +12 -0
- package/dist/esm/clientMeta.js +77 -0
- package/dist/esm/fillLink.d.ts +77 -0
- package/dist/esm/fillLink.js +318 -0
- package/dist/esm/fixedDecimal.d.ts +11 -0
- package/dist/esm/fixedDecimal.js +32 -0
- package/dist/esm/fundingRecon.d.ts +16 -0
- package/dist/esm/fundingRecon.js +256 -0
- package/dist/esm/holding.d.ts +48 -0
- package/dist/esm/holding.js +257 -0
- package/dist/esm/index.d.ts +11 -1
- package/dist/esm/index.js +6 -1
- package/dist/esm/receipt.d.ts +49 -2
- package/dist/esm/receipt.js +154 -10
- package/package.json +1 -1
package/dist/cjs/receipt.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/** Re-derive a simulation receipt. The check is verified and reproducible. */
|
|
3
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.RECEIPT_VERSION = exports.RECEIPT_KIND = exports.RECEIPT_STATEMENT = void 0;
|
|
4
|
+
exports.InvalidLimitError = exports.MissingInputsError = exports.UnsupportedVerificationError = exports.ResourceLimitError = exports.NoVerdictError = exports.RECEIPT_VERSION = exports.RECEIPT_KIND = exports.RECEIPT_STATEMENT = void 0;
|
|
5
5
|
exports.verifyReceipt = verifyReceipt;
|
|
6
6
|
exports.canonical = canonical;
|
|
7
7
|
exports.sha256Json = sha256Json;
|
|
@@ -14,11 +14,16 @@ exports.buildReceiptFiles = buildReceiptFiles;
|
|
|
14
14
|
exports.writeReceiptDir = writeReceiptDir;
|
|
15
15
|
exports.buildReceiptDir = buildReceiptDir;
|
|
16
16
|
exports.buildGuardedReceipt = buildGuardedReceipt;
|
|
17
|
+
exports.readChunksCapped = readChunksCapped;
|
|
17
18
|
exports.verifyReceiptAt = verifyReceiptAt;
|
|
19
|
+
const clientMeta_ts_1 = require("./clientMeta.js");
|
|
18
20
|
const node_crypto_1 = require("node:crypto");
|
|
19
21
|
const node_fs_1 = require("node:fs");
|
|
20
22
|
const node_path_1 = require("node:path");
|
|
21
23
|
const guards_ts_1 = require("./guards.js");
|
|
24
|
+
const calibration_ts_1 = require("./calibration.js");
|
|
25
|
+
const fundingRecon_ts_1 = require("./fundingRecon.js");
|
|
26
|
+
const holding_ts_1 = require("./holding.js");
|
|
22
27
|
const guarded_ts_1 = require("./guarded.js");
|
|
23
28
|
const simDefaults_ts_1 = require("./vendor/simDefaults.js");
|
|
24
29
|
const study_ts_1 = require("./study.js");
|
|
@@ -133,19 +138,24 @@ function simulateInputs(inputs) {
|
|
|
133
138
|
// Receipts store the snake_case wire form; do not hash the camelCase runtime object.
|
|
134
139
|
return wireResult(runSim(inputs));
|
|
135
140
|
}
|
|
136
|
-
function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
|
|
141
|
+
function buildReceiptFiles(inputs, result, limits, marketSnapshot, clientMetadata) {
|
|
137
142
|
const inputsBytes = canonicalFileBytes(inputs);
|
|
138
143
|
const dataSnapshotId = sha256Bytes(inputsBytes);
|
|
139
144
|
const limitsHash = sha256Json(limits);
|
|
140
145
|
const marketSnapshotId = sha256Json(marketSnapshot);
|
|
141
146
|
const resultSha256 = sha256Json(result);
|
|
142
|
-
|
|
147
|
+
let manifest = {
|
|
143
148
|
data_snapshot_id: dataSnapshotId,
|
|
144
149
|
files: [{ file: "inputs.json", rows: 1, sha256: dataSnapshotId }],
|
|
145
150
|
limits_hash: limitsHash,
|
|
146
151
|
market_snapshot_id: marketSnapshotId,
|
|
147
152
|
result_sha256: resultSha256,
|
|
148
153
|
};
|
|
154
|
+
// Issue 97: an opaque hashed block in the manifest only. Undefined or empty leaves the
|
|
155
|
+
// manifest, and so the receipt, byte-identical to a build without it.
|
|
156
|
+
if (clientMetadata !== undefined && clientMetadata.length > 0) {
|
|
157
|
+
manifest = (0, clientMeta_ts_1.attachClientMeta)(manifest, clientMetadata);
|
|
158
|
+
}
|
|
149
159
|
const manifestBytes = prettyBytes(manifest);
|
|
150
160
|
const receipt = {
|
|
151
161
|
data_snapshot_id: dataSnapshotId,
|
|
@@ -163,6 +173,11 @@ function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
|
|
|
163
173
|
statement: exports.RECEIPT_STATEMENT,
|
|
164
174
|
version: exports.RECEIPT_VERSION,
|
|
165
175
|
};
|
|
176
|
+
// Mirror the Python builder: record study accounting whenever the inputs carry a study block.
|
|
177
|
+
const recordedStudy = studyFromInputs(inputs, (0, simDefaults_ts_1.simDefaults)(simDefaults_ts_1.CURRENT_SIM_DEFAULTS).numerics === "fixed18" ? "fixed18" : "float");
|
|
178
|
+
if (recordedStudy !== null) {
|
|
179
|
+
receipt.study_accounting = { ...recordedStudy };
|
|
180
|
+
}
|
|
166
181
|
return {
|
|
167
182
|
receipt,
|
|
168
183
|
manifest,
|
|
@@ -227,16 +242,118 @@ function insideDirectory(root, ref) {
|
|
|
227
242
|
return (0, node_path_1.join)(root, candidate);
|
|
228
243
|
}
|
|
229
244
|
/** Read a receipt.json file, or a directory that contains one, and check it. */
|
|
230
|
-
|
|
231
|
-
|
|
245
|
+
/**
|
|
246
|
+
* Base for "no verdict reached": the check did not run to VERIFIED or MISMATCH. Thrown, never
|
|
247
|
+
* folded into a report, and says nothing about whether the record is valid.
|
|
248
|
+
*/
|
|
249
|
+
class NoVerdictError extends Error {
|
|
250
|
+
constructor(message) {
|
|
251
|
+
super(message);
|
|
252
|
+
this.name = "NoVerdictError";
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
exports.NoVerdictError = NoVerdictError;
|
|
256
|
+
/**
|
|
257
|
+
* A file is larger than the caller's explicit read limit. Thrown, never folded into a
|
|
258
|
+
* MISMATCH or VERIFIED report: "too big to check" is a resource failure, not a verdict.
|
|
259
|
+
*/
|
|
260
|
+
class ResourceLimitError extends NoVerdictError {
|
|
261
|
+
constructor(message) {
|
|
262
|
+
super(message);
|
|
263
|
+
this.name = "ResourceLimitError";
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
exports.ResourceLimitError = ResourceLimitError;
|
|
267
|
+
/** The record is of a kind this function does not check. No verdict was reached: this is neither
|
|
268
|
+
* VERIFIED nor MISMATCH, and says nothing about whether the record is valid. */
|
|
269
|
+
class UnsupportedVerificationError extends NoVerdictError {
|
|
270
|
+
constructor(message) {
|
|
271
|
+
super(message);
|
|
272
|
+
this.name = "UnsupportedVerificationError";
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
exports.UnsupportedVerificationError = UnsupportedVerificationError;
|
|
276
|
+
/** The inputs a record is checked against were not supplied (not found beside it). No verdict:
|
|
277
|
+
* a missing file is not evidence that the record is invalid. */
|
|
278
|
+
class MissingInputsError extends NoVerdictError {
|
|
279
|
+
constructor(message) {
|
|
280
|
+
super(message);
|
|
281
|
+
this.name = "MissingInputsError";
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
exports.MissingInputsError = MissingInputsError;
|
|
285
|
+
/** The caller's `maxBytes` is not a positive safe integer. A caller error, thrown before any file
|
|
286
|
+
* is read: it is neither a verdict nor a resource failure. */
|
|
287
|
+
class InvalidLimitError extends RangeError {
|
|
288
|
+
constructor(message) {
|
|
289
|
+
super(message);
|
|
290
|
+
this.name = "InvalidLimitError";
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
exports.InvalidLimitError = InvalidLimitError;
|
|
294
|
+
function assertLimit(maxBytes) {
|
|
295
|
+
if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) {
|
|
296
|
+
throw new InvalidLimitError(`maxBytes must be a positive safe integer, got ${String(maxBytes)}`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const READ_CHUNK = 64 * 1024;
|
|
300
|
+
/**
|
|
301
|
+
* Read chunks until end of file or one byte past ``maxBytes``. The size comes from the bytes
|
|
302
|
+
* actually read, never from a stat, so a file that grows or is replaced after any size check is
|
|
303
|
+
* still bounded, and a large limit never allocates for the limit.
|
|
304
|
+
*/
|
|
305
|
+
function readChunksCapped(read, maxBytes, name) {
|
|
306
|
+
const chunks = [];
|
|
307
|
+
let total = 0;
|
|
308
|
+
for (;;) {
|
|
309
|
+
const want = Math.min(READ_CHUNK, maxBytes + 1 - total);
|
|
310
|
+
const chunk = Buffer.alloc(want);
|
|
311
|
+
const n = read(chunk, want);
|
|
312
|
+
if (n === 0)
|
|
313
|
+
break;
|
|
314
|
+
total += n;
|
|
315
|
+
if (total > maxBytes) {
|
|
316
|
+
throw new ResourceLimitError(`${name} exceeds the ${maxBytes} byte read limit`);
|
|
317
|
+
}
|
|
318
|
+
chunks.push(n === want ? chunk : chunk.subarray(0, n));
|
|
319
|
+
}
|
|
320
|
+
return Buffer.concat(chunks, total);
|
|
321
|
+
}
|
|
322
|
+
function readCapped(path, maxBytes) {
|
|
323
|
+
if (maxBytes === undefined) {
|
|
324
|
+
return (0, node_fs_1.readFileSync)(path);
|
|
325
|
+
}
|
|
326
|
+
const fd = (0, node_fs_1.openSync)(path, "r");
|
|
327
|
+
try {
|
|
328
|
+
const name = path.split(/[\\/]/).pop() ?? path;
|
|
329
|
+
return readChunksCapped((buffer, length) => (0, node_fs_1.readSync)(fd, buffer, 0, length, null), maxBytes, name);
|
|
330
|
+
}
|
|
331
|
+
finally {
|
|
332
|
+
(0, node_fs_1.closeSync)(fd);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
function verifyReceiptAt(path, options = {}) {
|
|
336
|
+
const maxBytes = options.maxBytes;
|
|
337
|
+
assertLimit(maxBytes);
|
|
338
|
+
let receiptFile = path;
|
|
339
|
+
if ((0, node_fs_1.existsSync)(path) && (0, node_fs_1.statSync)(path).isDirectory()) {
|
|
340
|
+
receiptFile = (0, node_path_1.join)(path, "receipt.json");
|
|
341
|
+
const calibrationFile = (0, node_path_1.join)(path, "calibration.json");
|
|
342
|
+
// A directory with no receipt.json but a calibration.json is a calibration report.
|
|
343
|
+
if (!(0, node_fs_1.existsSync)(receiptFile) && (0, node_fs_1.existsSync)(calibrationFile)) {
|
|
344
|
+
receiptFile = calibrationFile;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
232
347
|
if (!(0, node_fs_1.existsSync)(receiptFile) || !(0, node_fs_1.statSync)(receiptFile).isFile()) {
|
|
233
348
|
return report(["receipt.json missing"]);
|
|
234
349
|
}
|
|
235
350
|
let loaded;
|
|
236
351
|
try {
|
|
237
|
-
loaded = JSON.parse((
|
|
352
|
+
loaded = JSON.parse(readCapped(receiptFile, maxBytes).toString("utf8"));
|
|
238
353
|
}
|
|
239
|
-
catch {
|
|
354
|
+
catch (error) {
|
|
355
|
+
if (error instanceof NoVerdictError)
|
|
356
|
+
throw error;
|
|
240
357
|
return report(["receipt json mismatch"]);
|
|
241
358
|
}
|
|
242
359
|
const receipt = asObject(loaded);
|
|
@@ -244,9 +361,31 @@ function verifyReceiptAt(path) {
|
|
|
244
361
|
return report(["receipt mismatch"]);
|
|
245
362
|
}
|
|
246
363
|
const root = (0, node_path_1.dirname)(receiptFile);
|
|
364
|
+
if (receipt.kind === fundingRecon_ts_1.RECON_KIND) {
|
|
365
|
+
// A funding-reconciliation receipt is checked against inputs.json beside it.
|
|
366
|
+
const inputsPath = (0, node_path_1.join)(root, "inputs.json");
|
|
367
|
+
if (!(0, node_fs_1.existsSync)(inputsPath) || !(0, node_fs_1.statSync)(inputsPath).isFile()) {
|
|
368
|
+
return report(["inputs.json missing (download it next to receipt.json)"]);
|
|
369
|
+
}
|
|
370
|
+
return (0, fundingRecon_ts_1.verifyReconReceipt)(receipt, readCapped(inputsPath, maxBytes));
|
|
371
|
+
}
|
|
372
|
+
if (receipt.kind === calibration_ts_1.CALIBRATION_KIND) {
|
|
373
|
+
// A calibration report is checked against calibration-inputs.json beside it. VERIFIED here means the
|
|
374
|
+
// report reproduces from those inputs (self-consistency); it does not authenticate the inputs or any venue.
|
|
375
|
+
const inputsPath = (0, node_path_1.join)(root, "calibration-inputs.json");
|
|
376
|
+
if (!(0, node_fs_1.existsSync)(inputsPath) || !(0, node_fs_1.statSync)(inputsPath).isFile()) {
|
|
377
|
+
throw new MissingInputsError("calibration-inputs.json missing (keep it next to calibration.json)");
|
|
378
|
+
}
|
|
379
|
+
const checked = (0, calibration_ts_1.verifyReport)(receipt, readCapped(inputsPath, maxBytes));
|
|
380
|
+
return { ...report(checked.mismatches), scope: "self-consistency-only", venue_authenticated: false };
|
|
381
|
+
}
|
|
382
|
+
if (receipt.kind === holding_ts_1.HOLDING_KIND) {
|
|
383
|
+
// A holding record needs the fills and the sim receipt it was linked to; verifyHolding takes them.
|
|
384
|
+
throw new UnsupportedVerificationError("a holding record cannot be checked by verifyReceiptAt: use verifyHolding with its fills and sim receipt");
|
|
385
|
+
}
|
|
247
386
|
const missing = [];
|
|
248
387
|
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() ? (
|
|
388
|
+
const manifest = (0, node_fs_1.existsSync)(manifestPath) && (0, node_fs_1.statSync)(manifestPath).isFile() ? readCapped(manifestPath, maxBytes) : null;
|
|
250
389
|
if (manifest === null) {
|
|
251
390
|
missing.push("manifest missing");
|
|
252
391
|
}
|
|
@@ -259,13 +398,15 @@ function verifyReceiptAt(path) {
|
|
|
259
398
|
try {
|
|
260
399
|
const rawPath = insideDirectory(root, rawRef);
|
|
261
400
|
if ((0, node_fs_1.existsSync)(rawPath) && (0, node_fs_1.statSync)(rawPath).isFile()) {
|
|
262
|
-
inputs = (
|
|
401
|
+
inputs = readCapped(rawPath, maxBytes);
|
|
263
402
|
}
|
|
264
403
|
else {
|
|
265
404
|
missing.push(`${rawRef} missing`);
|
|
266
405
|
}
|
|
267
406
|
}
|
|
268
|
-
catch {
|
|
407
|
+
catch (error) {
|
|
408
|
+
if (error instanceof NoVerdictError)
|
|
409
|
+
throw error;
|
|
269
410
|
missing.push("raw_ref mismatch");
|
|
270
411
|
}
|
|
271
412
|
}
|
|
@@ -347,6 +488,15 @@ function checkManifest(manifest, receipt, mismatches) {
|
|
|
347
488
|
mismatches.push(`manifest ${key} mismatch`);
|
|
348
489
|
}
|
|
349
490
|
}
|
|
491
|
+
if ("client_metadata" in manifest) {
|
|
492
|
+
try {
|
|
493
|
+
(0, clientMeta_ts_1.validateClientMeta)(manifest.client_metadata);
|
|
494
|
+
}
|
|
495
|
+
catch (error) {
|
|
496
|
+
// Fixed validator messages only; never echo manifest content.
|
|
497
|
+
mismatches.push(`manifest client_metadata mismatch: ${messageOf(error)}`);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
350
500
|
const files = manifest.files;
|
|
351
501
|
const rawRef = receipt.raw_ref;
|
|
352
502
|
if (!Array.isArray(files)) {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export declare const CALIBRATION_KIND = "perpbrain.calibration-report";
|
|
2
|
+
export declare const CALIBRATION_VERSION = 2;
|
|
3
|
+
export declare const CALIBRATION_STATEMENT = "reproducible from the supplied inputs; links are candidates, not venue-authenticated";
|
|
4
|
+
/** Proposed minimum sample gate, not statistical sufficiency. */
|
|
5
|
+
export declare const MIN_SAMPLE = 10;
|
|
6
|
+
type Row = Record<string, unknown>;
|
|
7
|
+
export interface CalibrationCandidate {
|
|
8
|
+
link_record: Row;
|
|
9
|
+
link_sha256: string;
|
|
10
|
+
sim_defaults_version?: unknown;
|
|
11
|
+
group?: string;
|
|
12
|
+
link_inputs?: unknown;
|
|
13
|
+
}
|
|
14
|
+
export interface CalibrationInputs {
|
|
15
|
+
window: unknown;
|
|
16
|
+
sim_defaults_version: unknown;
|
|
17
|
+
candidates: CalibrationCandidate[];
|
|
18
|
+
}
|
|
19
|
+
export interface BuiltReport {
|
|
20
|
+
record: Row;
|
|
21
|
+
recordBytes: Buffer;
|
|
22
|
+
inputsBytes: Buffer;
|
|
23
|
+
}
|
|
24
|
+
export interface ReportVerify {
|
|
25
|
+
status: "VERIFIED" | "MISMATCH";
|
|
26
|
+
mismatches: string[];
|
|
27
|
+
}
|
|
28
|
+
export declare function computeReport(inputs: CalibrationInputs): Row;
|
|
29
|
+
export declare function buildReport(inputs: CalibrationInputs): BuiltReport;
|
|
30
|
+
export declare function verifyReport(record: unknown, inputsBytes: Buffer): ReportVerify;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Calibration report (feedback loop), per pb-specs-28nov.md section 4.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript port of `perpbrain_read.sim.calibration` (report version 2). Read-only:
|
|
5
|
+
* aggregates candidate link records into slippage statistics for a reviewer. Nothing here
|
|
6
|
+
* proves a link is genuine. A candidate is RECOMPUTED (it carries its link_inputs and the link
|
|
7
|
+
* hash and result reproduce from them: integrity only) or UNVERIFIED (only the self-supplied
|
|
8
|
+
* hash was checked). Only RECOMPUTED candidates can meet the sample gate. Duplicates (same link
|
|
9
|
+
* hash, or the same fills under a different link) count once. Arithmetic is integer fixed point
|
|
10
|
+
* (1e18), truncating toward zero, identical to the Python side. No automatic promotion.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { canonical } from "./receipt.js";
|
|
14
|
+
import { computeLink } from "./fillLink.js";
|
|
15
|
+
import { formatFixed, parseStrictFixed, tdiv } from "./fixedDecimal.js";
|
|
16
|
+
export const CALIBRATION_KIND = "perpbrain.calibration-report";
|
|
17
|
+
export const CALIBRATION_VERSION = 2;
|
|
18
|
+
export const CALIBRATION_STATEMENT = "reproducible from the supplied inputs; links are candidates, not venue-authenticated";
|
|
19
|
+
/** Proposed minimum sample gate, not statistical sufficiency. */
|
|
20
|
+
export const MIN_SAMPLE = 10;
|
|
21
|
+
function sha256Hex(raw) {
|
|
22
|
+
return createHash("sha256").update(raw).digest("hex");
|
|
23
|
+
}
|
|
24
|
+
function recomputed(link, cand) {
|
|
25
|
+
const linkIn = cand.link_inputs;
|
|
26
|
+
if (linkIn === null || typeof linkIn !== "object" || Array.isArray(linkIn))
|
|
27
|
+
return false;
|
|
28
|
+
try {
|
|
29
|
+
if (sha256Hex(canonical(linkIn)) !== link.inputs_sha256)
|
|
30
|
+
return false;
|
|
31
|
+
return canonical(computeLink(linkIn)) === canonical(link.result);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function fillsKey(link) {
|
|
38
|
+
const res = (link.result ?? {});
|
|
39
|
+
return canonical({ oids: res.oids ?? null, hashes: res.hashes ?? null });
|
|
40
|
+
}
|
|
41
|
+
function stats(values, basis) {
|
|
42
|
+
const vals = [...values].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
43
|
+
const n = vals.length;
|
|
44
|
+
if (n === 0)
|
|
45
|
+
return null;
|
|
46
|
+
const mid = Math.floor(n / 2);
|
|
47
|
+
const median = n % 2 ? vals[mid] : tdiv(vals[mid - 1] + vals[mid], 2n);
|
|
48
|
+
const sum = vals.reduce((a, b) => a + b, 0n);
|
|
49
|
+
return {
|
|
50
|
+
basis,
|
|
51
|
+
n,
|
|
52
|
+
mean_bps: formatFixed(tdiv(sum, BigInt(n))),
|
|
53
|
+
median_bps: formatFixed(median),
|
|
54
|
+
p90_bps: formatFixed(vals[Math.floor((9 * (n - 1)) / 10)]),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export function computeReport(inputs) {
|
|
58
|
+
const excluded = [];
|
|
59
|
+
const valid = [];
|
|
60
|
+
inputs.candidates.forEach((cand, idx) => {
|
|
61
|
+
const sha = cand.link_sha256;
|
|
62
|
+
const link = cand.link_record;
|
|
63
|
+
const drop = (reason) => excluded.push({ link_sha256: sha, reason });
|
|
64
|
+
if (link.kind !== "perpbrain.execution-link")
|
|
65
|
+
return drop("WRONG_KIND");
|
|
66
|
+
if (sha256Hex(canonical(link)) !== sha)
|
|
67
|
+
return drop("HASH_MISMATCH");
|
|
68
|
+
const res = (link.result ?? {});
|
|
69
|
+
if (res.status !== "LINKED") {
|
|
70
|
+
return drop(typeof res.status === "string" && res.status ? res.status : "NOT_LINKED");
|
|
71
|
+
}
|
|
72
|
+
if (cand.sim_defaults_version !== inputs.sim_defaults_version) {
|
|
73
|
+
return drop("DEFAULTS_VERSION_MISMATCH");
|
|
74
|
+
}
|
|
75
|
+
valid.push({ idx, cand, ok: recomputed(link, cand) });
|
|
76
|
+
});
|
|
77
|
+
// Duplicate groups keep a recomputed candidate over an unrecomputed one, then the earliest.
|
|
78
|
+
const seenHash = new Set();
|
|
79
|
+
const seenFills = new Set();
|
|
80
|
+
const kept = [];
|
|
81
|
+
const order = [...valid].sort((x, y) => Number(!x.ok) - Number(!y.ok) || x.idx - y.idx);
|
|
82
|
+
for (const v of order) {
|
|
83
|
+
const sha = v.cand.link_sha256;
|
|
84
|
+
const key = fillsKey(v.cand.link_record);
|
|
85
|
+
if (seenHash.has(sha)) {
|
|
86
|
+
excluded.push({ link_sha256: sha, reason: "DUPLICATE_LINK" });
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (seenFills.has(key)) {
|
|
90
|
+
excluded.push({ link_sha256: sha, reason: "DUPLICATE_FILLS" });
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
seenHash.add(sha);
|
|
94
|
+
seenFills.add(key);
|
|
95
|
+
kept.push(v);
|
|
96
|
+
}
|
|
97
|
+
kept.sort((x, y) => x.idx - y.idx);
|
|
98
|
+
const included = kept.map((k) => k.cand);
|
|
99
|
+
const groups = new Map();
|
|
100
|
+
for (const { cand, ok } of kept) {
|
|
101
|
+
const group = String(cand.group ?? "unknown");
|
|
102
|
+
const res = cand.link_record.result;
|
|
103
|
+
const value = parseStrictFixed(res.slippage_vs_sim_bps, "slippage_vs_sim_bps");
|
|
104
|
+
const items = groups.get(group) ?? [];
|
|
105
|
+
items.push({ value, ok });
|
|
106
|
+
groups.set(group, items);
|
|
107
|
+
}
|
|
108
|
+
const outGroups = {};
|
|
109
|
+
for (const group of [...groups.keys()].sort()) {
|
|
110
|
+
const items = groups.get(group);
|
|
111
|
+
const recVals = items.filter((i) => i.ok).map((i) => i.value);
|
|
112
|
+
outGroups[group] = {
|
|
113
|
+
candidate_count: items.length,
|
|
114
|
+
recomputed_count: recVals.length,
|
|
115
|
+
unrecomputed_count: items.length - recVals.length,
|
|
116
|
+
sufficiency: recVals.length >= MIN_SAMPLE ? "MIN_SAMPLE_MET" : "INSUFFICIENT_DATA",
|
|
117
|
+
candidate_stats: stats(items.map((i) => i.value), "ALL_DEDUPED_CANDIDATES_UNVERIFIED"),
|
|
118
|
+
recomputed_stats: stats(recVals, "RECOMPUTED_ONLY"),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
window: inputs.window,
|
|
123
|
+
sim_defaults_version: inputs.sim_defaults_version,
|
|
124
|
+
included: included.map((c) => c.link_sha256),
|
|
125
|
+
excluded,
|
|
126
|
+
groups: outGroups,
|
|
127
|
+
proposal: null,
|
|
128
|
+
note: "candidate statistics for reviewer judgment; no automatic promotion",
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
export function buildReport(inputs) {
|
|
132
|
+
const raw = canonical(inputs);
|
|
133
|
+
const result = computeReport(inputs);
|
|
134
|
+
const record = {
|
|
135
|
+
kind: CALIBRATION_KIND,
|
|
136
|
+
version: CALIBRATION_VERSION,
|
|
137
|
+
statement: CALIBRATION_STATEMENT,
|
|
138
|
+
inputs_sha256: sha256Hex(raw),
|
|
139
|
+
result,
|
|
140
|
+
result_sha256: sha256Hex(canonical(result)),
|
|
141
|
+
};
|
|
142
|
+
return {
|
|
143
|
+
record,
|
|
144
|
+
recordBytes: Buffer.from(canonical(record) + "\n", "utf8"),
|
|
145
|
+
inputsBytes: Buffer.from(raw + "\n", "utf8"),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
export function verifyReport(record, inputsBytes) {
|
|
149
|
+
const problems = [];
|
|
150
|
+
const body = (record ?? null);
|
|
151
|
+
if (body === null || typeof body !== "object") {
|
|
152
|
+
return { status: "MISMATCH", mismatches: ["record must be an object"] };
|
|
153
|
+
}
|
|
154
|
+
if (body.kind !== CALIBRATION_KIND)
|
|
155
|
+
problems.push("kind");
|
|
156
|
+
if (body.version !== CALIBRATION_VERSION)
|
|
157
|
+
problems.push("version");
|
|
158
|
+
let result;
|
|
159
|
+
try {
|
|
160
|
+
const inputs = JSON.parse(inputsBytes.toString("utf8"));
|
|
161
|
+
if (sha256Hex(canonical(inputs)) !== body.inputs_sha256)
|
|
162
|
+
problems.push("inputs_sha256");
|
|
163
|
+
result = computeReport(inputs);
|
|
164
|
+
}
|
|
165
|
+
catch (exc) {
|
|
166
|
+
problems.push(`inputs: ${exc instanceof Error ? exc.message : String(exc)}`);
|
|
167
|
+
return { status: "MISMATCH", mismatches: problems };
|
|
168
|
+
}
|
|
169
|
+
if (canonical(body.result) !== canonical(result))
|
|
170
|
+
problems.push("result");
|
|
171
|
+
if (body.result_sha256 !== sha256Hex(canonical(result)))
|
|
172
|
+
problems.push("result_sha256");
|
|
173
|
+
return { status: problems.length ? "MISMATCH" : "VERIFIED", mismatches: problems };
|
|
174
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare const CLIENT_META_MAX_CANONICAL_BYTES = 4096;
|
|
2
|
+
export declare const CLIENT_META_ALLOWED_KEYS: ReadonlySet<string>;
|
|
3
|
+
export interface ClientMetaEntry {
|
|
4
|
+
key: string;
|
|
5
|
+
value: string;
|
|
6
|
+
}
|
|
7
|
+
/** One opaque entry: the SHA-256 of an off-venue artifact, never the artifact. */
|
|
8
|
+
export declare function makeEntry(key: string, payload: Buffer | string): ClientMetaEntry;
|
|
9
|
+
/** Shape and size checks; the verifier ignores-but-binds the entries themselves. */
|
|
10
|
+
export declare function validateClientMeta(block: unknown): void;
|
|
11
|
+
/** Return a new manifest carrying client_metadata; the input manifest is untouched. */
|
|
12
|
+
export declare function attachClientMeta(manifest: Record<string, unknown>, entries: ClientMetaEntry[]): Record<string, unknown>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional hashed client metadata on receipt manifests (issue 97).
|
|
3
|
+
*
|
|
4
|
+
* TypeScript port of `perpbrain_read.sim.client_meta`. The block lives in the MANIFEST, not
|
|
5
|
+
* the receipt body: the receipt already pins manifest_sha256 and the shipped verifier
|
|
6
|
+
* re-hashes the manifest bytes, so a manifest block is bound end-to-end with no
|
|
7
|
+
* receipt-schema or verifier change. Keys come from a fixed allow-list (no free-text key can
|
|
8
|
+
* carry strategy detail). Values are SHA-256 hex digests only. A digest hides the artifact only
|
|
9
|
+
* if the artifact is high-entropy: a short or guessable input can be recovered by hashing
|
|
10
|
+
* guesses, so salt anything small before hashing. This is hashing, not confidentiality. Absent
|
|
11
|
+
* and null are equivalent and produce byte-identical manifests. Canonical encoding is capped
|
|
12
|
+
* at 4 KiB.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { canonical } from "./receipt.js";
|
|
16
|
+
export const CLIENT_META_MAX_CANONICAL_BYTES = 4096;
|
|
17
|
+
export const CLIENT_META_ALLOWED_KEYS = new Set([
|
|
18
|
+
"offvenue_leg_sha256",
|
|
19
|
+
"note_sha256",
|
|
20
|
+
"strategy_sha256",
|
|
21
|
+
"config_sha256",
|
|
22
|
+
"dataset_sha256",
|
|
23
|
+
"model_sha256",
|
|
24
|
+
"code_sha256",
|
|
25
|
+
]);
|
|
26
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
27
|
+
function sha256Hex(raw) {
|
|
28
|
+
return createHash("sha256").update(raw).digest("hex");
|
|
29
|
+
}
|
|
30
|
+
/** One opaque entry: the SHA-256 of an off-venue artifact, never the artifact. */
|
|
31
|
+
export function makeEntry(key, payload) {
|
|
32
|
+
if (!CLIENT_META_ALLOWED_KEYS.has(key))
|
|
33
|
+
throw new Error("key is not in the allow-list");
|
|
34
|
+
return { key, value: sha256Hex(payload) };
|
|
35
|
+
}
|
|
36
|
+
/** Shape and size checks; the verifier ignores-but-binds the entries themselves. */
|
|
37
|
+
export function validateClientMeta(block) {
|
|
38
|
+
if (block === null || typeof block !== "object") {
|
|
39
|
+
throw new Error("client_metadata version must be 1");
|
|
40
|
+
}
|
|
41
|
+
const body = block;
|
|
42
|
+
if (body.version !== 1)
|
|
43
|
+
throw new Error("client_metadata version must be 1");
|
|
44
|
+
if (Object.keys(body).sort().join(",") !== "entries,version") {
|
|
45
|
+
throw new Error("client_metadata has unknown or missing fields");
|
|
46
|
+
}
|
|
47
|
+
if (!Array.isArray(body.entries))
|
|
48
|
+
throw new Error("client_metadata.entries must be a list");
|
|
49
|
+
const seen = new Set();
|
|
50
|
+
for (const entry of body.entries) {
|
|
51
|
+
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
|
|
52
|
+
throw new Error("entry must be an object");
|
|
53
|
+
}
|
|
54
|
+
if (Object.keys(entry).sort().join(",") !== "key,value") {
|
|
55
|
+
throw new Error("entry must have exactly key and value");
|
|
56
|
+
}
|
|
57
|
+
const { key, value } = entry;
|
|
58
|
+
if (typeof key !== "string" || !CLIENT_META_ALLOWED_KEYS.has(key)) {
|
|
59
|
+
throw new Error("key is not in the allow-list");
|
|
60
|
+
}
|
|
61
|
+
if (seen.has(key))
|
|
62
|
+
throw new Error("duplicate key");
|
|
63
|
+
seen.add(key);
|
|
64
|
+
if (typeof value !== "string" || !HEX64.test(value)) {
|
|
65
|
+
throw new Error("value must be a lowercase sha256 hex digest");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (Buffer.byteLength(canonical(block), "utf8") > CLIENT_META_MAX_CANONICAL_BYTES) {
|
|
69
|
+
throw new Error("client_metadata exceeds 4 KiB canonical");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Return a new manifest carrying client_metadata; the input manifest is untouched. */
|
|
73
|
+
export function attachClientMeta(manifest, entries) {
|
|
74
|
+
const block = { version: 1, entries: entries.map((e) => ({ ...e })) };
|
|
75
|
+
validateClientMeta(block);
|
|
76
|
+
return { ...manifest, client_metadata: block };
|
|
77
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fill linking (issue 98): attach real Hyperliquid fills to a simulation receipt.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript port of `perpbrain_read.sim.fill_link`. Same record, same bigint fixed-point
|
|
5
|
+
* arithmetic (18 decimals, truncating division), same canonical JSON, so a link record built
|
|
6
|
+
* by either SDK verifies in the other. Shared vectors: fixtures/fill_link/expected.json.
|
|
7
|
+
* Read-only: no keys, no order path, no network in this module.
|
|
8
|
+
*/
|
|
9
|
+
export declare const LINK_KIND = "perpbrain.execution-link";
|
|
10
|
+
export declare const LINK_VERSION = 1;
|
|
11
|
+
export type LinkSelector = "oid" | "hash" | "cloid";
|
|
12
|
+
export type LinkNetwork = "mainnet" | "testnet";
|
|
13
|
+
type Row = Record<string, unknown>;
|
|
14
|
+
export interface SimTrade {
|
|
15
|
+
market: string;
|
|
16
|
+
side: string;
|
|
17
|
+
price: string;
|
|
18
|
+
size: string;
|
|
19
|
+
fee_usd: string;
|
|
20
|
+
decision_time_ms: number;
|
|
21
|
+
trade_index: number;
|
|
22
|
+
}
|
|
23
|
+
export interface LinkInputs {
|
|
24
|
+
network: string;
|
|
25
|
+
user: string;
|
|
26
|
+
by: LinkSelector;
|
|
27
|
+
value: string;
|
|
28
|
+
receipt_sha256: string;
|
|
29
|
+
sim: SimTrade;
|
|
30
|
+
fills: Row[];
|
|
31
|
+
}
|
|
32
|
+
export interface LinkResult {
|
|
33
|
+
status: "LINKED" | "NO_FILLS" | "MISMATCHED_TRADE";
|
|
34
|
+
problems: string[];
|
|
35
|
+
fills: number;
|
|
36
|
+
oids: number[];
|
|
37
|
+
hashes: string[];
|
|
38
|
+
size: string;
|
|
39
|
+
avg_px: string;
|
|
40
|
+
fees_usdc: string;
|
|
41
|
+
first_time_ms: number | null;
|
|
42
|
+
last_time_ms: number | null;
|
|
43
|
+
sim_price: string;
|
|
44
|
+
sim_size: string;
|
|
45
|
+
sim_fee_usd: string;
|
|
46
|
+
fill_ratio: string;
|
|
47
|
+
slippage_vs_sim_bps: string;
|
|
48
|
+
fee_drag_usd: string;
|
|
49
|
+
time_to_first_fill_ms: number | null;
|
|
50
|
+
}
|
|
51
|
+
export interface BuiltLink {
|
|
52
|
+
record: Record<string, unknown>;
|
|
53
|
+
recordBytes: Buffer;
|
|
54
|
+
inputsBytes: Buffer;
|
|
55
|
+
}
|
|
56
|
+
export interface LinkVerify {
|
|
57
|
+
status: "VERIFIED" | "MISMATCH";
|
|
58
|
+
mismatches: string[];
|
|
59
|
+
}
|
|
60
|
+
/** The simulated trade `tradeIndex` (0 = entry) of a perpbrain.sim-receipt. */
|
|
61
|
+
export declare function simFromReceipt(receipt: unknown, tradeIndex?: number): SimTrade;
|
|
62
|
+
/** The selector value as stored: decimal oid, lowercase 0x hash or cloid. */
|
|
63
|
+
export declare function normaliseSelector(by: string, value: unknown): string;
|
|
64
|
+
/** Raw fill rows matching the selector, verbatim, oldest first. */
|
|
65
|
+
export declare function selectFills(rows: readonly Row[], by: string, value: unknown): Row[];
|
|
66
|
+
export declare function linkInputs(receipt: unknown, rows: readonly Row[], options: {
|
|
67
|
+
network: string;
|
|
68
|
+
user: string;
|
|
69
|
+
by: LinkSelector;
|
|
70
|
+
value: unknown;
|
|
71
|
+
tradeIndex?: number;
|
|
72
|
+
}): LinkInputs;
|
|
73
|
+
export declare function computeLink(inputs: LinkInputs): LinkResult;
|
|
74
|
+
export declare function buildLink(inputs: LinkInputs): BuiltLink;
|
|
75
|
+
/** Re-hash the inputs, rerun the comparison and, given the receipt, check the binding. */
|
|
76
|
+
export declare function verifyLink(record: Record<string, unknown>, inputsBytes: Uint8Array, receipt?: unknown): LinkVerify;
|
|
77
|
+
export {};
|