@perpbrain/sdk 0.1.3 → 0.1.4

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,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 {};
@@ -0,0 +1,328 @@
1
+ "use strict";
2
+ /**
3
+ * Fill linking (issue 98): attach real Hyperliquid fills to a simulation receipt.
4
+ *
5
+ * TypeScript port of `perpbrain_read.sim.fill_link`. Same record, same bigint fixed-point
6
+ * arithmetic (18 decimals, truncating division), same canonical JSON, so a link record built
7
+ * by either SDK verifies in the other. Shared vectors: fixtures/fill_link/expected.json.
8
+ * Read-only: no keys, no order path, no network in this module.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.LINK_VERSION = exports.LINK_KIND = void 0;
12
+ exports.simFromReceipt = simFromReceipt;
13
+ exports.normaliseSelector = normaliseSelector;
14
+ exports.selectFills = selectFills;
15
+ exports.linkInputs = linkInputs;
16
+ exports.computeLink = computeLink;
17
+ exports.buildLink = buildLink;
18
+ exports.verifyLink = verifyLink;
19
+ const node_crypto_1 = require("node:crypto");
20
+ const receipt_ts_1 = require("./receipt.js");
21
+ const fees_ts_1 = require("./vendor/fees.js");
22
+ exports.LINK_KIND = "perpbrain.execution-link";
23
+ exports.LINK_VERSION = 1;
24
+ const STATEMENT = "verified and reproducible";
25
+ const SCALE = 10n ** 18n;
26
+ const HASH = /^0x[0-9a-f]{64}$/;
27
+ const ZERO_HASH = `0x${"0".repeat(64)}`;
28
+ const CLOID = /^0x[0-9a-f]{32}$/;
29
+ const ADDRESS = /^0x[0-9a-f]{40}$/;
30
+ function sha256(text) {
31
+ return (0, node_crypto_1.createHash)("sha256").update(text).digest("hex");
32
+ }
33
+ function obj(value) {
34
+ return typeof value === "object" && value !== null && !Array.isArray(value)
35
+ ? value
36
+ : null;
37
+ }
38
+ function int(value) {
39
+ if (typeof value !== "number" || !Number.isInteger(value)) {
40
+ throw new Error("fill time and tid must be integers");
41
+ }
42
+ return value;
43
+ }
44
+ function text(value) {
45
+ return typeof value === "string" ? value : "";
46
+ }
47
+ function fixed(value) {
48
+ if (typeof value !== "string") {
49
+ throw new Error("decimal required");
50
+ }
51
+ return (0, fees_ts_1.parseDecimal)(value);
52
+ }
53
+ function tdiv(n, d) {
54
+ if (d === 0n) {
55
+ throw new Error("division by zero");
56
+ }
57
+ return n / d; // bigint division truncates toward zero, like the Python tdiv
58
+ }
59
+ /** The simulated trade `tradeIndex` (0 = entry) of a perpbrain.sim-receipt. */
60
+ function simFromReceipt(receipt, tradeIndex = 0) {
61
+ const body = obj(receipt);
62
+ if (body === null || body.kind !== "perpbrain.sim-receipt") {
63
+ throw new Error("not a perpbrain.sim-receipt");
64
+ }
65
+ const result = obj(body.result);
66
+ const inputs = obj(body.inputs);
67
+ if (result === null || inputs === null) {
68
+ throw new Error("receipt has no result or inputs");
69
+ }
70
+ const fills = result.fills;
71
+ if (!Array.isArray(fills) || tradeIndex < 0 || tradeIndex >= fills.length) {
72
+ throw new Error(`receipt has no simulated trade ${tradeIndex}`);
73
+ }
74
+ const trade = obj(fills[tradeIndex]);
75
+ if (trade === null) {
76
+ throw new Error("simulated trade must be an object");
77
+ }
78
+ const decision = obj(inputs.decision);
79
+ const bars = inputs.bars;
80
+ if (decision === null || !Array.isArray(bars)) {
81
+ throw new Error("receipt inputs have no decision or bars");
82
+ }
83
+ const index = decision.bar_index;
84
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= bars.length) {
85
+ throw new Error("decision bar_index is out of range");
86
+ }
87
+ let when = obj(bars[index])?.time_ms;
88
+ if (typeof when !== "number" || !Number.isInteger(when)) {
89
+ // Paper receipts use a flat bar without a time; the live book time is the decision time.
90
+ when = obj(inputs.book)?.time_ms;
91
+ }
92
+ if (typeof when !== "number" || !Number.isInteger(when)) {
93
+ throw new Error("decision bar has no time_ms");
94
+ }
95
+ const side = trade.side;
96
+ if (side !== "buy" && side !== "sell") {
97
+ throw new Error("simulated side must be buy or sell");
98
+ }
99
+ const market = "market" in result ? result.market : inputs.market;
100
+ if (typeof market !== "string") {
101
+ throw new Error("receipt has no market");
102
+ }
103
+ for (const key of ["price", "size", "fee"]) {
104
+ fixed(trade[key]);
105
+ }
106
+ return {
107
+ market,
108
+ side,
109
+ price: trade.price,
110
+ size: trade.size,
111
+ fee_usd: trade.fee,
112
+ decision_time_ms: when,
113
+ trade_index: tradeIndex,
114
+ };
115
+ }
116
+ /** The selector value as stored: decimal oid, lowercase 0x hash or cloid. */
117
+ function normaliseSelector(by, value) {
118
+ const raw = String(value).trim();
119
+ if (by === "oid") {
120
+ if (!/^\d{1,20}$/.test(raw)) {
121
+ throw new Error("oid must be a non-negative integer");
122
+ }
123
+ return BigInt(raw).toString();
124
+ }
125
+ const lowered = raw.toLowerCase();
126
+ if (by === "hash") {
127
+ if (!HASH.test(lowered)) {
128
+ throw new Error("fill hash must be 0x followed by 64 hex digits");
129
+ }
130
+ if (lowered === ZERO_HASH) {
131
+ throw new Error("the all-zero fill hash is not unique; link by oid instead");
132
+ }
133
+ return lowered;
134
+ }
135
+ if (by === "cloid") {
136
+ if (!CLOID.test(lowered)) {
137
+ throw new Error("cloid must be 0x followed by 32 hex digits");
138
+ }
139
+ return lowered;
140
+ }
141
+ throw new Error("link by oid, hash or cloid");
142
+ }
143
+ function matches(row, by, value) {
144
+ if (by === "oid") {
145
+ return typeof row.oid === "number" && Number.isInteger(row.oid) && String(row.oid) === value;
146
+ }
147
+ if (by === "hash") {
148
+ return text(row.hash).toLowerCase() === value;
149
+ }
150
+ return text(row.cloid).toLowerCase() === value;
151
+ }
152
+ /** Raw fill rows matching the selector, verbatim, oldest first. */
153
+ function selectFills(rows, by, value) {
154
+ const key = normaliseSelector(by, value);
155
+ const picked = rows.filter((r) => matches(r, by, key)).map((r) => ({ ...r }));
156
+ return picked.sort((a, b) => int(a.time) - int(b.time) || int(a.tid) - int(b.tid));
157
+ }
158
+ function linkInputs(receipt, rows, options) {
159
+ if (options.network !== "mainnet" && options.network !== "testnet") {
160
+ throw new Error("network must be mainnet or testnet");
161
+ }
162
+ const account = options.user.toLowerCase();
163
+ if (!ADDRESS.test(account)) {
164
+ throw new Error("user must be a 0x-prefixed 20-byte address");
165
+ }
166
+ return {
167
+ network: options.network,
168
+ user: account,
169
+ by: options.by,
170
+ value: normaliseSelector(options.by, options.value),
171
+ receipt_sha256: sha256((0, receipt_ts_1.canonical)(receipt)),
172
+ sim: simFromReceipt(receipt, options.tradeIndex ?? 0),
173
+ fills: selectFills(rows, options.by, options.value),
174
+ };
175
+ }
176
+ function computeLink(inputs) {
177
+ const sim = inputs.sim;
178
+ const by = inputs.by;
179
+ const value = normaliseSelector(by, inputs.value);
180
+ const rows = inputs.fills;
181
+ let problems = [];
182
+ if (rows.some((r) => !matches(r, by, value))) {
183
+ problems.push("a fill does not match the selector");
184
+ }
185
+ let size = 0n;
186
+ let notional = 0n;
187
+ let fees = 0n;
188
+ let first = null;
189
+ let last = null;
190
+ const oids = [];
191
+ const hashes = [];
192
+ const sideHl = sim.side === "buy" ? "B" : "A";
193
+ for (const row of rows) {
194
+ const sz = fixed(row.sz);
195
+ const px = fixed(row.px);
196
+ size += sz;
197
+ notional += tdiv(sz * px, SCALE);
198
+ if (row.feeToken === undefined || row.feeToken === null || row.feeToken === "USDC") {
199
+ fees += fixed(row.fee);
200
+ }
201
+ const t = int(row.time);
202
+ first = first === null ? t : Math.min(first, t);
203
+ last = last === null ? t : Math.max(last, t);
204
+ const oid = int(row.oid);
205
+ if (!oids.includes(oid)) {
206
+ oids.push(oid);
207
+ }
208
+ const h = text(row.hash).toLowerCase();
209
+ if (!hashes.includes(h)) {
210
+ hashes.push(h);
211
+ }
212
+ const coin = text(row.coin);
213
+ if (coin !== sim.market) {
214
+ problems.push(`fill coin ${coin || "?"} is not the simulated ${sim.market}`);
215
+ }
216
+ const side = text(row.side);
217
+ if (side !== sideHl) {
218
+ problems.push(`fill side ${side || "?"} is not the simulated ${sim.side}`);
219
+ }
220
+ }
221
+ const simPx = (0, fees_ts_1.parseDecimal)(sim.price);
222
+ const simSz = (0, fees_ts_1.parseDecimal)(sim.size);
223
+ const simFee = (0, fees_ts_1.parseDecimal)(sim.fee_usd);
224
+ const avg = size !== 0n ? tdiv(notional * SCALE, size) : 0n;
225
+ const diff = sim.side === "buy" ? avg - simPx : simPx - avg;
226
+ const bps = size !== 0n && simPx !== 0n ? tdiv(diff * 10000n * SCALE, simPx) : 0n;
227
+ const ratio = simSz !== 0n ? tdiv(size * SCALE, simSz) : 0n;
228
+ problems = [...new Set(problems)];
229
+ const status = rows.length === 0 ? "NO_FILLS" : problems.length > 0 ? "MISMATCHED_TRADE" : "LINKED";
230
+ return {
231
+ status,
232
+ problems,
233
+ fills: rows.length,
234
+ oids,
235
+ hashes,
236
+ size: (0, fees_ts_1.formatDecimal)(size),
237
+ avg_px: (0, fees_ts_1.formatDecimal)(avg),
238
+ fees_usdc: (0, fees_ts_1.formatDecimal)(fees),
239
+ first_time_ms: first,
240
+ last_time_ms: last,
241
+ sim_price: sim.price,
242
+ sim_size: sim.size,
243
+ sim_fee_usd: sim.fee_usd,
244
+ fill_ratio: (0, fees_ts_1.formatDecimal)(ratio),
245
+ slippage_vs_sim_bps: (0, fees_ts_1.formatDecimal)(bps),
246
+ fee_drag_usd: rows.length > 0 ? (0, fees_ts_1.formatDecimal)(fees - simFee) : "0",
247
+ time_to_first_fill_ms: first === null ? null : first - sim.decision_time_ms,
248
+ };
249
+ }
250
+ function buildLink(inputs) {
251
+ const raw = (0, receipt_ts_1.canonical)(inputs);
252
+ const result = computeLink(inputs);
253
+ const record = {
254
+ kind: exports.LINK_KIND,
255
+ version: exports.LINK_VERSION,
256
+ label: inputs.network === "mainnet" ? "MAINNET" : "TESTNET",
257
+ statement: STATEMENT,
258
+ receipt_sha256: inputs.receipt_sha256,
259
+ user: inputs.user,
260
+ selector: { by: inputs.by, value: inputs.value },
261
+ inputs_sha256: sha256(raw),
262
+ result,
263
+ result_sha256: sha256((0, receipt_ts_1.canonical)(result)),
264
+ };
265
+ return {
266
+ record,
267
+ recordBytes: Buffer.from(`${(0, receipt_ts_1.canonical)(record)}\n`, "utf8"),
268
+ inputsBytes: Buffer.from(`${raw}\n`, "utf8"),
269
+ };
270
+ }
271
+ /** Re-hash the inputs, rerun the comparison and, given the receipt, check the binding. */
272
+ function verifyLink(record, inputsBytes, receipt) {
273
+ const problems = [];
274
+ if (record.kind !== exports.LINK_KIND) {
275
+ problems.push("kind");
276
+ }
277
+ if (record.version !== exports.LINK_VERSION) {
278
+ problems.push("version");
279
+ }
280
+ let inputs;
281
+ let result;
282
+ try {
283
+ inputs = JSON.parse(Buffer.from(inputsBytes).toString("utf8"));
284
+ if (sha256((0, receipt_ts_1.canonical)(inputs)) !== record.inputs_sha256) {
285
+ problems.push("inputs_sha256");
286
+ }
287
+ result = computeLink(inputs);
288
+ }
289
+ catch (error) {
290
+ return {
291
+ status: "MISMATCH",
292
+ mismatches: [...problems, `inputs: ${error.message}`],
293
+ };
294
+ }
295
+ const label = inputs.network === "mainnet" ? "MAINNET" : "TESTNET";
296
+ if (record.label !== label) {
297
+ problems.push("label");
298
+ }
299
+ if (record.receipt_sha256 !== inputs.receipt_sha256) {
300
+ problems.push("receipt_sha256");
301
+ }
302
+ if ((0, receipt_ts_1.canonical)(record.selector) !== (0, receipt_ts_1.canonical)({ by: inputs.by, value: inputs.value })) {
303
+ problems.push("selector");
304
+ }
305
+ if ((0, receipt_ts_1.canonical)(record.result) !== (0, receipt_ts_1.canonical)(result)) {
306
+ problems.push("result");
307
+ }
308
+ if (record.result_sha256 !== sha256((0, receipt_ts_1.canonical)(result))) {
309
+ problems.push("result_sha256");
310
+ }
311
+ if (receipt !== undefined) {
312
+ if (sha256((0, receipt_ts_1.canonical)(receipt)) !== inputs.receipt_sha256) {
313
+ problems.push("receipt does not match receipt_sha256");
314
+ }
315
+ else {
316
+ try {
317
+ const sim = simFromReceipt(receipt, inputs.sim.trade_index);
318
+ if ((0, receipt_ts_1.canonical)(sim) !== (0, receipt_ts_1.canonical)(inputs.sim)) {
319
+ problems.push("sim trade differs from the receipt");
320
+ }
321
+ }
322
+ catch (error) {
323
+ problems.push(`receipt: ${error.message}`);
324
+ }
325
+ }
326
+ }
327
+ return { status: problems.length > 0 ? "MISMATCH" : "VERIFIED", mismatches: problems };
328
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Funding-reconciliation receipts (`perpbrain.funding-recon-receipt`), TypeScript port of
3
+ * `perpbrain_read.sim.funding_recon`: re-run the match of on-chain funding measurements against
4
+ * the venue's `userFunding` rows and check the receipt's hashes. No network, no keys.
5
+ *
6
+ * Decimal strings follow Python's `str(Decimal)` for the values these receipts carry
7
+ * (plain notation), as in the in-browser checker at perpbrain.com/verify.
8
+ */
9
+ export declare const RECON_KIND = "perpbrain.funding-recon-receipt";
10
+ export declare const RECON_VERSION = 1;
11
+ export interface ReconVerify {
12
+ status: "VERIFIED" | "MISMATCH";
13
+ mismatches: string[];
14
+ }
15
+ export declare function reconcile(inputs: Record<string, unknown>): Record<string, unknown>;
16
+ export declare function verifyReconReceipt(receipt: unknown, inputsBytes: Uint8Array): ReconVerify;
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ /**
3
+ * Funding-reconciliation receipts (`perpbrain.funding-recon-receipt`), TypeScript port of
4
+ * `perpbrain_read.sim.funding_recon`: re-run the match of on-chain funding measurements against
5
+ * the venue's `userFunding` rows and check the receipt's hashes. No network, no keys.
6
+ *
7
+ * Decimal strings follow Python's `str(Decimal)` for the values these receipts carry
8
+ * (plain notation), as in the in-browser checker at perpbrain.com/verify.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.RECON_VERSION = exports.RECON_KIND = void 0;
12
+ exports.reconcile = reconcile;
13
+ exports.verifyReconReceipt = verifyReconReceipt;
14
+ const node_crypto_1 = require("node:crypto");
15
+ exports.RECON_KIND = "perpbrain.funding-recon-receipt";
16
+ exports.RECON_VERSION = 1;
17
+ class Dec {
18
+ coeff;
19
+ exp;
20
+ constructor(coeff, exp) {
21
+ this.coeff = coeff;
22
+ this.exp = exp;
23
+ }
24
+ static from(value) {
25
+ if (value instanceof Dec) {
26
+ return value;
27
+ }
28
+ if (typeof value === "bigint") {
29
+ return new Dec(value, 0);
30
+ }
31
+ if (typeof value === "number" && Number.isInteger(value)) {
32
+ return new Dec(BigInt(value), 0);
33
+ }
34
+ const s = String(value).trim();
35
+ if (!/^-?\d+(\.\d+)?$/.test(s)) {
36
+ throw new Error(`decimal required: ${s}`);
37
+ }
38
+ const neg = s.startsWith("-");
39
+ const body = neg ? s.slice(1) : s;
40
+ const i = body.indexOf(".");
41
+ const digits = i === -1 ? body : body.slice(0, i) + body.slice(i + 1);
42
+ const exp = i === -1 ? 0 : -(body.length - i - 1);
43
+ return new Dec(BigInt(digits) * (neg ? -1n : 1n), exp);
44
+ }
45
+ align(other) {
46
+ if (this.exp === other.exp) {
47
+ return [this.coeff, other.coeff, this.exp];
48
+ }
49
+ if (this.exp < other.exp) {
50
+ return [this.coeff, other.coeff * 10n ** BigInt(other.exp - this.exp), this.exp];
51
+ }
52
+ return [this.coeff * 10n ** BigInt(this.exp - other.exp), other.coeff, other.exp];
53
+ }
54
+ add(other) {
55
+ const [a, b, e] = this.align(other);
56
+ return new Dec(a + b, e);
57
+ }
58
+ sub(other) {
59
+ const [a, b, e] = this.align(other);
60
+ return new Dec(a - b, e);
61
+ }
62
+ /** Exact division by 10^places with Python's ideal exponent (that of the dividend). */
63
+ divPow10(places) {
64
+ let c = this.coeff;
65
+ let e = this.exp - places;
66
+ while (e < this.exp && c % 10n === 0n) {
67
+ c /= 10n;
68
+ e += 1;
69
+ }
70
+ return new Dec(c, e);
71
+ }
72
+ abs() {
73
+ return this.coeff < 0n ? new Dec(-this.coeff, this.exp) : this;
74
+ }
75
+ cmp(other) {
76
+ const [a, b] = this.align(other);
77
+ return a < b ? -1 : a > b ? 1 : 0;
78
+ }
79
+ /** Python's str(Decimal): plain notation unless the exponent is positive or very small. */
80
+ toString() {
81
+ const neg = this.coeff < 0n;
82
+ let digits = (neg ? -this.coeff : this.coeff).toString();
83
+ const adjusted = this.exp + digits.length - 1;
84
+ let body;
85
+ if (this.exp <= 0 && adjusted >= -6) {
86
+ if (this.exp === 0) {
87
+ body = digits;
88
+ }
89
+ else {
90
+ const places = -this.exp;
91
+ if (digits.length <= places) {
92
+ digits = digits.padStart(places + 1, "0");
93
+ }
94
+ const i = digits.length - places;
95
+ body = `${digits.slice(0, i)}.${digits.slice(i)}`;
96
+ }
97
+ }
98
+ else {
99
+ const mantissa = digits.length > 1 ? `${digits[0]}.${digits.slice(1)}` : digits;
100
+ body = `${mantissa}E${adjusted > 0 ? "+" : ""}${adjusted}`;
101
+ }
102
+ return (neg ? "-" : "") + body;
103
+ }
104
+ }
105
+ function num(value, what) {
106
+ if (typeof value !== "number" || !Number.isInteger(value)) {
107
+ throw new Error(`${what} must be an integer`);
108
+ }
109
+ return value;
110
+ }
111
+ function fundingInWindow(rows, startMs, endMs) {
112
+ let total = Dec.from(0);
113
+ for (const row of rows) {
114
+ const t = num(row.time, "time");
115
+ if (startMs < t && t <= endMs) {
116
+ total = total.add(Dec.from(row.usdc));
117
+ }
118
+ }
119
+ return total;
120
+ }
121
+ function reconcile(inputs) {
122
+ const coin = inputs.coin;
123
+ const rows = (inputs.funding_rows ?? []).filter((r) => r.coin === coin);
124
+ const meas = [...(inputs.measurements ?? [])].sort((a, b) => num(a.time_ms, "time_ms") - num(b.time_ms, "time_ms") || num(a.block, "block") - num(b.block, "block"));
125
+ const tol = Dec.from(inputs.tolerance_usdc);
126
+ const startMs = num(inputs.start_ms, "start_ms");
127
+ const endMs = num(inputs.end_ms, "end_ms");
128
+ const windows = [];
129
+ let prev = startMs;
130
+ let inWindows = Dec.from(0);
131
+ let measuredTotal = Dec.from(0);
132
+ let differing = 0;
133
+ for (const m of meas) {
134
+ const t = num(m.time_ms, "time_ms");
135
+ if (t < prev) {
136
+ throw new Error("measurement before window start");
137
+ }
138
+ const venue = fundingInWindow(rows, prev, t);
139
+ const count = rows.filter((r) => prev < num(r.time, "time") && num(r.time, "time") <= t).length;
140
+ const measured = Dec.from(num(m.measured_micro, "measured_micro")).divPow10(6);
141
+ const diff = measured.sub(venue);
142
+ const status = diff.abs().cmp(tol) <= 0 ? "MATCH" : "DIFF";
143
+ if (status === "DIFF") {
144
+ differing += 1;
145
+ }
146
+ inWindows = inWindows.add(venue);
147
+ measuredTotal = measuredTotal.add(measured);
148
+ windows.push({
149
+ from_ms: prev,
150
+ to_ms: t,
151
+ block: m.block,
152
+ tx: m.tx,
153
+ measured_usdc: measured.toString(),
154
+ venue_usdc: venue.toString(),
155
+ venue_rows: count,
156
+ diff_usdc: diff.toString(),
157
+ status,
158
+ });
159
+ prev = t;
160
+ }
161
+ const last = meas.length > 0 ? num(meas[meas.length - 1].time_ms, "time_ms") : startMs;
162
+ const before = meas.length > 0 ? fundingInWindow(rows, startMs - 1, startMs) : Dec.from(0);
163
+ const after = meas.length > 0 ? fundingInWindow(rows, last, endMs) : fundingInWindow(rows, startMs, endMs);
164
+ return {
165
+ windows,
166
+ matched: windows.length - differing,
167
+ differing,
168
+ measured_total_usdc: measuredTotal.toString(),
169
+ venue_total_in_windows_usdc: inWindows.toString(),
170
+ venue_before_first_usdc: before.toString(),
171
+ venue_after_last_usdc: after.toString(),
172
+ venue_total_usdc: fundingInWindow(rows, startMs - 1, endMs).toString(),
173
+ status: windows.length === 0 ? "NO_MEASUREMENTS" : differing > 0 ? "DIFFERENCES" : "RECONCILED",
174
+ };
175
+ }
176
+ function sortValue(value) {
177
+ if (Array.isArray(value)) {
178
+ return value.map(sortValue);
179
+ }
180
+ if (value !== null && typeof value === "object") {
181
+ const out = {};
182
+ for (const key of Object.keys(value).sort()) {
183
+ out[key] = sortValue(value[key]);
184
+ }
185
+ return out;
186
+ }
187
+ return value;
188
+ }
189
+ /** Python's json.dumps(sort_keys=True, separators=(",", ":"), ensure_ascii=True). */
190
+ function canonicalAscii(value) {
191
+ return JSON.stringify(sortValue(value)).replace(/[\u007f-\uffff]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
192
+ }
193
+ function sha256(data) {
194
+ return (0, node_crypto_1.createHash)("sha256").update(data).digest("hex");
195
+ }
196
+ function verifyReconReceipt(receipt, inputsBytes) {
197
+ const body = typeof receipt === "object" && receipt !== null && !Array.isArray(receipt)
198
+ ? receipt
199
+ : null;
200
+ if (body === null) {
201
+ return { status: "MISMATCH", mismatches: ["receipt mismatch"] };
202
+ }
203
+ const problems = [];
204
+ if (body.kind !== exports.RECON_KIND) {
205
+ problems.push("kind");
206
+ }
207
+ if (body.version !== exports.RECON_VERSION) {
208
+ problems.push("version");
209
+ }
210
+ if (body.inputs_sha256 !== sha256(inputsBytes)) {
211
+ problems.push("inputs_sha256");
212
+ }
213
+ let result;
214
+ try {
215
+ const inputs = JSON.parse(Buffer.from(inputsBytes).toString("utf8"));
216
+ result = reconcile(inputs);
217
+ }
218
+ catch (error) {
219
+ return { status: "MISMATCH", mismatches: [...problems, `inputs: ${error.message}`] };
220
+ }
221
+ if (canonicalAscii(body.result) !== canonicalAscii(result)) {
222
+ problems.push("result");
223
+ }
224
+ if (body.result_sha256 !== sha256(canonicalAscii(result))) {
225
+ problems.push("result_sha256");
226
+ }
227
+ return { status: problems.length > 0 ? "MISMATCH" : "VERIFIED", mismatches: problems };
228
+ }
@@ -4,6 +4,10 @@ export type { GuardCode, GuardLimits, GuardOverrides, GuardResult, Guards, Marke
4
4
  export { guardedSimulate } from "./guarded.ts";
5
5
  export type { GuardedSimulateResult } from "./guarded.ts";
6
6
  export { renderReceiptCard } from "./card.ts";
7
+ export { RECON_KIND, RECON_VERSION, reconcile, verifyReconReceipt } from "./fundingRecon.ts";
8
+ export type { ReconVerify } from "./fundingRecon.ts";
9
+ export { LINK_KIND, LINK_VERSION, buildLink, computeLink, linkInputs, normaliseSelector, selectFills, simFromReceipt, verifyLink, } from "./fillLink.ts";
10
+ export type { BuiltLink, LinkInputs, LinkNetwork, LinkResult, LinkSelector, LinkVerify, SimTrade, } from "./fillLink.ts";
7
11
  export { RECEIPT_KIND, RECEIPT_STATEMENT, RECEIPT_VERSION, buildGuardedReceipt, buildReceiptDir, buildReceiptFiles, canonical, costBreakdownFromReceipt, exampleInputs, limitsPayload, sha256Json, simulateInputs, snapshotRows, verifyReceipt, verifyReceiptAt, writeReceiptDir, } from "./receipt.ts";
8
12
  export type { BuiltReceipt } from "./receipt.ts";
9
13
  export { executionCost } from "./vendor/costs.ts";