@perpbrain/sdk 0.1.4 → 0.3.0

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
+ }
@@ -8,6 +8,7 @@
8
8
  */
9
9
  export declare const LINK_KIND = "perpbrain.execution-link";
10
10
  export declare const LINK_VERSION = 1;
11
+ export declare const LINK_VERSION_V2 = 2;
11
12
  export type LinkSelector = "oid" | "hash" | "cloid";
12
13
  export type LinkNetwork = "mainnet" | "testnet";
13
14
  type Row = Record<string, unknown>;
@@ -28,6 +29,8 @@ export interface LinkInputs {
28
29
  receipt_sha256: string;
29
30
  sim: SimTrade;
30
31
  fills: Row[];
32
+ policy?: unknown;
33
+ bounds?: unknown;
31
34
  }
32
35
  export interface LinkResult {
33
36
  status: "LINKED" | "NO_FILLS" | "MISMATCHED_TRADE";
@@ -69,9 +72,26 @@ export declare function linkInputs(receipt: unknown, rows: readonly Row[], optio
69
72
  by: LinkSelector;
70
73
  value: unknown;
71
74
  tradeIndex?: number;
75
+ policy?: unknown;
72
76
  }): 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. */
77
+ /** v2 inputs are canonical in both SDKs only when every number is a JSON integer within the
78
+ * double-safe range and every object key is ASCII. Anything else is refused, never coerced. */
79
+ export declare function checkV2Value(value: unknown): void;
80
+ /** Float spellings (1.0, 1e3) parse differently across languages: refused in the raw bytes. */
81
+ export declare function checkV2Text(raw: string): void;
82
+ /** Structural facts taken from the receipt: the smallest positive bar gap and where the decision
83
+ * time came from ("bar", "book", or "unknown" when timed bars exist but the decision bar is not). */
84
+ export declare function receiptBounds(receipt: unknown): {
85
+ bar_interval_ms: number | null;
86
+ time_field: string;
87
+ };
88
+ /** v1 inputs (no `policy` key) give the v1 result unchanged and malformed rows throw, as in 0.2.1.
89
+ * v2 inputs add `correspondence`; malformed rows give a structured INVALID_INPUT result.
90
+ * `bound` is true only when the caller verified the inputs against the receipt. */
91
+ export declare function computeLink(inputs: LinkInputs, bound?: boolean): LinkResult & Record<string, unknown>;
92
+ /** Without `receipt` a v2 link is built unbound: it can never be positive. */
93
+ export declare function buildLink(inputs: LinkInputs, receipt?: unknown): BuiltLink;
94
+ /** Re-hash the inputs, rerun the comparison and, given the receipt, check the binding. A v2
95
+ * record that claims a receipt-bound decision time needs the receipt to verify. */
76
96
  export declare function verifyLink(record: Record<string, unknown>, inputsBytes: Uint8Array, receipt?: unknown): LinkVerify;
77
97
  export {};