@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
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Holding-period receipts (issue 96): entry and exit fill linkage plus a funding sum.
|
|
3
|
+
*
|
|
4
|
+
* TypeScript port of `perpbrain_read.sim.holding` (record version 2). Same record, same
|
|
5
|
+
* canonical JSON, so a record built by either SDK verifies in the other.
|
|
6
|
+
*
|
|
7
|
+
* What the record proves: the result reproduces from the stored inputs. Tamper-evidence only.
|
|
8
|
+
* Fills and funding rows are caller-supplied and not authenticated to the venue or account.
|
|
9
|
+
* `funding_usdc` is the account-level sum of the supplied rows for one coin in the window, NOT
|
|
10
|
+
* attributed to this position. Funding coverage is unknown. Fee tokens other than USDC are
|
|
11
|
+
* flagged, never valued as zero.
|
|
12
|
+
*
|
|
13
|
+
* Pinned definitions: funding window `start_ms < time <= end_ms`; each leg's first and last
|
|
14
|
+
* fill time in `[start_ms, end_ms]`. COMPLETE needs both legs LINKED with fill_ratio 1, equal
|
|
15
|
+
* size, same coin as the funding coin, opposite sides, distinct fills, exit after entry, fills
|
|
16
|
+
* in window and USDC fees only. Otherwise INCOMPLETE with reasons. An open position with no
|
|
17
|
+
* reasons is PROVISIONAL.
|
|
18
|
+
*
|
|
19
|
+
* Read-only: no keys, no order path, no network.
|
|
20
|
+
*/
|
|
21
|
+
import { createHash } from "node:crypto";
|
|
22
|
+
import { canonical, sha256Json } from "./receipt.js";
|
|
23
|
+
import { computeLink, linkInputs, normaliseSelector, simFromReceipt, } from "./fillLink.js";
|
|
24
|
+
import { formatFixed, isStrictDecimal, parseStrictFixed } from "./fixedDecimal.js";
|
|
25
|
+
export const HOLDING_KIND = "perpbrain.holding-receipt";
|
|
26
|
+
export const HOLDING_VERSION = 3;
|
|
27
|
+
export const HOLDING_STATEMENT = "reproducible from the supplied inputs; not authenticated to the venue or account";
|
|
28
|
+
export const VERIFY_SCOPE = "ARITHMETIC_AND_HASHES_REPRODUCED_FROM_SUPPLIED_INPUTS; authenticity of fills and funding rows is not established";
|
|
29
|
+
export const FUNDING_SCOPE = "ACCOUNT_COIN_SUM_NOT_POSITION_ATTRIBUTED";
|
|
30
|
+
export const FUNDING_COVERAGE = "UNKNOWN";
|
|
31
|
+
function sha256Hex(raw) {
|
|
32
|
+
return createHash("sha256").update(raw).digest("hex");
|
|
33
|
+
}
|
|
34
|
+
function isInt(value) {
|
|
35
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
36
|
+
}
|
|
37
|
+
function validate(inputs) {
|
|
38
|
+
if (inputs.network !== "mainnet" && inputs.network !== "testnet") {
|
|
39
|
+
throw new Error("network must be mainnet or testnet");
|
|
40
|
+
}
|
|
41
|
+
if (!isInt(inputs.start_ms) || !isInt(inputs.end_ms)) {
|
|
42
|
+
throw new Error("start_ms and end_ms must be integers");
|
|
43
|
+
}
|
|
44
|
+
if (inputs.end_ms <= inputs.start_ms)
|
|
45
|
+
throw new Error("end_ms must be after start_ms");
|
|
46
|
+
}
|
|
47
|
+
function fundingRows(inputs) {
|
|
48
|
+
const rows = inputs.funding_rows;
|
|
49
|
+
if (!Array.isArray(rows))
|
|
50
|
+
throw new Error("funding_rows must be a list");
|
|
51
|
+
for (const row of rows) {
|
|
52
|
+
if (row === null || typeof row !== "object" || Array.isArray(row)) {
|
|
53
|
+
throw new Error("funding row must be an object");
|
|
54
|
+
}
|
|
55
|
+
if (typeof row.coin !== "string" || !isInt(row.time)) {
|
|
56
|
+
throw new Error("funding row needs a string coin and an integer time");
|
|
57
|
+
}
|
|
58
|
+
if (!isStrictDecimal(row.usdc))
|
|
59
|
+
throw new Error("funding row usdc must be a plain decimal string");
|
|
60
|
+
}
|
|
61
|
+
return rows;
|
|
62
|
+
}
|
|
63
|
+
function leg(inputs, spec, receipt, allFills) {
|
|
64
|
+
const sim = simFromReceipt(receipt, spec.trade_index);
|
|
65
|
+
const built = linkInputs(receipt, allFills, {
|
|
66
|
+
network: inputs.network,
|
|
67
|
+
user: inputs.account,
|
|
68
|
+
by: spec.by,
|
|
69
|
+
value: spec.value,
|
|
70
|
+
tradeIndex: spec.trade_index,
|
|
71
|
+
});
|
|
72
|
+
const result = computeLink(built);
|
|
73
|
+
return {
|
|
74
|
+
block: {
|
|
75
|
+
selector: { by: spec.by, value: normaliseSelector(spec.by, spec.value) },
|
|
76
|
+
market: sim.market,
|
|
77
|
+
side: sim.side,
|
|
78
|
+
status: result.status,
|
|
79
|
+
size: result.size,
|
|
80
|
+
avg_px: result.avg_px,
|
|
81
|
+
fees_usdc: result.fees_usdc,
|
|
82
|
+
fill_ratio: result.fill_ratio,
|
|
83
|
+
slippage_vs_sim_bps: result.slippage_vs_sim_bps,
|
|
84
|
+
fee_drag_usd: result.fee_drag_usd,
|
|
85
|
+
time_to_first_fill_ms: result.time_to_first_fill_ms,
|
|
86
|
+
first_time_ms: result.first_time_ms,
|
|
87
|
+
last_time_ms: result.last_time_ms,
|
|
88
|
+
oids: result.oids,
|
|
89
|
+
hashes: result.hashes,
|
|
90
|
+
},
|
|
91
|
+
fills: built.fills,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function legReasons(name, block, fills) {
|
|
95
|
+
const reasons = [];
|
|
96
|
+
if (block.status !== "LINKED")
|
|
97
|
+
reasons.push(`${name}_NOT_LINKED`);
|
|
98
|
+
if (block.fill_ratio !== "1")
|
|
99
|
+
reasons.push(`${name}_NOT_FULL_FILL`);
|
|
100
|
+
if (fills.some((f) => f.feeToken !== undefined && f.feeToken !== null && f.feeToken !== "USDC")) {
|
|
101
|
+
reasons.push(`${name}_UNSUPPORTED_FEE_TOKEN`);
|
|
102
|
+
}
|
|
103
|
+
return reasons;
|
|
104
|
+
}
|
|
105
|
+
function outside(block, startMs, endMs) {
|
|
106
|
+
const first = block.first_time_ms;
|
|
107
|
+
const last = block.last_time_ms;
|
|
108
|
+
return first === null || last === null || first < startMs || last > endMs;
|
|
109
|
+
}
|
|
110
|
+
function intersects(a, b) {
|
|
111
|
+
const right = new Set(b);
|
|
112
|
+
return a.some((x) => right.has(x));
|
|
113
|
+
}
|
|
114
|
+
export function computeHolding(inputs, receipt, allFills, receiptVerified = false) {
|
|
115
|
+
validate(inputs);
|
|
116
|
+
const rows = fundingRows(inputs);
|
|
117
|
+
const { start_ms: startMs, end_ms: endMs } = inputs;
|
|
118
|
+
const entryOut = leg(inputs, inputs.entry, receipt, allFills);
|
|
119
|
+
const entry = entryOut.block;
|
|
120
|
+
let reasons = legReasons("ENTRY", entry, entryOut.fills);
|
|
121
|
+
if (outside(entry, startMs, endMs))
|
|
122
|
+
reasons.push("ENTRY_OUTSIDE_WINDOW");
|
|
123
|
+
if (entry.market !== inputs.coin)
|
|
124
|
+
reasons.push("COIN_MISMATCH");
|
|
125
|
+
let exitBlock = null;
|
|
126
|
+
const isOpen = inputs.exit === null;
|
|
127
|
+
if (inputs.exit !== null) {
|
|
128
|
+
const exitOut = leg(inputs, inputs.exit, receipt, allFills);
|
|
129
|
+
exitBlock = exitOut.block;
|
|
130
|
+
reasons = reasons.concat(legReasons("EXIT", exitBlock, exitOut.fills));
|
|
131
|
+
if (outside(exitBlock, startMs, endMs))
|
|
132
|
+
reasons.push("EXIT_OUTSIDE_WINDOW");
|
|
133
|
+
if (exitBlock.market !== inputs.coin)
|
|
134
|
+
reasons.push("COIN_MISMATCH");
|
|
135
|
+
if (exitBlock.side === entry.side)
|
|
136
|
+
reasons.push("SIDE_NOT_OPPOSITE");
|
|
137
|
+
if (exitBlock.size !== entry.size)
|
|
138
|
+
reasons.push("SIZE_MISMATCH");
|
|
139
|
+
if (intersects(exitBlock.oids, entry.oids) || intersects(exitBlock.hashes, entry.hashes)) {
|
|
140
|
+
reasons.push("LEGS_SHARE_FILLS");
|
|
141
|
+
}
|
|
142
|
+
if (entry.last_time_ms !== null &&
|
|
143
|
+
exitBlock.first_time_ms !== null &&
|
|
144
|
+
exitBlock.first_time_ms <= entry.last_time_ms) {
|
|
145
|
+
reasons.push("EXIT_NOT_AFTER_ENTRY");
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const inWindow = rows.filter((r) => r.coin === inputs.coin && startMs < r.time && r.time <= endMs);
|
|
149
|
+
let funding = 0n;
|
|
150
|
+
for (const r of inWindow)
|
|
151
|
+
funding += parseStrictFixed(r.usdc, "funding row usdc");
|
|
152
|
+
reasons = [...new Set(reasons)].sort();
|
|
153
|
+
const status = reasons.length
|
|
154
|
+
? "INCOMPLETE"
|
|
155
|
+
: isOpen || !receiptVerified
|
|
156
|
+
? "PROVISIONAL"
|
|
157
|
+
: "COMPLETE";
|
|
158
|
+
if (!receiptVerified)
|
|
159
|
+
reasons = [...new Set([...reasons, "RECEIPT_NOT_VERIFIED"])].sort();
|
|
160
|
+
return {
|
|
161
|
+
status,
|
|
162
|
+
reasons,
|
|
163
|
+
entry,
|
|
164
|
+
exit: exitBlock,
|
|
165
|
+
funding_usdc: formatFixed(funding),
|
|
166
|
+
funding_rows_count: inWindow.length,
|
|
167
|
+
funding_scope: FUNDING_SCOPE,
|
|
168
|
+
funding_coverage: FUNDING_COVERAGE,
|
|
169
|
+
hold_ms: endMs - startMs,
|
|
170
|
+
open: isOpen,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/** receiptVerified is true only when the caller ran the upstream receipt verifier. The default
|
|
174
|
+
* is false: the record is capped at PROVISIONAL with reason RECEIPT_NOT_VERIFIED. */
|
|
175
|
+
export function buildHolding(inputs, receipt, allFills, receiptVerified = false) {
|
|
176
|
+
const raw = canonical(inputs);
|
|
177
|
+
const result = computeHolding(inputs, receipt, allFills, receiptVerified);
|
|
178
|
+
const record = {
|
|
179
|
+
kind: HOLDING_KIND,
|
|
180
|
+
version: HOLDING_VERSION,
|
|
181
|
+
label: (inputs.network === "mainnet" ? "MAINNET" : "TESTNET") +
|
|
182
|
+
(result.open ? " OPEN" : ""),
|
|
183
|
+
statement: HOLDING_STATEMENT,
|
|
184
|
+
receipt_sha256: sha256Json(receipt),
|
|
185
|
+
upstream_receipt_verification: receiptVerified ? "VERIFIED" : "NOT_VERIFIED",
|
|
186
|
+
inputs_sha256: sha256Hex(raw),
|
|
187
|
+
result,
|
|
188
|
+
result_sha256: sha256Json(result),
|
|
189
|
+
};
|
|
190
|
+
return {
|
|
191
|
+
record,
|
|
192
|
+
recordBytes: Buffer.from(canonical(record) + "\n", "utf8"),
|
|
193
|
+
inputsBytes: Buffer.from(raw + "\n", "utf8"),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
/** VERIFIED only when the receipt is supplied and every hash and the result reproduce.
|
|
197
|
+
* receiptVerified is the caller's assertion that it ran an upstream receipt verifier; this
|
|
198
|
+
* function cannot check it, and the TS side has no CLI path that sets it (default false).
|
|
199
|
+
* VERIFIED does not mean the receipt is authentic. The record field is outside
|
|
200
|
+
* result_sha256, but the hashed result carries RECEIPT_NOT_VERIFIED when it is not set.
|
|
201
|
+
* Without a receipt only kind, version and the inputs hash can be checked: the answer is
|
|
202
|
+
* UNCHECKED_PARTIAL, never VERIFIED. */
|
|
203
|
+
export function verifyHolding(record, inputsBytes, allFills, receipt, receiptVerified = false) {
|
|
204
|
+
const problems = [];
|
|
205
|
+
const body = (record ?? null);
|
|
206
|
+
if (body === null || typeof body !== "object") {
|
|
207
|
+
return { status: "MISMATCH", mismatches: ["record must be an object"] };
|
|
208
|
+
}
|
|
209
|
+
if (body.kind !== HOLDING_KIND)
|
|
210
|
+
problems.push("kind");
|
|
211
|
+
if (body.version !== HOLDING_VERSION)
|
|
212
|
+
problems.push("version");
|
|
213
|
+
let result;
|
|
214
|
+
try {
|
|
215
|
+
const inputs = JSON.parse(inputsBytes.toString("utf8"));
|
|
216
|
+
if (sha256Hex(canonical(inputs)) !== body.inputs_sha256)
|
|
217
|
+
problems.push("inputs_sha256");
|
|
218
|
+
if (receipt === undefined) {
|
|
219
|
+
if (problems.length)
|
|
220
|
+
return { status: "MISMATCH", mismatches: problems };
|
|
221
|
+
return {
|
|
222
|
+
status: "UNCHECKED_PARTIAL",
|
|
223
|
+
mismatches: [],
|
|
224
|
+
unchecked: ["result", "result_sha256", "receipt_sha256"],
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
result = computeHolding(inputs, receipt, allFills, receiptVerified);
|
|
228
|
+
}
|
|
229
|
+
catch (exc) {
|
|
230
|
+
problems.push(`inputs: ${exc instanceof Error ? exc.message : String(exc)}`);
|
|
231
|
+
return { status: "MISMATCH", mismatches: problems };
|
|
232
|
+
}
|
|
233
|
+
const network = JSON.parse(inputsBytes.toString("utf8")).network;
|
|
234
|
+
const expectedLabel = (network === "mainnet" ? "MAINNET" : "TESTNET") + (result.open ? " OPEN" : "");
|
|
235
|
+
if (body.label !== expectedLabel)
|
|
236
|
+
problems.push("label");
|
|
237
|
+
if (body.statement !== HOLDING_STATEMENT)
|
|
238
|
+
problems.push("statement");
|
|
239
|
+
if (canonical(body.result) !== canonical(result))
|
|
240
|
+
problems.push("result");
|
|
241
|
+
if (body.result_sha256 !== sha256Json(result))
|
|
242
|
+
problems.push("result_sha256");
|
|
243
|
+
if (body.receipt_sha256 !== sha256Json(receipt))
|
|
244
|
+
problems.push("receipt_sha256");
|
|
245
|
+
const expectedFlag = receiptVerified ? "VERIFIED" : "NOT_VERIFIED";
|
|
246
|
+
if (body.upstream_receipt_verification !== expectedFlag) {
|
|
247
|
+
problems.push("upstream_receipt_verification");
|
|
248
|
+
}
|
|
249
|
+
if (problems.length)
|
|
250
|
+
return { status: "MISMATCH", mismatches: problems };
|
|
251
|
+
return {
|
|
252
|
+
status: "VERIFIED",
|
|
253
|
+
mismatches: [],
|
|
254
|
+
scope: VERIFY_SCOPE,
|
|
255
|
+
upstream_receipt_verification: expectedFlag,
|
|
256
|
+
};
|
|
257
|
+
}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -4,7 +4,17 @@ 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 {
|
|
7
|
+
export { CALIBRATION_KIND, CALIBRATION_VERSION, CALIBRATION_STATEMENT, MIN_SAMPLE, buildReport, computeReport, verifyReport, } from "./calibration.ts";
|
|
8
|
+
export type { BuiltReport, CalibrationCandidate, CalibrationInputs, ReportVerify, } from "./calibration.ts";
|
|
9
|
+
export { CLIENT_META_ALLOWED_KEYS, CLIENT_META_MAX_CANONICAL_BYTES, attachClientMeta, makeEntry, validateClientMeta, } from "./clientMeta.ts";
|
|
10
|
+
export type { ClientMetaEntry } from "./clientMeta.ts";
|
|
11
|
+
export { FUNDING_COVERAGE, FUNDING_SCOPE, HOLDING_KIND, HOLDING_STATEMENT, HOLDING_VERSION, VERIFY_SCOPE, buildHolding, computeHolding, verifyHolding, } from "./holding.ts";
|
|
12
|
+
export type { BuiltHolding, HoldingInputs, HoldingLeg, HoldingVerify } from "./holding.ts";
|
|
13
|
+
export { RECON_KIND, RECON_VERSION, reconcile, verifyReconReceipt } from "./fundingRecon.ts";
|
|
14
|
+
export type { ReconVerify } from "./fundingRecon.ts";
|
|
15
|
+
export { LINK_KIND, LINK_VERSION, buildLink, computeLink, linkInputs, normaliseSelector, selectFills, simFromReceipt, verifyLink, } from "./fillLink.ts";
|
|
16
|
+
export type { BuiltLink, LinkInputs, LinkNetwork, LinkResult, LinkSelector, LinkVerify, SimTrade, } from "./fillLink.ts";
|
|
17
|
+
export { RECEIPT_KIND, RECEIPT_STATEMENT, RECEIPT_VERSION, buildGuardedReceipt, buildReceiptDir, buildReceiptFiles, canonical, costBreakdownFromReceipt, exampleInputs, limitsPayload, sha256Json, simulateInputs, snapshotRows, verifyReceipt, verifyReceiptAt, ResourceLimitError, UnsupportedVerificationError, MissingInputsError, InvalidLimitError, NoVerdictError, writeReceiptDir, } from "./receipt.ts";
|
|
8
18
|
export type { BuiltReceipt } from "./receipt.ts";
|
|
9
19
|
export { executionCost } from "./vendor/costs.ts";
|
|
10
20
|
export type { CostBreakdown } from "./vendor/costs.ts";
|
package/dist/esm/index.js
CHANGED
|
@@ -2,7 +2,12 @@
|
|
|
2
2
|
export { CODES, HARD_MAX_DAILY_LOSS_PCT, HARD_MAX_OPEN_POSITIONS, HARD_MAX_ORDER_RATE, HARD_MAX_SLIPPAGE_BPS, PRESETS, STALE_BLOCK_MS, STALE_HALT_MS, GuardBlocked, GuardConfigError, GuardLoosenError, GuardSession, defaultGuards, defaultSnapshot, fromConfig, survivalReport, wireCode, } from "./guards.js";
|
|
3
3
|
export { guardedSimulate } from "./guarded.js";
|
|
4
4
|
export { renderReceiptCard } from "./card.js";
|
|
5
|
-
export {
|
|
5
|
+
export { CALIBRATION_KIND, CALIBRATION_VERSION, CALIBRATION_STATEMENT, MIN_SAMPLE, buildReport, computeReport, verifyReport, } from "./calibration.js";
|
|
6
|
+
export { CLIENT_META_ALLOWED_KEYS, CLIENT_META_MAX_CANONICAL_BYTES, attachClientMeta, makeEntry, validateClientMeta, } from "./clientMeta.js";
|
|
7
|
+
export { FUNDING_COVERAGE, FUNDING_SCOPE, HOLDING_KIND, HOLDING_STATEMENT, HOLDING_VERSION, VERIFY_SCOPE, buildHolding, computeHolding, verifyHolding, } from "./holding.js";
|
|
8
|
+
export { RECON_KIND, RECON_VERSION, reconcile, verifyReconReceipt } from "./fundingRecon.js";
|
|
9
|
+
export { LINK_KIND, LINK_VERSION, buildLink, computeLink, linkInputs, normaliseSelector, selectFills, simFromReceipt, verifyLink, } from "./fillLink.js";
|
|
10
|
+
export { RECEIPT_KIND, RECEIPT_STATEMENT, RECEIPT_VERSION, buildGuardedReceipt, buildReceiptDir, buildReceiptFiles, canonical, costBreakdownFromReceipt, exampleInputs, limitsPayload, sha256Json, simulateInputs, snapshotRows, verifyReceipt, verifyReceiptAt, ResourceLimitError, UnsupportedVerificationError, MissingInputsError, InvalidLimitError, NoVerdictError, writeReceiptDir, } from "./receipt.js";
|
|
6
11
|
export { executionCost } from "./vendor/costs.js";
|
|
7
12
|
export { InfoClient } from "./vendor/info.js";
|
|
8
13
|
export { fees, funding, markets, orderBook, positions } from "./vendor/queries.js";
|
package/dist/esm/receipt.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** Re-derive a simulation receipt. The check is verified and reproducible. */
|
|
2
|
+
import type { ClientMetaEntry } from "./clientMeta.ts";
|
|
2
3
|
import { GuardSession, type Guards, type MarketSnapshot } from "./guards.ts";
|
|
3
4
|
import { type GuardedSimulateResult } from "./guarded.ts";
|
|
4
5
|
import { type CostBreakdown } from "./vendor/costs.ts";
|
|
@@ -8,6 +9,11 @@ export declare const RECEIPT_VERSION = 5;
|
|
|
8
9
|
export interface VerifyReport {
|
|
9
10
|
status: "VERIFIED" | "MISMATCH";
|
|
10
11
|
mismatches: string[];
|
|
12
|
+
/** Set on kinds whose VERIFIED covers less than a full re-run. A calibration report sets
|
|
13
|
+
* "self-consistency-only" with venue_authenticated false: arithmetic and hashes reproduce from
|
|
14
|
+
* the supplied inputs, and nothing is matched to a venue. Absent on other kinds. */
|
|
15
|
+
scope?: "self-consistency-only";
|
|
16
|
+
venue_authenticated?: false;
|
|
11
17
|
}
|
|
12
18
|
export declare function verifyReceipt(receipt: unknown, manifest: Uint8Array, inputs: Uint8Array): VerifyReport;
|
|
13
19
|
export declare function canonical(value: unknown): string;
|
|
@@ -24,7 +30,7 @@ export declare function exampleInputs(): Record<string, unknown>;
|
|
|
24
30
|
export declare function limitsPayload(limits: Guards): Record<string, unknown>;
|
|
25
31
|
export declare function snapshotRows(snapshot: MarketSnapshot): Record<string, unknown>[];
|
|
26
32
|
export declare function simulateInputs(inputs: Record<string, unknown>): Record<string, unknown>;
|
|
27
|
-
export declare function buildReceiptFiles(inputs: Record<string, unknown>, result: Record<string, unknown>, limits: Record<string, unknown>, marketSnapshot: Record<string, unknown>[]): BuiltReceipt;
|
|
33
|
+
export declare function buildReceiptFiles(inputs: Record<string, unknown>, result: Record<string, unknown>, limits: Record<string, unknown>, marketSnapshot: Record<string, unknown>[], clientMetadata?: ClientMetaEntry[]): BuiltReceipt;
|
|
28
34
|
export declare function writeReceiptDir(directory: string, built: BuiltReceipt): string;
|
|
29
35
|
export declare function buildReceiptDir(directory: string, inputs?: Record<string, unknown>, limits?: Guards | null, snapshot?: MarketSnapshot | null): string;
|
|
30
36
|
/**
|
|
@@ -42,4 +48,45 @@ export declare function buildReceiptDir(directory: string, inputs?: Record<strin
|
|
|
42
48
|
*/
|
|
43
49
|
export declare function buildGuardedReceipt(directory: string, inputs: Record<string, unknown>, result: GuardedSimulateResult | Record<string, unknown>, session: GuardSession, snapshot?: MarketSnapshot | null): string;
|
|
44
50
|
/** Read a receipt.json file, or a directory that contains one, and check it. */
|
|
45
|
-
|
|
51
|
+
/**
|
|
52
|
+
* Base for "no verdict reached": the check did not run to VERIFIED or MISMATCH. Thrown, never
|
|
53
|
+
* folded into a report, and says nothing about whether the record is valid.
|
|
54
|
+
*/
|
|
55
|
+
export declare class NoVerdictError extends Error {
|
|
56
|
+
constructor(message: string);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* A file is larger than the caller's explicit read limit. Thrown, never folded into a
|
|
60
|
+
* MISMATCH or VERIFIED report: "too big to check" is a resource failure, not a verdict.
|
|
61
|
+
*/
|
|
62
|
+
export declare class ResourceLimitError extends NoVerdictError {
|
|
63
|
+
constructor(message: string);
|
|
64
|
+
}
|
|
65
|
+
/** The record is of a kind this function does not check. No verdict was reached: this is neither
|
|
66
|
+
* VERIFIED nor MISMATCH, and says nothing about whether the record is valid. */
|
|
67
|
+
export declare class UnsupportedVerificationError extends NoVerdictError {
|
|
68
|
+
constructor(message: string);
|
|
69
|
+
}
|
|
70
|
+
/** The inputs a record is checked against were not supplied (not found beside it). No verdict:
|
|
71
|
+
* a missing file is not evidence that the record is invalid. */
|
|
72
|
+
export declare class MissingInputsError extends NoVerdictError {
|
|
73
|
+
constructor(message: string);
|
|
74
|
+
}
|
|
75
|
+
/** The caller's `maxBytes` is not a positive safe integer. A caller error, thrown before any file
|
|
76
|
+
* is read: it is neither a verdict nor a resource failure. */
|
|
77
|
+
export declare class InvalidLimitError extends RangeError {
|
|
78
|
+
constructor(message: string);
|
|
79
|
+
}
|
|
80
|
+
export interface VerifyAtOptions {
|
|
81
|
+
/** Opt-in per-file read limit for receipt.json, manifest.json and inputs.json. Default: none. */
|
|
82
|
+
maxBytes?: number;
|
|
83
|
+
}
|
|
84
|
+
/** Reads with a shared descriptor reader; exported only so a test can inject a growing file. */
|
|
85
|
+
export type ChunkReader = (buffer: Buffer, length: number) => number;
|
|
86
|
+
/**
|
|
87
|
+
* Read chunks until end of file or one byte past ``maxBytes``. The size comes from the bytes
|
|
88
|
+
* actually read, never from a stat, so a file that grows or is replaced after any size check is
|
|
89
|
+
* still bounded, and a large limit never allocates for the limit.
|
|
90
|
+
*/
|
|
91
|
+
export declare function readChunksCapped(read: ChunkReader, maxBytes: number, name: string): Buffer;
|
|
92
|
+
export declare function verifyReceiptAt(path: string, options?: VerifyAtOptions): VerifyReport;
|
package/dist/esm/receipt.js
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
/** Re-derive a simulation receipt. The check is verified and reproducible. */
|
|
2
|
+
import { attachClientMeta, validateClientMeta } from "./clientMeta.js";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
|
-
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
|
|
4
5
|
import { dirname, join } from "node:path";
|
|
5
6
|
import { GuardBlocked, GuardSession, defaultSnapshot, snapshotFromCoins, } from "./guards.js";
|
|
7
|
+
import { CALIBRATION_KIND, verifyReport as verifyCalibrationReport } from "./calibration.js";
|
|
8
|
+
import { RECON_KIND, verifyReconReceipt } from "./fundingRecon.js";
|
|
9
|
+
import { HOLDING_KIND } from "./holding.js";
|
|
6
10
|
import { guardedSimulate } from "./guarded.js";
|
|
7
11
|
import { CURRENT_SIM_DEFAULTS, receiptProfile, simDefaults } from "./vendor/simDefaults.js";
|
|
8
12
|
import { studyAccounting } from "./study.js";
|
|
@@ -117,19 +121,24 @@ export function simulateInputs(inputs) {
|
|
|
117
121
|
// Receipts store the snake_case wire form; do not hash the camelCase runtime object.
|
|
118
122
|
return wireResult(runSim(inputs));
|
|
119
123
|
}
|
|
120
|
-
export function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
|
|
124
|
+
export function buildReceiptFiles(inputs, result, limits, marketSnapshot, clientMetadata) {
|
|
121
125
|
const inputsBytes = canonicalFileBytes(inputs);
|
|
122
126
|
const dataSnapshotId = sha256Bytes(inputsBytes);
|
|
123
127
|
const limitsHash = sha256Json(limits);
|
|
124
128
|
const marketSnapshotId = sha256Json(marketSnapshot);
|
|
125
129
|
const resultSha256 = sha256Json(result);
|
|
126
|
-
|
|
130
|
+
let manifest = {
|
|
127
131
|
data_snapshot_id: dataSnapshotId,
|
|
128
132
|
files: [{ file: "inputs.json", rows: 1, sha256: dataSnapshotId }],
|
|
129
133
|
limits_hash: limitsHash,
|
|
130
134
|
market_snapshot_id: marketSnapshotId,
|
|
131
135
|
result_sha256: resultSha256,
|
|
132
136
|
};
|
|
137
|
+
// Issue 97: an opaque hashed block in the manifest only. Undefined or empty leaves the
|
|
138
|
+
// manifest, and so the receipt, byte-identical to a build without it.
|
|
139
|
+
if (clientMetadata !== undefined && clientMetadata.length > 0) {
|
|
140
|
+
manifest = attachClientMeta(manifest, clientMetadata);
|
|
141
|
+
}
|
|
133
142
|
const manifestBytes = prettyBytes(manifest);
|
|
134
143
|
const receipt = {
|
|
135
144
|
data_snapshot_id: dataSnapshotId,
|
|
@@ -147,6 +156,11 @@ export function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
|
|
|
147
156
|
statement: RECEIPT_STATEMENT,
|
|
148
157
|
version: RECEIPT_VERSION,
|
|
149
158
|
};
|
|
159
|
+
// Mirror the Python builder: record study accounting whenever the inputs carry a study block.
|
|
160
|
+
const recordedStudy = studyFromInputs(inputs, simDefaults(CURRENT_SIM_DEFAULTS).numerics === "fixed18" ? "fixed18" : "float");
|
|
161
|
+
if (recordedStudy !== null) {
|
|
162
|
+
receipt.study_accounting = { ...recordedStudy };
|
|
163
|
+
}
|
|
150
164
|
return {
|
|
151
165
|
receipt,
|
|
152
166
|
manifest,
|
|
@@ -211,16 +225,113 @@ function insideDirectory(root, ref) {
|
|
|
211
225
|
return join(root, candidate);
|
|
212
226
|
}
|
|
213
227
|
/** Read a receipt.json file, or a directory that contains one, and check it. */
|
|
214
|
-
|
|
215
|
-
|
|
228
|
+
/**
|
|
229
|
+
* Base for "no verdict reached": the check did not run to VERIFIED or MISMATCH. Thrown, never
|
|
230
|
+
* folded into a report, and says nothing about whether the record is valid.
|
|
231
|
+
*/
|
|
232
|
+
export class NoVerdictError extends Error {
|
|
233
|
+
constructor(message) {
|
|
234
|
+
super(message);
|
|
235
|
+
this.name = "NoVerdictError";
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* A file is larger than the caller's explicit read limit. Thrown, never folded into a
|
|
240
|
+
* MISMATCH or VERIFIED report: "too big to check" is a resource failure, not a verdict.
|
|
241
|
+
*/
|
|
242
|
+
export class ResourceLimitError extends NoVerdictError {
|
|
243
|
+
constructor(message) {
|
|
244
|
+
super(message);
|
|
245
|
+
this.name = "ResourceLimitError";
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/** The record is of a kind this function does not check. No verdict was reached: this is neither
|
|
249
|
+
* VERIFIED nor MISMATCH, and says nothing about whether the record is valid. */
|
|
250
|
+
export class UnsupportedVerificationError extends NoVerdictError {
|
|
251
|
+
constructor(message) {
|
|
252
|
+
super(message);
|
|
253
|
+
this.name = "UnsupportedVerificationError";
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/** The inputs a record is checked against were not supplied (not found beside it). No verdict:
|
|
257
|
+
* a missing file is not evidence that the record is invalid. */
|
|
258
|
+
export class MissingInputsError extends NoVerdictError {
|
|
259
|
+
constructor(message) {
|
|
260
|
+
super(message);
|
|
261
|
+
this.name = "MissingInputsError";
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/** The caller's `maxBytes` is not a positive safe integer. A caller error, thrown before any file
|
|
265
|
+
* is read: it is neither a verdict nor a resource failure. */
|
|
266
|
+
export class InvalidLimitError extends RangeError {
|
|
267
|
+
constructor(message) {
|
|
268
|
+
super(message);
|
|
269
|
+
this.name = "InvalidLimitError";
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
function assertLimit(maxBytes) {
|
|
273
|
+
if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) {
|
|
274
|
+
throw new InvalidLimitError(`maxBytes must be a positive safe integer, got ${String(maxBytes)}`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const READ_CHUNK = 64 * 1024;
|
|
278
|
+
/**
|
|
279
|
+
* Read chunks until end of file or one byte past ``maxBytes``. The size comes from the bytes
|
|
280
|
+
* actually read, never from a stat, so a file that grows or is replaced after any size check is
|
|
281
|
+
* still bounded, and a large limit never allocates for the limit.
|
|
282
|
+
*/
|
|
283
|
+
export function readChunksCapped(read, maxBytes, name) {
|
|
284
|
+
const chunks = [];
|
|
285
|
+
let total = 0;
|
|
286
|
+
for (;;) {
|
|
287
|
+
const want = Math.min(READ_CHUNK, maxBytes + 1 - total);
|
|
288
|
+
const chunk = Buffer.alloc(want);
|
|
289
|
+
const n = read(chunk, want);
|
|
290
|
+
if (n === 0)
|
|
291
|
+
break;
|
|
292
|
+
total += n;
|
|
293
|
+
if (total > maxBytes) {
|
|
294
|
+
throw new ResourceLimitError(`${name} exceeds the ${maxBytes} byte read limit`);
|
|
295
|
+
}
|
|
296
|
+
chunks.push(n === want ? chunk : chunk.subarray(0, n));
|
|
297
|
+
}
|
|
298
|
+
return Buffer.concat(chunks, total);
|
|
299
|
+
}
|
|
300
|
+
function readCapped(path, maxBytes) {
|
|
301
|
+
if (maxBytes === undefined) {
|
|
302
|
+
return readFileSync(path);
|
|
303
|
+
}
|
|
304
|
+
const fd = openSync(path, "r");
|
|
305
|
+
try {
|
|
306
|
+
const name = path.split(/[\\/]/).pop() ?? path;
|
|
307
|
+
return readChunksCapped((buffer, length) => readSync(fd, buffer, 0, length, null), maxBytes, name);
|
|
308
|
+
}
|
|
309
|
+
finally {
|
|
310
|
+
closeSync(fd);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
export function verifyReceiptAt(path, options = {}) {
|
|
314
|
+
const maxBytes = options.maxBytes;
|
|
315
|
+
assertLimit(maxBytes);
|
|
316
|
+
let receiptFile = path;
|
|
317
|
+
if (existsSync(path) && statSync(path).isDirectory()) {
|
|
318
|
+
receiptFile = join(path, "receipt.json");
|
|
319
|
+
const calibrationFile = join(path, "calibration.json");
|
|
320
|
+
// A directory with no receipt.json but a calibration.json is a calibration report.
|
|
321
|
+
if (!existsSync(receiptFile) && existsSync(calibrationFile)) {
|
|
322
|
+
receiptFile = calibrationFile;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
216
325
|
if (!existsSync(receiptFile) || !statSync(receiptFile).isFile()) {
|
|
217
326
|
return report(["receipt.json missing"]);
|
|
218
327
|
}
|
|
219
328
|
let loaded;
|
|
220
329
|
try {
|
|
221
|
-
loaded = JSON.parse(
|
|
330
|
+
loaded = JSON.parse(readCapped(receiptFile, maxBytes).toString("utf8"));
|
|
222
331
|
}
|
|
223
|
-
catch {
|
|
332
|
+
catch (error) {
|
|
333
|
+
if (error instanceof NoVerdictError)
|
|
334
|
+
throw error;
|
|
224
335
|
return report(["receipt json mismatch"]);
|
|
225
336
|
}
|
|
226
337
|
const receipt = asObject(loaded);
|
|
@@ -228,9 +339,31 @@ export function verifyReceiptAt(path) {
|
|
|
228
339
|
return report(["receipt mismatch"]);
|
|
229
340
|
}
|
|
230
341
|
const root = dirname(receiptFile);
|
|
342
|
+
if (receipt.kind === RECON_KIND) {
|
|
343
|
+
// A funding-reconciliation receipt is checked against inputs.json beside it.
|
|
344
|
+
const inputsPath = join(root, "inputs.json");
|
|
345
|
+
if (!existsSync(inputsPath) || !statSync(inputsPath).isFile()) {
|
|
346
|
+
return report(["inputs.json missing (download it next to receipt.json)"]);
|
|
347
|
+
}
|
|
348
|
+
return verifyReconReceipt(receipt, readCapped(inputsPath, maxBytes));
|
|
349
|
+
}
|
|
350
|
+
if (receipt.kind === CALIBRATION_KIND) {
|
|
351
|
+
// A calibration report is checked against calibration-inputs.json beside it. VERIFIED here means the
|
|
352
|
+
// report reproduces from those inputs (self-consistency); it does not authenticate the inputs or any venue.
|
|
353
|
+
const inputsPath = join(root, "calibration-inputs.json");
|
|
354
|
+
if (!existsSync(inputsPath) || !statSync(inputsPath).isFile()) {
|
|
355
|
+
throw new MissingInputsError("calibration-inputs.json missing (keep it next to calibration.json)");
|
|
356
|
+
}
|
|
357
|
+
const checked = verifyCalibrationReport(receipt, readCapped(inputsPath, maxBytes));
|
|
358
|
+
return { ...report(checked.mismatches), scope: "self-consistency-only", venue_authenticated: false };
|
|
359
|
+
}
|
|
360
|
+
if (receipt.kind === HOLDING_KIND) {
|
|
361
|
+
// A holding record needs the fills and the sim receipt it was linked to; verifyHolding takes them.
|
|
362
|
+
throw new UnsupportedVerificationError("a holding record cannot be checked by verifyReceiptAt: use verifyHolding with its fills and sim receipt");
|
|
363
|
+
}
|
|
231
364
|
const missing = [];
|
|
232
365
|
const manifestPath = join(root, "manifest.json");
|
|
233
|
-
const manifest = existsSync(manifestPath) && statSync(manifestPath).isFile() ?
|
|
366
|
+
const manifest = existsSync(manifestPath) && statSync(manifestPath).isFile() ? readCapped(manifestPath, maxBytes) : null;
|
|
234
367
|
if (manifest === null) {
|
|
235
368
|
missing.push("manifest missing");
|
|
236
369
|
}
|
|
@@ -243,13 +376,15 @@ export function verifyReceiptAt(path) {
|
|
|
243
376
|
try {
|
|
244
377
|
const rawPath = insideDirectory(root, rawRef);
|
|
245
378
|
if (existsSync(rawPath) && statSync(rawPath).isFile()) {
|
|
246
|
-
inputs =
|
|
379
|
+
inputs = readCapped(rawPath, maxBytes);
|
|
247
380
|
}
|
|
248
381
|
else {
|
|
249
382
|
missing.push(`${rawRef} missing`);
|
|
250
383
|
}
|
|
251
384
|
}
|
|
252
|
-
catch {
|
|
385
|
+
catch (error) {
|
|
386
|
+
if (error instanceof NoVerdictError)
|
|
387
|
+
throw error;
|
|
253
388
|
missing.push("raw_ref mismatch");
|
|
254
389
|
}
|
|
255
390
|
}
|
|
@@ -331,6 +466,15 @@ function checkManifest(manifest, receipt, mismatches) {
|
|
|
331
466
|
mismatches.push(`manifest ${key} mismatch`);
|
|
332
467
|
}
|
|
333
468
|
}
|
|
469
|
+
if ("client_metadata" in manifest) {
|
|
470
|
+
try {
|
|
471
|
+
validateClientMeta(manifest.client_metadata);
|
|
472
|
+
}
|
|
473
|
+
catch (error) {
|
|
474
|
+
// Fixed validator messages only; never echo manifest content.
|
|
475
|
+
mismatches.push(`manifest client_metadata mismatch: ${messageOf(error)}`);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
334
478
|
const files = manifest.files;
|
|
335
479
|
const rawRef = receipt.raw_ref;
|
|
336
480
|
if (!Array.isArray(files)) {
|