@perpbrain/sdk 0.1.0 → 0.1.3
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/LICENSE +1 -1
- package/README.md +10 -1
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.js +12 -2
- package/dist/cjs/receipt.d.ts +32 -0
- package/dist/cjs/receipt.js +195 -0
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/receipt.d.ts +32 -0
- package/dist/esm/receipt.js +187 -1
- package/package.json +2 -1
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -14,4 +14,13 @@ npm run build
|
|
|
14
14
|
|
|
15
15
|
The `perpbrain-mcp` command starts `python -m perpbrain.mcp`. If that module is missing, the command prints install guidance and exits.
|
|
16
16
|
|
|
17
|
-
Simulation output is labelled `SIMULATED
|
|
17
|
+
Simulation output is labelled `SIMULATED` and places no order. See the [risk disclosure](https://perpbrain.com/legal/risk-disclosure).
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
## Reads, simulation, and receipts
|
|
21
|
+
|
|
22
|
+
Public `orderBook` and `funding` results include `coin`, `stale`, `asOfMs`, `ageMs`, and (for funding) `midPx`, `markPx`, `oraclePx`, and `openInterest`. `stale` is `true` when `ageMs` is at least 20_000.
|
|
23
|
+
|
|
24
|
+
`verifyReceipt(receipt, manifestBytes, inputsBytes)` re-derives the hashes and reruns the simulator. `verifyReceiptAt(path)` accepts a `receipt.json` file or the directory that contains it. After a successful `guardedSimulate`, call `buildGuardedReceipt(directory, inputs, result, session)` (or `buildReceiptDir`) so the hashed result is the unguarded replay. Do not hash the guarded result object. Receipt inputs are snake_case (`bar_index`); `Decision` is camelCase (`barIndex`).
|
|
25
|
+
|
|
26
|
+
`buildGuardedReceipt`, `buildReceiptDir`, and `verifyReceiptAt` are not in the published `0.1.0` package. Until the next release, write the receipt with Python `build_receipt_dir` and check the three files with `verifyReceipt`.
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -4,7 +4,8 @@ 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 { RECEIPT_KIND, RECEIPT_STATEMENT, RECEIPT_VERSION, buildGuardedReceipt, buildReceiptDir, buildReceiptFiles, canonical, costBreakdownFromReceipt, exampleInputs, limitsPayload, sha256Json, simulateInputs, snapshotRows, verifyReceipt, verifyReceiptAt, writeReceiptDir, } from "./receipt.ts";
|
|
8
|
+
export type { BuiltReceipt } from "./receipt.ts";
|
|
8
9
|
export { executionCost } from "./vendor/costs.ts";
|
|
9
10
|
export type { CostBreakdown } from "./vendor/costs.ts";
|
|
10
11
|
export type { VerifyReport } from "./receipt.ts";
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/** Read-only and simulation-only SDK surface. */
|
|
3
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.READ_AND_SIM_TOOLS = exports.simulate = exports.positions = exports.orderBook = exports.markets = exports.funding = exports.fees = exports.InfoClient = exports.executionCost = exports.verifyReceipt = exports.sha256Json = exports.canonical = exports.
|
|
4
|
+
exports.READ_AND_SIM_TOOLS = exports.simulate = exports.positions = exports.orderBook = exports.markets = exports.funding = exports.fees = exports.InfoClient = exports.executionCost = exports.writeReceiptDir = exports.verifyReceiptAt = exports.verifyReceipt = exports.snapshotRows = exports.simulateInputs = exports.sha256Json = exports.limitsPayload = exports.exampleInputs = exports.costBreakdownFromReceipt = exports.canonical = exports.buildReceiptFiles = exports.buildReceiptDir = exports.buildGuardedReceipt = exports.RECEIPT_VERSION = exports.RECEIPT_STATEMENT = exports.RECEIPT_KIND = exports.renderReceiptCard = exports.guardedSimulate = exports.wireCode = exports.survivalReport = exports.fromConfig = exports.defaultSnapshot = exports.defaultGuards = exports.GuardSession = exports.GuardLoosenError = exports.GuardConfigError = exports.GuardBlocked = exports.STALE_HALT_MS = exports.STALE_BLOCK_MS = exports.PRESETS = exports.HARD_MAX_SLIPPAGE_BPS = exports.HARD_MAX_ORDER_RATE = exports.HARD_MAX_OPEN_POSITIONS = exports.HARD_MAX_DAILY_LOSS_PCT = exports.CODES = void 0;
|
|
5
5
|
var guards_ts_1 = require("./guards.js");
|
|
6
6
|
Object.defineProperty(exports, "CODES", { enumerable: true, get: function () { return guards_ts_1.CODES; } });
|
|
7
7
|
Object.defineProperty(exports, "HARD_MAX_DAILY_LOSS_PCT", { enumerable: true, get: function () { return guards_ts_1.HARD_MAX_DAILY_LOSS_PCT; } });
|
|
@@ -25,12 +25,22 @@ Object.defineProperty(exports, "guardedSimulate", { enumerable: true, get: funct
|
|
|
25
25
|
var card_ts_1 = require("./card.js");
|
|
26
26
|
Object.defineProperty(exports, "renderReceiptCard", { enumerable: true, get: function () { return card_ts_1.renderReceiptCard; } });
|
|
27
27
|
var receipt_ts_1 = require("./receipt.js");
|
|
28
|
-
Object.defineProperty(exports, "costBreakdownFromReceipt", { enumerable: true, get: function () { return receipt_ts_1.costBreakdownFromReceipt; } });
|
|
29
28
|
Object.defineProperty(exports, "RECEIPT_KIND", { enumerable: true, get: function () { return receipt_ts_1.RECEIPT_KIND; } });
|
|
30
29
|
Object.defineProperty(exports, "RECEIPT_STATEMENT", { enumerable: true, get: function () { return receipt_ts_1.RECEIPT_STATEMENT; } });
|
|
30
|
+
Object.defineProperty(exports, "RECEIPT_VERSION", { enumerable: true, get: function () { return receipt_ts_1.RECEIPT_VERSION; } });
|
|
31
|
+
Object.defineProperty(exports, "buildGuardedReceipt", { enumerable: true, get: function () { return receipt_ts_1.buildGuardedReceipt; } });
|
|
32
|
+
Object.defineProperty(exports, "buildReceiptDir", { enumerable: true, get: function () { return receipt_ts_1.buildReceiptDir; } });
|
|
33
|
+
Object.defineProperty(exports, "buildReceiptFiles", { enumerable: true, get: function () { return receipt_ts_1.buildReceiptFiles; } });
|
|
31
34
|
Object.defineProperty(exports, "canonical", { enumerable: true, get: function () { return receipt_ts_1.canonical; } });
|
|
35
|
+
Object.defineProperty(exports, "costBreakdownFromReceipt", { enumerable: true, get: function () { return receipt_ts_1.costBreakdownFromReceipt; } });
|
|
36
|
+
Object.defineProperty(exports, "exampleInputs", { enumerable: true, get: function () { return receipt_ts_1.exampleInputs; } });
|
|
37
|
+
Object.defineProperty(exports, "limitsPayload", { enumerable: true, get: function () { return receipt_ts_1.limitsPayload; } });
|
|
32
38
|
Object.defineProperty(exports, "sha256Json", { enumerable: true, get: function () { return receipt_ts_1.sha256Json; } });
|
|
39
|
+
Object.defineProperty(exports, "simulateInputs", { enumerable: true, get: function () { return receipt_ts_1.simulateInputs; } });
|
|
40
|
+
Object.defineProperty(exports, "snapshotRows", { enumerable: true, get: function () { return receipt_ts_1.snapshotRows; } });
|
|
33
41
|
Object.defineProperty(exports, "verifyReceipt", { enumerable: true, get: function () { return receipt_ts_1.verifyReceipt; } });
|
|
42
|
+
Object.defineProperty(exports, "verifyReceiptAt", { enumerable: true, get: function () { return receipt_ts_1.verifyReceiptAt; } });
|
|
43
|
+
Object.defineProperty(exports, "writeReceiptDir", { enumerable: true, get: function () { return receipt_ts_1.writeReceiptDir; } });
|
|
34
44
|
var costs_ts_1 = require("./vendor/costs.js");
|
|
35
45
|
Object.defineProperty(exports, "executionCost", { enumerable: true, get: function () { return costs_ts_1.executionCost; } });
|
|
36
46
|
var info_ts_1 = require("./vendor/info.js");
|
package/dist/cjs/receipt.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
/** Re-derive a simulation receipt. The check is verified and reproducible. */
|
|
2
|
+
import { GuardSession, type Guards, type MarketSnapshot } from "./guards.ts";
|
|
3
|
+
import { type GuardedSimulateResult } from "./guarded.ts";
|
|
2
4
|
import { type CostBreakdown } from "./vendor/costs.ts";
|
|
3
5
|
export declare const RECEIPT_STATEMENT = "verified and reproducible";
|
|
4
6
|
export declare const RECEIPT_KIND = "perpbrain.sim-receipt";
|
|
@@ -11,3 +13,33 @@ export declare function verifyReceipt(receipt: unknown, manifest: Uint8Array, in
|
|
|
11
13
|
export declare function canonical(value: unknown): string;
|
|
12
14
|
export declare function sha256Json(value: unknown): string;
|
|
13
15
|
export declare function costBreakdownFromReceipt(receipt: unknown): CostBreakdown;
|
|
16
|
+
export interface BuiltReceipt {
|
|
17
|
+
receipt: Record<string, unknown>;
|
|
18
|
+
manifest: Record<string, unknown>;
|
|
19
|
+
receiptBytes: Uint8Array;
|
|
20
|
+
manifestBytes: Uint8Array;
|
|
21
|
+
inputsBytes: Uint8Array;
|
|
22
|
+
}
|
|
23
|
+
export declare function exampleInputs(): Record<string, unknown>;
|
|
24
|
+
export declare function limitsPayload(limits: Guards): Record<string, unknown>;
|
|
25
|
+
export declare function snapshotRows(snapshot: MarketSnapshot): Record<string, unknown>[];
|
|
26
|
+
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;
|
|
28
|
+
export declare function writeReceiptDir(directory: string, built: BuiltReceipt): string;
|
|
29
|
+
export declare function buildReceiptDir(directory: string, inputs?: Record<string, unknown>, limits?: Guards | null, snapshot?: MarketSnapshot | null): string;
|
|
30
|
+
/**
|
|
31
|
+
* Write a verifiable receipt from a successful `guardedSimulate` result.
|
|
32
|
+
*
|
|
33
|
+
* Verification reruns the unguarded simulator on the raw inputs, so the
|
|
34
|
+
* hashed result is `simulateInputs`, not the guarded result object. Guard
|
|
35
|
+
* metadata attached to that object (`guardPreset`, `limits`, `limitsHash`,
|
|
36
|
+
* `effectiveLimitsPerCoin`, `loosened`, `marketSnapshotId`, `guardViolations`)
|
|
37
|
+
* must not be hashed. The market snapshot defaults to `defaultSnapshot`; an
|
|
38
|
+
* empty snapshot list would refuse coins as `coin_not_allowed`.
|
|
39
|
+
*
|
|
40
|
+
* Receipt inputs use snake_case (`bar_index`, `time_ms`), even though the
|
|
41
|
+
* TypeScript `Decision` / `Bar` types are camelCase.
|
|
42
|
+
*/
|
|
43
|
+
export declare function buildGuardedReceipt(directory: string, inputs: Record<string, unknown>, result: GuardedSimulateResult | Record<string, unknown>, session: GuardSession, snapshot?: MarketSnapshot | null): string;
|
|
44
|
+
/** Read a receipt.json file, or a directory that contains one, and check it. */
|
|
45
|
+
export declare function verifyReceiptAt(path: string): VerifyReport;
|
package/dist/cjs/receipt.js
CHANGED
|
@@ -6,7 +6,18 @@ exports.verifyReceipt = verifyReceipt;
|
|
|
6
6
|
exports.canonical = canonical;
|
|
7
7
|
exports.sha256Json = sha256Json;
|
|
8
8
|
exports.costBreakdownFromReceipt = costBreakdownFromReceipt;
|
|
9
|
+
exports.exampleInputs = exampleInputs;
|
|
10
|
+
exports.limitsPayload = limitsPayload;
|
|
11
|
+
exports.snapshotRows = snapshotRows;
|
|
12
|
+
exports.simulateInputs = simulateInputs;
|
|
13
|
+
exports.buildReceiptFiles = buildReceiptFiles;
|
|
14
|
+
exports.writeReceiptDir = writeReceiptDir;
|
|
15
|
+
exports.buildReceiptDir = buildReceiptDir;
|
|
16
|
+
exports.buildGuardedReceipt = buildGuardedReceipt;
|
|
17
|
+
exports.verifyReceiptAt = verifyReceiptAt;
|
|
9
18
|
const node_crypto_1 = require("node:crypto");
|
|
19
|
+
const node_fs_1 = require("node:fs");
|
|
20
|
+
const node_path_1 = require("node:path");
|
|
10
21
|
const guards_ts_1 = require("./guards.js");
|
|
11
22
|
const guarded_ts_1 = require("./guarded.js");
|
|
12
23
|
const simDefaults_ts_1 = require("./vendor/simDefaults.js");
|
|
@@ -77,6 +88,190 @@ function costBreakdownFromReceipt(receipt) {
|
|
|
77
88
|
}
|
|
78
89
|
return runSim(inputs, (0, simDefaults_ts_1.receiptProfile)(body.version, body.result)).cost_breakdown;
|
|
79
90
|
}
|
|
91
|
+
/** UTF-8 JSON with sorted keys and no extra space, plus a trailing newline. */
|
|
92
|
+
function canonicalFileBytes(value) {
|
|
93
|
+
return Buffer.from(`${canonical(value)}\n`, "utf8");
|
|
94
|
+
}
|
|
95
|
+
/** Indented JSON with a trailing newline, for the receipt and manifest files. */
|
|
96
|
+
function prettyBytes(value) {
|
|
97
|
+
return Buffer.from(`${JSON.stringify(sortValue(value), null, 2)}\n`, "utf8");
|
|
98
|
+
}
|
|
99
|
+
function exampleInputs() {
|
|
100
|
+
const bar = { open: "100", high: "100", low: "100", close: "100" };
|
|
101
|
+
return {
|
|
102
|
+
market: "ETH",
|
|
103
|
+
decision: { bar_index: 0, side: "long", size: "0.01", stop: null, target: null },
|
|
104
|
+
bars: [bar, bar],
|
|
105
|
+
book: { bids: [{ px: "100", sz: "5" }], asks: [{ px: "100", sz: "5" }] },
|
|
106
|
+
fee_version: null,
|
|
107
|
+
funding: [],
|
|
108
|
+
funding_interval_ms: simulate_ts_1.HL_FUNDING_INTERVAL_MS,
|
|
109
|
+
guard_context: { leverage: "1", open_positions: 1, daily_loss_usd: "0", age_ms: 0 },
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function limitsPayload(limits) {
|
|
113
|
+
return {
|
|
114
|
+
allowed_coins: [...limits.allowedCoins],
|
|
115
|
+
daily_loss_pct: limits.dailyLossPct,
|
|
116
|
+
loosened: limits.loosened,
|
|
117
|
+
max_leverage: limits.maxLeverage,
|
|
118
|
+
max_notional_usd: limits.maxNotionalUsd,
|
|
119
|
+
max_open_positions: limits.maxOpenPositions,
|
|
120
|
+
max_slippage_bps: limits.maxSlippageBps,
|
|
121
|
+
order_rate_per_sec: limits.orderRatePerSec,
|
|
122
|
+
preset: limits.preset,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function snapshotRows(snapshot) {
|
|
126
|
+
return snapshot.coins.map((coin) => ({
|
|
127
|
+
max_leverage: coin.maxLeverage,
|
|
128
|
+
name: coin.name,
|
|
129
|
+
open_interest: coin.openInterest,
|
|
130
|
+
}));
|
|
131
|
+
}
|
|
132
|
+
function simulateInputs(inputs) {
|
|
133
|
+
// Receipts store the snake_case wire form; do not hash the camelCase runtime object.
|
|
134
|
+
return wireResult(runSim(inputs));
|
|
135
|
+
}
|
|
136
|
+
function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
|
|
137
|
+
const inputsBytes = canonicalFileBytes(inputs);
|
|
138
|
+
const dataSnapshotId = sha256Bytes(inputsBytes);
|
|
139
|
+
const limitsHash = sha256Json(limits);
|
|
140
|
+
const marketSnapshotId = sha256Json(marketSnapshot);
|
|
141
|
+
const resultSha256 = sha256Json(result);
|
|
142
|
+
const manifest = {
|
|
143
|
+
data_snapshot_id: dataSnapshotId,
|
|
144
|
+
files: [{ file: "inputs.json", rows: 1, sha256: dataSnapshotId }],
|
|
145
|
+
limits_hash: limitsHash,
|
|
146
|
+
market_snapshot_id: marketSnapshotId,
|
|
147
|
+
result_sha256: resultSha256,
|
|
148
|
+
};
|
|
149
|
+
const manifestBytes = prettyBytes(manifest);
|
|
150
|
+
const receipt = {
|
|
151
|
+
data_snapshot_id: dataSnapshotId,
|
|
152
|
+
inputs,
|
|
153
|
+
kind: exports.RECEIPT_KIND,
|
|
154
|
+
label: "SIMULATED",
|
|
155
|
+
limits,
|
|
156
|
+
limits_hash: limitsHash,
|
|
157
|
+
manifest_sha256: sha256Bytes(manifestBytes),
|
|
158
|
+
market_snapshot: marketSnapshot,
|
|
159
|
+
market_snapshot_id: marketSnapshotId,
|
|
160
|
+
raw_ref: "inputs.json",
|
|
161
|
+
result,
|
|
162
|
+
result_sha256: resultSha256,
|
|
163
|
+
statement: exports.RECEIPT_STATEMENT,
|
|
164
|
+
version: exports.RECEIPT_VERSION,
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
receipt,
|
|
168
|
+
manifest,
|
|
169
|
+
receiptBytes: prettyBytes(receipt),
|
|
170
|
+
manifestBytes,
|
|
171
|
+
inputsBytes,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function writeReceiptDir(directory, built) {
|
|
175
|
+
(0, node_fs_1.mkdirSync)(directory, { recursive: true });
|
|
176
|
+
(0, node_fs_1.writeFileSync)((0, node_path_1.join)(directory, "inputs.json"), built.inputsBytes);
|
|
177
|
+
(0, node_fs_1.writeFileSync)((0, node_path_1.join)(directory, "manifest.json"), built.manifestBytes);
|
|
178
|
+
const receiptPath = (0, node_path_1.join)(directory, "receipt.json");
|
|
179
|
+
(0, node_fs_1.writeFileSync)(receiptPath, built.receiptBytes);
|
|
180
|
+
return receiptPath;
|
|
181
|
+
}
|
|
182
|
+
function acceptInputs(inputs, session) {
|
|
183
|
+
(0, guarded_ts_1.guardedSimulate)(requiredString(inputs.market, "market"), decisionOf(inputs.decision), barsOf(inputs.bars), bookOf(inputs.book), feeOf(inputs.fee_version), contextOf(inputs.guard_context), session.limits.preset, session, fundingOf(inputs.funding), intervalOf(inputs.funding_interval_ms));
|
|
184
|
+
}
|
|
185
|
+
function buildReceiptDir(directory, inputs = exampleInputs(), limits = null, snapshot = null) {
|
|
186
|
+
const session = limits === null ? guards_ts_1.GuardSession.fromConfig() : new guards_ts_1.GuardSession(limits);
|
|
187
|
+
const market = snapshot ?? (0, guards_ts_1.defaultSnapshot)();
|
|
188
|
+
const hashed = simulateInputs(inputs);
|
|
189
|
+
acceptInputs(inputs, session);
|
|
190
|
+
return writeReceiptDir(directory, buildReceiptFiles(inputs, hashed, limitsPayload(session.limits), snapshotRows(market)));
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Write a verifiable receipt from a successful `guardedSimulate` result.
|
|
194
|
+
*
|
|
195
|
+
* Verification reruns the unguarded simulator on the raw inputs, so the
|
|
196
|
+
* hashed result is `simulateInputs`, not the guarded result object. Guard
|
|
197
|
+
* metadata attached to that object (`guardPreset`, `limits`, `limitsHash`,
|
|
198
|
+
* `effectiveLimitsPerCoin`, `loosened`, `marketSnapshotId`, `guardViolations`)
|
|
199
|
+
* must not be hashed. The market snapshot defaults to `defaultSnapshot`; an
|
|
200
|
+
* empty snapshot list would refuse coins as `coin_not_allowed`.
|
|
201
|
+
*
|
|
202
|
+
* Receipt inputs use snake_case (`bar_index`, `time_ms`), even though the
|
|
203
|
+
* TypeScript `Decision` / `Bar` types are camelCase.
|
|
204
|
+
*/
|
|
205
|
+
function buildGuardedReceipt(directory, inputs, result, session, snapshot = null) {
|
|
206
|
+
const body = result;
|
|
207
|
+
if (body.label !== "SIMULATED") {
|
|
208
|
+
throw new Error("result must be a SIMULATED guardedSimulate outcome");
|
|
209
|
+
}
|
|
210
|
+
const violations = body.guardViolations ?? body.guard_violations;
|
|
211
|
+
if (Array.isArray(violations) && violations.length > 0) {
|
|
212
|
+
throw new Error("blocked simulate results cannot be written as a verified receipt");
|
|
213
|
+
}
|
|
214
|
+
const market = snapshot ?? (0, guards_ts_1.defaultSnapshot)();
|
|
215
|
+
const hashed = simulateInputs(inputs);
|
|
216
|
+
acceptInputs(inputs, session);
|
|
217
|
+
return writeReceiptDir(directory, buildReceiptFiles(inputs, hashed, limitsPayload(session.limits), snapshotRows(market)));
|
|
218
|
+
}
|
|
219
|
+
function insideDirectory(root, ref) {
|
|
220
|
+
if (ref === "" || ref.includes("\0")) {
|
|
221
|
+
throw new Error("raw_ref must stay inside the receipt directory");
|
|
222
|
+
}
|
|
223
|
+
const candidate = ref;
|
|
224
|
+
if (candidate.startsWith("/") || candidate.split(/[\\/]/).includes("..")) {
|
|
225
|
+
throw new Error("raw_ref must stay inside the receipt directory");
|
|
226
|
+
}
|
|
227
|
+
return (0, node_path_1.join)(root, candidate);
|
|
228
|
+
}
|
|
229
|
+
/** Read a receipt.json file, or a directory that contains one, and check it. */
|
|
230
|
+
function verifyReceiptAt(path) {
|
|
231
|
+
const receiptFile = (0, node_fs_1.existsSync)(path) && (0, node_fs_1.statSync)(path).isDirectory() ? (0, node_path_1.join)(path, "receipt.json") : path;
|
|
232
|
+
if (!(0, node_fs_1.existsSync)(receiptFile) || !(0, node_fs_1.statSync)(receiptFile).isFile()) {
|
|
233
|
+
return report(["receipt.json missing"]);
|
|
234
|
+
}
|
|
235
|
+
let loaded;
|
|
236
|
+
try {
|
|
237
|
+
loaded = JSON.parse((0, node_fs_1.readFileSync)(receiptFile, "utf8"));
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
return report(["receipt json mismatch"]);
|
|
241
|
+
}
|
|
242
|
+
const receipt = asObject(loaded);
|
|
243
|
+
if (receipt === null) {
|
|
244
|
+
return report(["receipt mismatch"]);
|
|
245
|
+
}
|
|
246
|
+
const root = (0, node_path_1.dirname)(receiptFile);
|
|
247
|
+
const missing = [];
|
|
248
|
+
const manifestPath = (0, node_path_1.join)(root, "manifest.json");
|
|
249
|
+
const manifest = (0, node_fs_1.existsSync)(manifestPath) && (0, node_fs_1.statSync)(manifestPath).isFile() ? (0, node_fs_1.readFileSync)(manifestPath) : null;
|
|
250
|
+
if (manifest === null) {
|
|
251
|
+
missing.push("manifest missing");
|
|
252
|
+
}
|
|
253
|
+
let inputs = Buffer.alloc(0);
|
|
254
|
+
const rawRef = receipt.raw_ref;
|
|
255
|
+
if (typeof rawRef !== "string") {
|
|
256
|
+
missing.push("raw_ref mismatch");
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
try {
|
|
260
|
+
const rawPath = insideDirectory(root, rawRef);
|
|
261
|
+
if ((0, node_fs_1.existsSync)(rawPath) && (0, node_fs_1.statSync)(rawPath).isFile()) {
|
|
262
|
+
inputs = (0, node_fs_1.readFileSync)(rawPath);
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
missing.push(`${rawRef} missing`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
missing.push("raw_ref mismatch");
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const checked = verifyReceipt(receipt, manifest ?? Buffer.alloc(0), inputs);
|
|
273
|
+
return report([...missing, ...checked.mismatches]);
|
|
274
|
+
}
|
|
80
275
|
function checkIdentity(receipt, mismatches) {
|
|
81
276
|
const version = receipt.version;
|
|
82
277
|
if (typeof version !== "number" || !Number.isInteger(version) || (version !== 1 && version !== 2 && version !== 3 && version !== 4 && version !== 5)) {
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -4,7 +4,8 @@ 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 { RECEIPT_KIND, RECEIPT_STATEMENT, RECEIPT_VERSION, buildGuardedReceipt, buildReceiptDir, buildReceiptFiles, canonical, costBreakdownFromReceipt, exampleInputs, limitsPayload, sha256Json, simulateInputs, snapshotRows, verifyReceipt, verifyReceiptAt, writeReceiptDir, } from "./receipt.ts";
|
|
8
|
+
export type { BuiltReceipt } from "./receipt.ts";
|
|
8
9
|
export { executionCost } from "./vendor/costs.ts";
|
|
9
10
|
export type { CostBreakdown } from "./vendor/costs.ts";
|
|
10
11
|
export type { VerifyReport } from "./receipt.ts";
|
package/dist/esm/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
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 { RECEIPT_KIND, RECEIPT_STATEMENT, RECEIPT_VERSION, buildGuardedReceipt, buildReceiptDir, buildReceiptFiles, canonical, costBreakdownFromReceipt, exampleInputs, limitsPayload, sha256Json, simulateInputs, snapshotRows, verifyReceipt, verifyReceiptAt, writeReceiptDir, } from "./receipt.js";
|
|
6
6
|
export { executionCost } from "./vendor/costs.js";
|
|
7
7
|
export { InfoClient } from "./vendor/info.js";
|
|
8
8
|
export { fees, funding, markets, orderBook, positions } from "./vendor/queries.js";
|
package/dist/esm/receipt.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
/** Re-derive a simulation receipt. The check is verified and reproducible. */
|
|
2
|
+
import { GuardSession, type Guards, type MarketSnapshot } from "./guards.ts";
|
|
3
|
+
import { type GuardedSimulateResult } from "./guarded.ts";
|
|
2
4
|
import { type CostBreakdown } from "./vendor/costs.ts";
|
|
3
5
|
export declare const RECEIPT_STATEMENT = "verified and reproducible";
|
|
4
6
|
export declare const RECEIPT_KIND = "perpbrain.sim-receipt";
|
|
@@ -11,3 +13,33 @@ export declare function verifyReceipt(receipt: unknown, manifest: Uint8Array, in
|
|
|
11
13
|
export declare function canonical(value: unknown): string;
|
|
12
14
|
export declare function sha256Json(value: unknown): string;
|
|
13
15
|
export declare function costBreakdownFromReceipt(receipt: unknown): CostBreakdown;
|
|
16
|
+
export interface BuiltReceipt {
|
|
17
|
+
receipt: Record<string, unknown>;
|
|
18
|
+
manifest: Record<string, unknown>;
|
|
19
|
+
receiptBytes: Uint8Array;
|
|
20
|
+
manifestBytes: Uint8Array;
|
|
21
|
+
inputsBytes: Uint8Array;
|
|
22
|
+
}
|
|
23
|
+
export declare function exampleInputs(): Record<string, unknown>;
|
|
24
|
+
export declare function limitsPayload(limits: Guards): Record<string, unknown>;
|
|
25
|
+
export declare function snapshotRows(snapshot: MarketSnapshot): Record<string, unknown>[];
|
|
26
|
+
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;
|
|
28
|
+
export declare function writeReceiptDir(directory: string, built: BuiltReceipt): string;
|
|
29
|
+
export declare function buildReceiptDir(directory: string, inputs?: Record<string, unknown>, limits?: Guards | null, snapshot?: MarketSnapshot | null): string;
|
|
30
|
+
/**
|
|
31
|
+
* Write a verifiable receipt from a successful `guardedSimulate` result.
|
|
32
|
+
*
|
|
33
|
+
* Verification reruns the unguarded simulator on the raw inputs, so the
|
|
34
|
+
* hashed result is `simulateInputs`, not the guarded result object. Guard
|
|
35
|
+
* metadata attached to that object (`guardPreset`, `limits`, `limitsHash`,
|
|
36
|
+
* `effectiveLimitsPerCoin`, `loosened`, `marketSnapshotId`, `guardViolations`)
|
|
37
|
+
* must not be hashed. The market snapshot defaults to `defaultSnapshot`; an
|
|
38
|
+
* empty snapshot list would refuse coins as `coin_not_allowed`.
|
|
39
|
+
*
|
|
40
|
+
* Receipt inputs use snake_case (`bar_index`, `time_ms`), even though the
|
|
41
|
+
* TypeScript `Decision` / `Bar` types are camelCase.
|
|
42
|
+
*/
|
|
43
|
+
export declare function buildGuardedReceipt(directory: string, inputs: Record<string, unknown>, result: GuardedSimulateResult | Record<string, unknown>, session: GuardSession, snapshot?: MarketSnapshot | null): string;
|
|
44
|
+
/** Read a receipt.json file, or a directory that contains one, and check it. */
|
|
45
|
+
export declare function verifyReceiptAt(path: string): VerifyReport;
|
package/dist/esm/receipt.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/** Re-derive a simulation receipt. The check is verified and reproducible. */
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
|
-
import {
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { GuardBlocked, GuardSession, defaultSnapshot, snapshotFromCoins, } from "./guards.js";
|
|
4
6
|
import { guardedSimulate } from "./guarded.js";
|
|
5
7
|
import { CURRENT_SIM_DEFAULTS, receiptProfile, simDefaults } from "./vendor/simDefaults.js";
|
|
6
8
|
import { studyAccounting } from "./study.js";
|
|
@@ -70,6 +72,190 @@ export function costBreakdownFromReceipt(receipt) {
|
|
|
70
72
|
}
|
|
71
73
|
return runSim(inputs, receiptProfile(body.version, body.result)).cost_breakdown;
|
|
72
74
|
}
|
|
75
|
+
/** UTF-8 JSON with sorted keys and no extra space, plus a trailing newline. */
|
|
76
|
+
function canonicalFileBytes(value) {
|
|
77
|
+
return Buffer.from(`${canonical(value)}\n`, "utf8");
|
|
78
|
+
}
|
|
79
|
+
/** Indented JSON with a trailing newline, for the receipt and manifest files. */
|
|
80
|
+
function prettyBytes(value) {
|
|
81
|
+
return Buffer.from(`${JSON.stringify(sortValue(value), null, 2)}\n`, "utf8");
|
|
82
|
+
}
|
|
83
|
+
export function exampleInputs() {
|
|
84
|
+
const bar = { open: "100", high: "100", low: "100", close: "100" };
|
|
85
|
+
return {
|
|
86
|
+
market: "ETH",
|
|
87
|
+
decision: { bar_index: 0, side: "long", size: "0.01", stop: null, target: null },
|
|
88
|
+
bars: [bar, bar],
|
|
89
|
+
book: { bids: [{ px: "100", sz: "5" }], asks: [{ px: "100", sz: "5" }] },
|
|
90
|
+
fee_version: null,
|
|
91
|
+
funding: [],
|
|
92
|
+
funding_interval_ms: HL_FUNDING_INTERVAL_MS,
|
|
93
|
+
guard_context: { leverage: "1", open_positions: 1, daily_loss_usd: "0", age_ms: 0 },
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
export function limitsPayload(limits) {
|
|
97
|
+
return {
|
|
98
|
+
allowed_coins: [...limits.allowedCoins],
|
|
99
|
+
daily_loss_pct: limits.dailyLossPct,
|
|
100
|
+
loosened: limits.loosened,
|
|
101
|
+
max_leverage: limits.maxLeverage,
|
|
102
|
+
max_notional_usd: limits.maxNotionalUsd,
|
|
103
|
+
max_open_positions: limits.maxOpenPositions,
|
|
104
|
+
max_slippage_bps: limits.maxSlippageBps,
|
|
105
|
+
order_rate_per_sec: limits.orderRatePerSec,
|
|
106
|
+
preset: limits.preset,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
export function snapshotRows(snapshot) {
|
|
110
|
+
return snapshot.coins.map((coin) => ({
|
|
111
|
+
max_leverage: coin.maxLeverage,
|
|
112
|
+
name: coin.name,
|
|
113
|
+
open_interest: coin.openInterest,
|
|
114
|
+
}));
|
|
115
|
+
}
|
|
116
|
+
export function simulateInputs(inputs) {
|
|
117
|
+
// Receipts store the snake_case wire form; do not hash the camelCase runtime object.
|
|
118
|
+
return wireResult(runSim(inputs));
|
|
119
|
+
}
|
|
120
|
+
export function buildReceiptFiles(inputs, result, limits, marketSnapshot) {
|
|
121
|
+
const inputsBytes = canonicalFileBytes(inputs);
|
|
122
|
+
const dataSnapshotId = sha256Bytes(inputsBytes);
|
|
123
|
+
const limitsHash = sha256Json(limits);
|
|
124
|
+
const marketSnapshotId = sha256Json(marketSnapshot);
|
|
125
|
+
const resultSha256 = sha256Json(result);
|
|
126
|
+
const manifest = {
|
|
127
|
+
data_snapshot_id: dataSnapshotId,
|
|
128
|
+
files: [{ file: "inputs.json", rows: 1, sha256: dataSnapshotId }],
|
|
129
|
+
limits_hash: limitsHash,
|
|
130
|
+
market_snapshot_id: marketSnapshotId,
|
|
131
|
+
result_sha256: resultSha256,
|
|
132
|
+
};
|
|
133
|
+
const manifestBytes = prettyBytes(manifest);
|
|
134
|
+
const receipt = {
|
|
135
|
+
data_snapshot_id: dataSnapshotId,
|
|
136
|
+
inputs,
|
|
137
|
+
kind: RECEIPT_KIND,
|
|
138
|
+
label: "SIMULATED",
|
|
139
|
+
limits,
|
|
140
|
+
limits_hash: limitsHash,
|
|
141
|
+
manifest_sha256: sha256Bytes(manifestBytes),
|
|
142
|
+
market_snapshot: marketSnapshot,
|
|
143
|
+
market_snapshot_id: marketSnapshotId,
|
|
144
|
+
raw_ref: "inputs.json",
|
|
145
|
+
result,
|
|
146
|
+
result_sha256: resultSha256,
|
|
147
|
+
statement: RECEIPT_STATEMENT,
|
|
148
|
+
version: RECEIPT_VERSION,
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
receipt,
|
|
152
|
+
manifest,
|
|
153
|
+
receiptBytes: prettyBytes(receipt),
|
|
154
|
+
manifestBytes,
|
|
155
|
+
inputsBytes,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
export function writeReceiptDir(directory, built) {
|
|
159
|
+
mkdirSync(directory, { recursive: true });
|
|
160
|
+
writeFileSync(join(directory, "inputs.json"), built.inputsBytes);
|
|
161
|
+
writeFileSync(join(directory, "manifest.json"), built.manifestBytes);
|
|
162
|
+
const receiptPath = join(directory, "receipt.json");
|
|
163
|
+
writeFileSync(receiptPath, built.receiptBytes);
|
|
164
|
+
return receiptPath;
|
|
165
|
+
}
|
|
166
|
+
function acceptInputs(inputs, session) {
|
|
167
|
+
guardedSimulate(requiredString(inputs.market, "market"), decisionOf(inputs.decision), barsOf(inputs.bars), bookOf(inputs.book), feeOf(inputs.fee_version), contextOf(inputs.guard_context), session.limits.preset, session, fundingOf(inputs.funding), intervalOf(inputs.funding_interval_ms));
|
|
168
|
+
}
|
|
169
|
+
export function buildReceiptDir(directory, inputs = exampleInputs(), limits = null, snapshot = null) {
|
|
170
|
+
const session = limits === null ? GuardSession.fromConfig() : new GuardSession(limits);
|
|
171
|
+
const market = snapshot ?? defaultSnapshot();
|
|
172
|
+
const hashed = simulateInputs(inputs);
|
|
173
|
+
acceptInputs(inputs, session);
|
|
174
|
+
return writeReceiptDir(directory, buildReceiptFiles(inputs, hashed, limitsPayload(session.limits), snapshotRows(market)));
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Write a verifiable receipt from a successful `guardedSimulate` result.
|
|
178
|
+
*
|
|
179
|
+
* Verification reruns the unguarded simulator on the raw inputs, so the
|
|
180
|
+
* hashed result is `simulateInputs`, not the guarded result object. Guard
|
|
181
|
+
* metadata attached to that object (`guardPreset`, `limits`, `limitsHash`,
|
|
182
|
+
* `effectiveLimitsPerCoin`, `loosened`, `marketSnapshotId`, `guardViolations`)
|
|
183
|
+
* must not be hashed. The market snapshot defaults to `defaultSnapshot`; an
|
|
184
|
+
* empty snapshot list would refuse coins as `coin_not_allowed`.
|
|
185
|
+
*
|
|
186
|
+
* Receipt inputs use snake_case (`bar_index`, `time_ms`), even though the
|
|
187
|
+
* TypeScript `Decision` / `Bar` types are camelCase.
|
|
188
|
+
*/
|
|
189
|
+
export function buildGuardedReceipt(directory, inputs, result, session, snapshot = null) {
|
|
190
|
+
const body = result;
|
|
191
|
+
if (body.label !== "SIMULATED") {
|
|
192
|
+
throw new Error("result must be a SIMULATED guardedSimulate outcome");
|
|
193
|
+
}
|
|
194
|
+
const violations = body.guardViolations ?? body.guard_violations;
|
|
195
|
+
if (Array.isArray(violations) && violations.length > 0) {
|
|
196
|
+
throw new Error("blocked simulate results cannot be written as a verified receipt");
|
|
197
|
+
}
|
|
198
|
+
const market = snapshot ?? defaultSnapshot();
|
|
199
|
+
const hashed = simulateInputs(inputs);
|
|
200
|
+
acceptInputs(inputs, session);
|
|
201
|
+
return writeReceiptDir(directory, buildReceiptFiles(inputs, hashed, limitsPayload(session.limits), snapshotRows(market)));
|
|
202
|
+
}
|
|
203
|
+
function insideDirectory(root, ref) {
|
|
204
|
+
if (ref === "" || ref.includes("\0")) {
|
|
205
|
+
throw new Error("raw_ref must stay inside the receipt directory");
|
|
206
|
+
}
|
|
207
|
+
const candidate = ref;
|
|
208
|
+
if (candidate.startsWith("/") || candidate.split(/[\\/]/).includes("..")) {
|
|
209
|
+
throw new Error("raw_ref must stay inside the receipt directory");
|
|
210
|
+
}
|
|
211
|
+
return join(root, candidate);
|
|
212
|
+
}
|
|
213
|
+
/** Read a receipt.json file, or a directory that contains one, and check it. */
|
|
214
|
+
export function verifyReceiptAt(path) {
|
|
215
|
+
const receiptFile = existsSync(path) && statSync(path).isDirectory() ? join(path, "receipt.json") : path;
|
|
216
|
+
if (!existsSync(receiptFile) || !statSync(receiptFile).isFile()) {
|
|
217
|
+
return report(["receipt.json missing"]);
|
|
218
|
+
}
|
|
219
|
+
let loaded;
|
|
220
|
+
try {
|
|
221
|
+
loaded = JSON.parse(readFileSync(receiptFile, "utf8"));
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
return report(["receipt json mismatch"]);
|
|
225
|
+
}
|
|
226
|
+
const receipt = asObject(loaded);
|
|
227
|
+
if (receipt === null) {
|
|
228
|
+
return report(["receipt mismatch"]);
|
|
229
|
+
}
|
|
230
|
+
const root = dirname(receiptFile);
|
|
231
|
+
const missing = [];
|
|
232
|
+
const manifestPath = join(root, "manifest.json");
|
|
233
|
+
const manifest = existsSync(manifestPath) && statSync(manifestPath).isFile() ? readFileSync(manifestPath) : null;
|
|
234
|
+
if (manifest === null) {
|
|
235
|
+
missing.push("manifest missing");
|
|
236
|
+
}
|
|
237
|
+
let inputs = Buffer.alloc(0);
|
|
238
|
+
const rawRef = receipt.raw_ref;
|
|
239
|
+
if (typeof rawRef !== "string") {
|
|
240
|
+
missing.push("raw_ref mismatch");
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
try {
|
|
244
|
+
const rawPath = insideDirectory(root, rawRef);
|
|
245
|
+
if (existsSync(rawPath) && statSync(rawPath).isFile()) {
|
|
246
|
+
inputs = readFileSync(rawPath);
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
missing.push(`${rawRef} missing`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
missing.push("raw_ref mismatch");
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const checked = verifyReceipt(receipt, manifest ?? Buffer.alloc(0), inputs);
|
|
257
|
+
return report([...missing, ...checked.mismatches]);
|
|
258
|
+
}
|
|
73
259
|
function checkIdentity(receipt, mismatches) {
|
|
74
260
|
const version = receipt.version;
|
|
75
261
|
if (typeof version !== "number" || !Number.isInteger(version) || (version !== 1 && version !== 2 && version !== 3 && version !== 4 && version !== 5)) {
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@perpbrain/sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
7
7
|
},
|
|
8
8
|
"description": "TypeScript SDK for PERPBRAIN read tools, simulation, and the MCP launcher. Verified and reproducible. Phase 1 has no live trading.",
|
|
9
|
+
"author": "GVNR DAO LLC <info@perpbrain.com> (https://perpbrain.com)",
|
|
9
10
|
"license": "MIT",
|
|
10
11
|
"homepage": "https://perpbrain.com/",
|
|
11
12
|
"repository": {
|