@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.
- package/dist/cjs/fillLink.d.ts +77 -0
- package/dist/cjs/fillLink.js +328 -0
- package/dist/cjs/fundingRecon.d.ts +16 -0
- package/dist/cjs/fundingRecon.js +228 -0
- package/dist/cjs/index.d.ts +4 -0
- package/dist/cjs/index.js +17 -1
- package/dist/cjs/receipt.js +9 -0
- package/dist/esm/fillLink.d.ts +77 -0
- package/dist/esm/fillLink.js +318 -0
- package/dist/esm/fundingRecon.d.ts +16 -0
- package/dist/esm/fundingRecon.js +223 -0
- package/dist/esm/index.d.ts +4 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/receipt.js +9 -0
- package/package.json +1 -1
|
@@ -0,0 +1,223 @@
|
|
|
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
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
export const RECON_KIND = "perpbrain.funding-recon-receipt";
|
|
11
|
+
export const RECON_VERSION = 1;
|
|
12
|
+
class Dec {
|
|
13
|
+
coeff;
|
|
14
|
+
exp;
|
|
15
|
+
constructor(coeff, exp) {
|
|
16
|
+
this.coeff = coeff;
|
|
17
|
+
this.exp = exp;
|
|
18
|
+
}
|
|
19
|
+
static from(value) {
|
|
20
|
+
if (value instanceof Dec) {
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
if (typeof value === "bigint") {
|
|
24
|
+
return new Dec(value, 0);
|
|
25
|
+
}
|
|
26
|
+
if (typeof value === "number" && Number.isInteger(value)) {
|
|
27
|
+
return new Dec(BigInt(value), 0);
|
|
28
|
+
}
|
|
29
|
+
const s = String(value).trim();
|
|
30
|
+
if (!/^-?\d+(\.\d+)?$/.test(s)) {
|
|
31
|
+
throw new Error(`decimal required: ${s}`);
|
|
32
|
+
}
|
|
33
|
+
const neg = s.startsWith("-");
|
|
34
|
+
const body = neg ? s.slice(1) : s;
|
|
35
|
+
const i = body.indexOf(".");
|
|
36
|
+
const digits = i === -1 ? body : body.slice(0, i) + body.slice(i + 1);
|
|
37
|
+
const exp = i === -1 ? 0 : -(body.length - i - 1);
|
|
38
|
+
return new Dec(BigInt(digits) * (neg ? -1n : 1n), exp);
|
|
39
|
+
}
|
|
40
|
+
align(other) {
|
|
41
|
+
if (this.exp === other.exp) {
|
|
42
|
+
return [this.coeff, other.coeff, this.exp];
|
|
43
|
+
}
|
|
44
|
+
if (this.exp < other.exp) {
|
|
45
|
+
return [this.coeff, other.coeff * 10n ** BigInt(other.exp - this.exp), this.exp];
|
|
46
|
+
}
|
|
47
|
+
return [this.coeff * 10n ** BigInt(this.exp - other.exp), other.coeff, other.exp];
|
|
48
|
+
}
|
|
49
|
+
add(other) {
|
|
50
|
+
const [a, b, e] = this.align(other);
|
|
51
|
+
return new Dec(a + b, e);
|
|
52
|
+
}
|
|
53
|
+
sub(other) {
|
|
54
|
+
const [a, b, e] = this.align(other);
|
|
55
|
+
return new Dec(a - b, e);
|
|
56
|
+
}
|
|
57
|
+
/** Exact division by 10^places with Python's ideal exponent (that of the dividend). */
|
|
58
|
+
divPow10(places) {
|
|
59
|
+
let c = this.coeff;
|
|
60
|
+
let e = this.exp - places;
|
|
61
|
+
while (e < this.exp && c % 10n === 0n) {
|
|
62
|
+
c /= 10n;
|
|
63
|
+
e += 1;
|
|
64
|
+
}
|
|
65
|
+
return new Dec(c, e);
|
|
66
|
+
}
|
|
67
|
+
abs() {
|
|
68
|
+
return this.coeff < 0n ? new Dec(-this.coeff, this.exp) : this;
|
|
69
|
+
}
|
|
70
|
+
cmp(other) {
|
|
71
|
+
const [a, b] = this.align(other);
|
|
72
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
73
|
+
}
|
|
74
|
+
/** Python's str(Decimal): plain notation unless the exponent is positive or very small. */
|
|
75
|
+
toString() {
|
|
76
|
+
const neg = this.coeff < 0n;
|
|
77
|
+
let digits = (neg ? -this.coeff : this.coeff).toString();
|
|
78
|
+
const adjusted = this.exp + digits.length - 1;
|
|
79
|
+
let body;
|
|
80
|
+
if (this.exp <= 0 && adjusted >= -6) {
|
|
81
|
+
if (this.exp === 0) {
|
|
82
|
+
body = digits;
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
const places = -this.exp;
|
|
86
|
+
if (digits.length <= places) {
|
|
87
|
+
digits = digits.padStart(places + 1, "0");
|
|
88
|
+
}
|
|
89
|
+
const i = digits.length - places;
|
|
90
|
+
body = `${digits.slice(0, i)}.${digits.slice(i)}`;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
const mantissa = digits.length > 1 ? `${digits[0]}.${digits.slice(1)}` : digits;
|
|
95
|
+
body = `${mantissa}E${adjusted > 0 ? "+" : ""}${adjusted}`;
|
|
96
|
+
}
|
|
97
|
+
return (neg ? "-" : "") + body;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function num(value, what) {
|
|
101
|
+
if (typeof value !== "number" || !Number.isInteger(value)) {
|
|
102
|
+
throw new Error(`${what} must be an integer`);
|
|
103
|
+
}
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
function fundingInWindow(rows, startMs, endMs) {
|
|
107
|
+
let total = Dec.from(0);
|
|
108
|
+
for (const row of rows) {
|
|
109
|
+
const t = num(row.time, "time");
|
|
110
|
+
if (startMs < t && t <= endMs) {
|
|
111
|
+
total = total.add(Dec.from(row.usdc));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return total;
|
|
115
|
+
}
|
|
116
|
+
export function reconcile(inputs) {
|
|
117
|
+
const coin = inputs.coin;
|
|
118
|
+
const rows = (inputs.funding_rows ?? []).filter((r) => r.coin === coin);
|
|
119
|
+
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"));
|
|
120
|
+
const tol = Dec.from(inputs.tolerance_usdc);
|
|
121
|
+
const startMs = num(inputs.start_ms, "start_ms");
|
|
122
|
+
const endMs = num(inputs.end_ms, "end_ms");
|
|
123
|
+
const windows = [];
|
|
124
|
+
let prev = startMs;
|
|
125
|
+
let inWindows = Dec.from(0);
|
|
126
|
+
let measuredTotal = Dec.from(0);
|
|
127
|
+
let differing = 0;
|
|
128
|
+
for (const m of meas) {
|
|
129
|
+
const t = num(m.time_ms, "time_ms");
|
|
130
|
+
if (t < prev) {
|
|
131
|
+
throw new Error("measurement before window start");
|
|
132
|
+
}
|
|
133
|
+
const venue = fundingInWindow(rows, prev, t);
|
|
134
|
+
const count = rows.filter((r) => prev < num(r.time, "time") && num(r.time, "time") <= t).length;
|
|
135
|
+
const measured = Dec.from(num(m.measured_micro, "measured_micro")).divPow10(6);
|
|
136
|
+
const diff = measured.sub(venue);
|
|
137
|
+
const status = diff.abs().cmp(tol) <= 0 ? "MATCH" : "DIFF";
|
|
138
|
+
if (status === "DIFF") {
|
|
139
|
+
differing += 1;
|
|
140
|
+
}
|
|
141
|
+
inWindows = inWindows.add(venue);
|
|
142
|
+
measuredTotal = measuredTotal.add(measured);
|
|
143
|
+
windows.push({
|
|
144
|
+
from_ms: prev,
|
|
145
|
+
to_ms: t,
|
|
146
|
+
block: m.block,
|
|
147
|
+
tx: m.tx,
|
|
148
|
+
measured_usdc: measured.toString(),
|
|
149
|
+
venue_usdc: venue.toString(),
|
|
150
|
+
venue_rows: count,
|
|
151
|
+
diff_usdc: diff.toString(),
|
|
152
|
+
status,
|
|
153
|
+
});
|
|
154
|
+
prev = t;
|
|
155
|
+
}
|
|
156
|
+
const last = meas.length > 0 ? num(meas[meas.length - 1].time_ms, "time_ms") : startMs;
|
|
157
|
+
const before = meas.length > 0 ? fundingInWindow(rows, startMs - 1, startMs) : Dec.from(0);
|
|
158
|
+
const after = meas.length > 0 ? fundingInWindow(rows, last, endMs) : fundingInWindow(rows, startMs, endMs);
|
|
159
|
+
return {
|
|
160
|
+
windows,
|
|
161
|
+
matched: windows.length - differing,
|
|
162
|
+
differing,
|
|
163
|
+
measured_total_usdc: measuredTotal.toString(),
|
|
164
|
+
venue_total_in_windows_usdc: inWindows.toString(),
|
|
165
|
+
venue_before_first_usdc: before.toString(),
|
|
166
|
+
venue_after_last_usdc: after.toString(),
|
|
167
|
+
venue_total_usdc: fundingInWindow(rows, startMs - 1, endMs).toString(),
|
|
168
|
+
status: windows.length === 0 ? "NO_MEASUREMENTS" : differing > 0 ? "DIFFERENCES" : "RECONCILED",
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function sortValue(value) {
|
|
172
|
+
if (Array.isArray(value)) {
|
|
173
|
+
return value.map(sortValue);
|
|
174
|
+
}
|
|
175
|
+
if (value !== null && typeof value === "object") {
|
|
176
|
+
const out = {};
|
|
177
|
+
for (const key of Object.keys(value).sort()) {
|
|
178
|
+
out[key] = sortValue(value[key]);
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
return value;
|
|
183
|
+
}
|
|
184
|
+
/** Python's json.dumps(sort_keys=True, separators=(",", ":"), ensure_ascii=True). */
|
|
185
|
+
function canonicalAscii(value) {
|
|
186
|
+
return JSON.stringify(sortValue(value)).replace(/[\u007f-\uffff]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
187
|
+
}
|
|
188
|
+
function sha256(data) {
|
|
189
|
+
return createHash("sha256").update(data).digest("hex");
|
|
190
|
+
}
|
|
191
|
+
export function verifyReconReceipt(receipt, inputsBytes) {
|
|
192
|
+
const body = typeof receipt === "object" && receipt !== null && !Array.isArray(receipt)
|
|
193
|
+
? receipt
|
|
194
|
+
: null;
|
|
195
|
+
if (body === null) {
|
|
196
|
+
return { status: "MISMATCH", mismatches: ["receipt mismatch"] };
|
|
197
|
+
}
|
|
198
|
+
const problems = [];
|
|
199
|
+
if (body.kind !== RECON_KIND) {
|
|
200
|
+
problems.push("kind");
|
|
201
|
+
}
|
|
202
|
+
if (body.version !== RECON_VERSION) {
|
|
203
|
+
problems.push("version");
|
|
204
|
+
}
|
|
205
|
+
if (body.inputs_sha256 !== sha256(inputsBytes)) {
|
|
206
|
+
problems.push("inputs_sha256");
|
|
207
|
+
}
|
|
208
|
+
let result;
|
|
209
|
+
try {
|
|
210
|
+
const inputs = JSON.parse(Buffer.from(inputsBytes).toString("utf8"));
|
|
211
|
+
result = reconcile(inputs);
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
return { status: "MISMATCH", mismatches: [...problems, `inputs: ${error.message}`] };
|
|
215
|
+
}
|
|
216
|
+
if (canonicalAscii(body.result) !== canonicalAscii(result)) {
|
|
217
|
+
problems.push("result");
|
|
218
|
+
}
|
|
219
|
+
if (body.result_sha256 !== sha256(canonicalAscii(result))) {
|
|
220
|
+
problems.push("result_sha256");
|
|
221
|
+
}
|
|
222
|
+
return { status: problems.length > 0 ? "MISMATCH" : "VERIFIED", mismatches: problems };
|
|
223
|
+
}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/esm/index.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
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 { RECON_KIND, RECON_VERSION, reconcile, verifyReconReceipt } from "./fundingRecon.js";
|
|
6
|
+
export { LINK_KIND, LINK_VERSION, buildLink, computeLink, linkInputs, normaliseSelector, selectFills, simFromReceipt, verifyLink, } from "./fillLink.js";
|
|
5
7
|
export { RECEIPT_KIND, RECEIPT_STATEMENT, RECEIPT_VERSION, buildGuardedReceipt, buildReceiptDir, buildReceiptFiles, canonical, costBreakdownFromReceipt, exampleInputs, limitsPayload, sha256Json, simulateInputs, snapshotRows, verifyReceipt, verifyReceiptAt, writeReceiptDir, } from "./receipt.js";
|
|
6
8
|
export { executionCost } from "./vendor/costs.js";
|
|
7
9
|
export { InfoClient } from "./vendor/info.js";
|
package/dist/esm/receipt.js
CHANGED
|
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { GuardBlocked, GuardSession, defaultSnapshot, snapshotFromCoins, } from "./guards.js";
|
|
6
|
+
import { RECON_KIND, verifyReconReceipt } from "./fundingRecon.js";
|
|
6
7
|
import { guardedSimulate } from "./guarded.js";
|
|
7
8
|
import { CURRENT_SIM_DEFAULTS, receiptProfile, simDefaults } from "./vendor/simDefaults.js";
|
|
8
9
|
import { studyAccounting } from "./study.js";
|
|
@@ -228,6 +229,14 @@ export function verifyReceiptAt(path) {
|
|
|
228
229
|
return report(["receipt mismatch"]);
|
|
229
230
|
}
|
|
230
231
|
const root = dirname(receiptFile);
|
|
232
|
+
if (receipt.kind === RECON_KIND) {
|
|
233
|
+
// A funding-reconciliation receipt is checked against inputs.json beside it.
|
|
234
|
+
const inputsPath = join(root, "inputs.json");
|
|
235
|
+
if (!existsSync(inputsPath) || !statSync(inputsPath).isFile()) {
|
|
236
|
+
return report(["inputs.json missing (download it next to receipt.json)"]);
|
|
237
|
+
}
|
|
238
|
+
return verifyReconReceipt(receipt, readFileSync(inputsPath));
|
|
239
|
+
}
|
|
231
240
|
const missing = [];
|
|
232
241
|
const manifestPath = join(root, "manifest.json");
|
|
233
242
|
const manifest = existsSync(manifestPath) && statSync(manifestPath).isFile() ? readFileSync(manifestPath) : null;
|