@perpbrain/sdk 0.1.4 → 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.
@@ -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,180 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MIN_SAMPLE = exports.CALIBRATION_STATEMENT = exports.CALIBRATION_VERSION = exports.CALIBRATION_KIND = void 0;
4
+ exports.computeReport = computeReport;
5
+ exports.buildReport = buildReport;
6
+ exports.verifyReport = verifyReport;
7
+ /**
8
+ * Calibration report (feedback loop), per pb-specs-28nov.md section 4.
9
+ *
10
+ * TypeScript port of `perpbrain_read.sim.calibration` (report version 2). Read-only:
11
+ * aggregates candidate link records into slippage statistics for a reviewer. Nothing here
12
+ * proves a link is genuine. A candidate is RECOMPUTED (it carries its link_inputs and the link
13
+ * hash and result reproduce from them: integrity only) or UNVERIFIED (only the self-supplied
14
+ * hash was checked). Only RECOMPUTED candidates can meet the sample gate. Duplicates (same link
15
+ * hash, or the same fills under a different link) count once. Arithmetic is integer fixed point
16
+ * (1e18), truncating toward zero, identical to the Python side. No automatic promotion.
17
+ */
18
+ const node_crypto_1 = require("node:crypto");
19
+ const receipt_ts_1 = require("./receipt.js");
20
+ const fillLink_ts_1 = require("./fillLink.js");
21
+ const fixedDecimal_ts_1 = require("./fixedDecimal.js");
22
+ exports.CALIBRATION_KIND = "perpbrain.calibration-report";
23
+ exports.CALIBRATION_VERSION = 2;
24
+ exports.CALIBRATION_STATEMENT = "reproducible from the supplied inputs; links are candidates, not venue-authenticated";
25
+ /** Proposed minimum sample gate, not statistical sufficiency. */
26
+ exports.MIN_SAMPLE = 10;
27
+ function sha256Hex(raw) {
28
+ return (0, node_crypto_1.createHash)("sha256").update(raw).digest("hex");
29
+ }
30
+ function recomputed(link, cand) {
31
+ const linkIn = cand.link_inputs;
32
+ if (linkIn === null || typeof linkIn !== "object" || Array.isArray(linkIn))
33
+ return false;
34
+ try {
35
+ if (sha256Hex((0, receipt_ts_1.canonical)(linkIn)) !== link.inputs_sha256)
36
+ return false;
37
+ return (0, receipt_ts_1.canonical)((0, fillLink_ts_1.computeLink)(linkIn)) === (0, receipt_ts_1.canonical)(link.result);
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
43
+ function fillsKey(link) {
44
+ const res = (link.result ?? {});
45
+ return (0, receipt_ts_1.canonical)({ oids: res.oids ?? null, hashes: res.hashes ?? null });
46
+ }
47
+ function stats(values, basis) {
48
+ const vals = [...values].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
49
+ const n = vals.length;
50
+ if (n === 0)
51
+ return null;
52
+ const mid = Math.floor(n / 2);
53
+ const median = n % 2 ? vals[mid] : (0, fixedDecimal_ts_1.tdiv)(vals[mid - 1] + vals[mid], 2n);
54
+ const sum = vals.reduce((a, b) => a + b, 0n);
55
+ return {
56
+ basis,
57
+ n,
58
+ mean_bps: (0, fixedDecimal_ts_1.formatFixed)((0, fixedDecimal_ts_1.tdiv)(sum, BigInt(n))),
59
+ median_bps: (0, fixedDecimal_ts_1.formatFixed)(median),
60
+ p90_bps: (0, fixedDecimal_ts_1.formatFixed)(vals[Math.floor((9 * (n - 1)) / 10)]),
61
+ };
62
+ }
63
+ function computeReport(inputs) {
64
+ const excluded = [];
65
+ const valid = [];
66
+ inputs.candidates.forEach((cand, idx) => {
67
+ const sha = cand.link_sha256;
68
+ const link = cand.link_record;
69
+ const drop = (reason) => excluded.push({ link_sha256: sha, reason });
70
+ if (link.kind !== "perpbrain.execution-link")
71
+ return drop("WRONG_KIND");
72
+ if (sha256Hex((0, receipt_ts_1.canonical)(link)) !== sha)
73
+ return drop("HASH_MISMATCH");
74
+ const res = (link.result ?? {});
75
+ if (res.status !== "LINKED") {
76
+ return drop(typeof res.status === "string" && res.status ? res.status : "NOT_LINKED");
77
+ }
78
+ if (cand.sim_defaults_version !== inputs.sim_defaults_version) {
79
+ return drop("DEFAULTS_VERSION_MISMATCH");
80
+ }
81
+ valid.push({ idx, cand, ok: recomputed(link, cand) });
82
+ });
83
+ // Duplicate groups keep a recomputed candidate over an unrecomputed one, then the earliest.
84
+ const seenHash = new Set();
85
+ const seenFills = new Set();
86
+ const kept = [];
87
+ const order = [...valid].sort((x, y) => Number(!x.ok) - Number(!y.ok) || x.idx - y.idx);
88
+ for (const v of order) {
89
+ const sha = v.cand.link_sha256;
90
+ const key = fillsKey(v.cand.link_record);
91
+ if (seenHash.has(sha)) {
92
+ excluded.push({ link_sha256: sha, reason: "DUPLICATE_LINK" });
93
+ continue;
94
+ }
95
+ if (seenFills.has(key)) {
96
+ excluded.push({ link_sha256: sha, reason: "DUPLICATE_FILLS" });
97
+ continue;
98
+ }
99
+ seenHash.add(sha);
100
+ seenFills.add(key);
101
+ kept.push(v);
102
+ }
103
+ kept.sort((x, y) => x.idx - y.idx);
104
+ const included = kept.map((k) => k.cand);
105
+ const groups = new Map();
106
+ for (const { cand, ok } of kept) {
107
+ const group = String(cand.group ?? "unknown");
108
+ const res = cand.link_record.result;
109
+ const value = (0, fixedDecimal_ts_1.parseStrictFixed)(res.slippage_vs_sim_bps, "slippage_vs_sim_bps");
110
+ const items = groups.get(group) ?? [];
111
+ items.push({ value, ok });
112
+ groups.set(group, items);
113
+ }
114
+ const outGroups = {};
115
+ for (const group of [...groups.keys()].sort()) {
116
+ const items = groups.get(group);
117
+ const recVals = items.filter((i) => i.ok).map((i) => i.value);
118
+ outGroups[group] = {
119
+ candidate_count: items.length,
120
+ recomputed_count: recVals.length,
121
+ unrecomputed_count: items.length - recVals.length,
122
+ sufficiency: recVals.length >= exports.MIN_SAMPLE ? "MIN_SAMPLE_MET" : "INSUFFICIENT_DATA",
123
+ candidate_stats: stats(items.map((i) => i.value), "ALL_DEDUPED_CANDIDATES_UNVERIFIED"),
124
+ recomputed_stats: stats(recVals, "RECOMPUTED_ONLY"),
125
+ };
126
+ }
127
+ return {
128
+ window: inputs.window,
129
+ sim_defaults_version: inputs.sim_defaults_version,
130
+ included: included.map((c) => c.link_sha256),
131
+ excluded,
132
+ groups: outGroups,
133
+ proposal: null,
134
+ note: "candidate statistics for reviewer judgment; no automatic promotion",
135
+ };
136
+ }
137
+ function buildReport(inputs) {
138
+ const raw = (0, receipt_ts_1.canonical)(inputs);
139
+ const result = computeReport(inputs);
140
+ const record = {
141
+ kind: exports.CALIBRATION_KIND,
142
+ version: exports.CALIBRATION_VERSION,
143
+ statement: exports.CALIBRATION_STATEMENT,
144
+ inputs_sha256: sha256Hex(raw),
145
+ result,
146
+ result_sha256: sha256Hex((0, receipt_ts_1.canonical)(result)),
147
+ };
148
+ return {
149
+ record,
150
+ recordBytes: Buffer.from((0, receipt_ts_1.canonical)(record) + "\n", "utf8"),
151
+ inputsBytes: Buffer.from(raw + "\n", "utf8"),
152
+ };
153
+ }
154
+ function verifyReport(record, inputsBytes) {
155
+ const problems = [];
156
+ const body = (record ?? null);
157
+ if (body === null || typeof body !== "object") {
158
+ return { status: "MISMATCH", mismatches: ["record must be an object"] };
159
+ }
160
+ if (body.kind !== exports.CALIBRATION_KIND)
161
+ problems.push("kind");
162
+ if (body.version !== exports.CALIBRATION_VERSION)
163
+ problems.push("version");
164
+ let result;
165
+ try {
166
+ const inputs = JSON.parse(inputsBytes.toString("utf8"));
167
+ if (sha256Hex((0, receipt_ts_1.canonical)(inputs)) !== body.inputs_sha256)
168
+ problems.push("inputs_sha256");
169
+ result = computeReport(inputs);
170
+ }
171
+ catch (exc) {
172
+ problems.push(`inputs: ${exc instanceof Error ? exc.message : String(exc)}`);
173
+ return { status: "MISMATCH", mismatches: problems };
174
+ }
175
+ if ((0, receipt_ts_1.canonical)(body.result) !== (0, receipt_ts_1.canonical)(result))
176
+ problems.push("result");
177
+ if (body.result_sha256 !== sha256Hex((0, receipt_ts_1.canonical)(result)))
178
+ problems.push("result_sha256");
179
+ return { status: problems.length ? "MISMATCH" : "VERIFIED", mismatches: problems };
180
+ }
@@ -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,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CLIENT_META_ALLOWED_KEYS = exports.CLIENT_META_MAX_CANONICAL_BYTES = void 0;
4
+ exports.makeEntry = makeEntry;
5
+ exports.validateClientMeta = validateClientMeta;
6
+ exports.attachClientMeta = attachClientMeta;
7
+ /**
8
+ * Optional hashed client metadata on receipt manifests (issue 97).
9
+ *
10
+ * TypeScript port of `perpbrain_read.sim.client_meta`. The block lives in the MANIFEST, not
11
+ * the receipt body: the receipt already pins manifest_sha256 and the shipped verifier
12
+ * re-hashes the manifest bytes, so a manifest block is bound end-to-end with no
13
+ * receipt-schema or verifier change. Keys come from a fixed allow-list (no free-text key can
14
+ * carry strategy detail). Values are SHA-256 hex digests only. A digest hides the artifact only
15
+ * if the artifact is high-entropy: a short or guessable input can be recovered by hashing
16
+ * guesses, so salt anything small before hashing. This is hashing, not confidentiality. Absent
17
+ * and null are equivalent and produce byte-identical manifests. Canonical encoding is capped
18
+ * at 4 KiB.
19
+ */
20
+ const node_crypto_1 = require("node:crypto");
21
+ const receipt_ts_1 = require("./receipt.js");
22
+ exports.CLIENT_META_MAX_CANONICAL_BYTES = 4096;
23
+ exports.CLIENT_META_ALLOWED_KEYS = new Set([
24
+ "offvenue_leg_sha256",
25
+ "note_sha256",
26
+ "strategy_sha256",
27
+ "config_sha256",
28
+ "dataset_sha256",
29
+ "model_sha256",
30
+ "code_sha256",
31
+ ]);
32
+ const HEX64 = /^[0-9a-f]{64}$/;
33
+ function sha256Hex(raw) {
34
+ return (0, node_crypto_1.createHash)("sha256").update(raw).digest("hex");
35
+ }
36
+ /** One opaque entry: the SHA-256 of an off-venue artifact, never the artifact. */
37
+ function makeEntry(key, payload) {
38
+ if (!exports.CLIENT_META_ALLOWED_KEYS.has(key))
39
+ throw new Error("key is not in the allow-list");
40
+ return { key, value: sha256Hex(payload) };
41
+ }
42
+ /** Shape and size checks; the verifier ignores-but-binds the entries themselves. */
43
+ function validateClientMeta(block) {
44
+ if (block === null || typeof block !== "object") {
45
+ throw new Error("client_metadata version must be 1");
46
+ }
47
+ const body = block;
48
+ if (body.version !== 1)
49
+ throw new Error("client_metadata version must be 1");
50
+ if (Object.keys(body).sort().join(",") !== "entries,version") {
51
+ throw new Error("client_metadata has unknown or missing fields");
52
+ }
53
+ if (!Array.isArray(body.entries))
54
+ throw new Error("client_metadata.entries must be a list");
55
+ const seen = new Set();
56
+ for (const entry of body.entries) {
57
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
58
+ throw new Error("entry must be an object");
59
+ }
60
+ if (Object.keys(entry).sort().join(",") !== "key,value") {
61
+ throw new Error("entry must have exactly key and value");
62
+ }
63
+ const { key, value } = entry;
64
+ if (typeof key !== "string" || !exports.CLIENT_META_ALLOWED_KEYS.has(key)) {
65
+ throw new Error("key is not in the allow-list");
66
+ }
67
+ if (seen.has(key))
68
+ throw new Error("duplicate key");
69
+ seen.add(key);
70
+ if (typeof value !== "string" || !HEX64.test(value)) {
71
+ throw new Error("value must be a lowercase sha256 hex digest");
72
+ }
73
+ }
74
+ if (Buffer.byteLength((0, receipt_ts_1.canonical)(block), "utf8") > exports.CLIENT_META_MAX_CANONICAL_BYTES) {
75
+ throw new Error("client_metadata exceeds 4 KiB canonical");
76
+ }
77
+ }
78
+ /** Return a new manifest carrying client_metadata; the input manifest is untouched. */
79
+ function attachClientMeta(manifest, entries) {
80
+ const block = { version: 1, entries: entries.map((e) => ({ ...e })) };
81
+ validateClientMeta(block);
82
+ return { ...manifest, client_metadata: block };
83
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Strict 18-decimal fixed-point helpers shared by the holding and calibration ports.
3
+ * Same grammar as the Python side: ASCII digits, optional leading minus, at most 18 fraction
4
+ * digits. No exponent, no spaces, no underscores, no NaN or Infinity. Division truncates
5
+ * toward zero, like Python `fill_link.tdiv`.
6
+ */
7
+ export declare const SCALE: bigint;
8
+ export declare function isStrictDecimal(text: unknown): text is string;
9
+ export declare function parseStrictFixed(text: unknown, what: string): bigint;
10
+ export declare function formatFixed(value: bigint): string;
11
+ export declare function tdiv(numerator: bigint, denominator: bigint): bigint;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SCALE = void 0;
4
+ exports.isStrictDecimal = isStrictDecimal;
5
+ exports.parseStrictFixed = parseStrictFixed;
6
+ exports.formatFixed = formatFixed;
7
+ exports.tdiv = tdiv;
8
+ /**
9
+ * Strict 18-decimal fixed-point helpers shared by the holding and calibration ports.
10
+ * Same grammar as the Python side: ASCII digits, optional leading minus, at most 18 fraction
11
+ * digits. No exponent, no spaces, no underscores, no NaN or Infinity. Division truncates
12
+ * toward zero, like Python `fill_link.tdiv`.
13
+ */
14
+ exports.SCALE = 10n ** 18n;
15
+ const STRICT = /^-?[0-9]+(\.[0-9]{1,18})?$/;
16
+ function isStrictDecimal(text) {
17
+ return typeof text === "string" && STRICT.test(text);
18
+ }
19
+ function parseStrictFixed(text, what) {
20
+ if (!isStrictDecimal(text))
21
+ throw new Error(`${what} must be a plain decimal string`);
22
+ const negative = text.startsWith("-");
23
+ const [whole, frac = ""] = (negative ? text.slice(1) : text).split(".");
24
+ const value = BigInt(whole) * exports.SCALE + BigInt((frac + "0".repeat(18)).slice(0, 18));
25
+ return negative ? -value : value;
26
+ }
27
+ function formatFixed(value) {
28
+ const negative = value < 0n;
29
+ const abs = negative ? -value : value;
30
+ const whole = abs / exports.SCALE;
31
+ const frac = (abs % exports.SCALE).toString().padStart(18, "0").replace(/0+$/, "");
32
+ const text = frac ? `${whole}.${frac}` : `${whole}`;
33
+ return negative && text !== "0" ? `-${text}` : text;
34
+ }
35
+ function tdiv(numerator, denominator) {
36
+ if (denominator === 0n)
37
+ throw new Error("division by zero");
38
+ return numerator / denominator; // BigInt division truncates toward zero
39
+ }
@@ -106,6 +106,9 @@ function num(value, what) {
106
106
  if (typeof value !== "number" || !Number.isInteger(value)) {
107
107
  throw new Error(`${what} must be an integer`);
108
108
  }
109
+ if (!Number.isSafeInteger(value)) {
110
+ throw new Error(`${what} exceeds 2^53-1`);
111
+ }
109
112
  return value;
110
113
  }
111
114
  function fundingInWindow(rows, startMs, endMs) {
@@ -193,6 +196,35 @@ function canonicalAscii(value) {
193
196
  function sha256(data) {
194
197
  return (0, node_crypto_1.createHash)("sha256").update(data).digest("hex");
195
198
  }
199
+ /**
200
+ * The header copies account, coin, source, window and label out of the inputs. Bind them to
201
+ * the hashed inputs so an edited header cannot still read VERIFIED. This does not authenticate
202
+ * the inputs themselves. Mirrors `_header_mismatches` in the Python verifier.
203
+ */
204
+ function headerMismatches(body, inputs) {
205
+ const found = [];
206
+ for (const key of ["account", "coin", "source"]) {
207
+ if (body[key] !== inputs[key]) {
208
+ found.push(key);
209
+ }
210
+ }
211
+ const window = body.window;
212
+ if (typeof window !== "object" ||
213
+ window === null ||
214
+ Object.keys(window).length !== 2 ||
215
+ window.start_ms !== inputs.start_ms ||
216
+ window.end_ms !== inputs.end_ms) {
217
+ found.push("window");
218
+ }
219
+ const network = inputs.network;
220
+ if (network !== "mainnet" && network !== "testnet") {
221
+ found.push("network");
222
+ }
223
+ else if (body.label !== network.toUpperCase()) {
224
+ found.push("label");
225
+ }
226
+ return found;
227
+ }
196
228
  function verifyReconReceipt(receipt, inputsBytes) {
197
229
  const body = typeof receipt === "object" && receipt !== null && !Array.isArray(receipt)
198
230
  ? receipt
@@ -214,6 +246,7 @@ function verifyReconReceipt(receipt, inputsBytes) {
214
246
  try {
215
247
  const inputs = JSON.parse(Buffer.from(inputsBytes).toString("utf8"));
216
248
  result = reconcile(inputs);
249
+ problems.push(...headerMismatches(body, inputs));
217
250
  }
218
251
  catch (error) {
219
252
  return { status: "MISMATCH", mismatches: [...problems, `inputs: ${error.message}`] };
@@ -0,0 +1,48 @@
1
+ import { type LinkSelector } from "./fillLink.ts";
2
+ export declare const HOLDING_KIND = "perpbrain.holding-receipt";
3
+ export declare const HOLDING_VERSION = 3;
4
+ export declare const HOLDING_STATEMENT = "reproducible from the supplied inputs; not authenticated to the venue or account";
5
+ export declare const VERIFY_SCOPE = "ARITHMETIC_AND_HASHES_REPRODUCED_FROM_SUPPLIED_INPUTS; authenticity of fills and funding rows is not established";
6
+ export declare const FUNDING_SCOPE = "ACCOUNT_COIN_SUM_NOT_POSITION_ATTRIBUTED";
7
+ export declare const FUNDING_COVERAGE = "UNKNOWN";
8
+ type Row = Record<string, unknown>;
9
+ export interface HoldingLeg {
10
+ by: LinkSelector;
11
+ value: string;
12
+ trade_index: number;
13
+ }
14
+ export interface HoldingInputs {
15
+ account: string;
16
+ network: string;
17
+ coin: string;
18
+ start_ms: number;
19
+ end_ms: number;
20
+ entry: HoldingLeg;
21
+ exit: HoldingLeg | null;
22
+ funding_rows: Row[];
23
+ }
24
+ export interface BuiltHolding {
25
+ record: Record<string, unknown>;
26
+ recordBytes: Buffer;
27
+ inputsBytes: Buffer;
28
+ }
29
+ export interface HoldingVerify {
30
+ status: "VERIFIED" | "MISMATCH" | "UNCHECKED_PARTIAL";
31
+ mismatches: string[];
32
+ unchecked?: string[];
33
+ scope?: string;
34
+ upstream_receipt_verification?: string;
35
+ }
36
+ export declare function computeHolding(inputs: HoldingInputs, receipt: Row, allFills: Row[], receiptVerified?: boolean): Row;
37
+ /** receiptVerified is true only when the caller ran the upstream receipt verifier. The default
38
+ * is false: the record is capped at PROVISIONAL with reason RECEIPT_NOT_VERIFIED. */
39
+ export declare function buildHolding(inputs: HoldingInputs, receipt: Row, allFills: Row[], receiptVerified?: boolean): BuiltHolding;
40
+ /** VERIFIED only when the receipt is supplied and every hash and the result reproduce.
41
+ * receiptVerified is the caller's assertion that it ran an upstream receipt verifier; this
42
+ * function cannot check it, and the TS side has no CLI path that sets it (default false).
43
+ * VERIFIED does not mean the receipt is authentic. The record field is outside
44
+ * result_sha256, but the hashed result carries RECEIPT_NOT_VERIFIED when it is not set.
45
+ * Without a receipt only kind, version and the inputs hash can be checked: the answer is
46
+ * UNCHECKED_PARTIAL, never VERIFIED. */
47
+ export declare function verifyHolding(record: unknown, inputsBytes: Buffer, allFills: Row[], receipt?: Row, receiptVerified?: boolean): HoldingVerify;
48
+ export {};