@perpbrain/sdk 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/fillLink.d.ts +23 -3
- package/dist/cjs/fillLink.js +568 -12
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +6 -2
- package/dist/esm/fillLink.d.ts +23 -3
- package/dist/esm/fillLink.js +564 -11
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/package.json +1 -1
package/dist/esm/fillLink.js
CHANGED
|
@@ -11,7 +11,10 @@ import { canonical } from "./receipt.js";
|
|
|
11
11
|
import { formatDecimal, parseDecimal } from "./vendor/fees.js";
|
|
12
12
|
export const LINK_KIND = "perpbrain.execution-link";
|
|
13
13
|
export const LINK_VERSION = 1;
|
|
14
|
+
export const LINK_VERSION_V2 = 2;
|
|
14
15
|
const STATEMENT = "verified and reproducible";
|
|
16
|
+
const STATEMENT_V2 = "integrity verified and reproducible; the fill is associated with the receipt by selector, " +
|
|
17
|
+
"coin and side only; see correspondence for the declared-policy checks";
|
|
15
18
|
const SCALE = 10n ** 18n;
|
|
16
19
|
const HASH = /^0x[0-9a-f]{64}$/;
|
|
17
20
|
const ZERO_HASH = `0x${"0".repeat(64)}`;
|
|
@@ -153,7 +156,7 @@ export function linkInputs(receipt, rows, options) {
|
|
|
153
156
|
if (!ADDRESS.test(account)) {
|
|
154
157
|
throw new Error("user must be a 0x-prefixed 20-byte address");
|
|
155
158
|
}
|
|
156
|
-
|
|
159
|
+
const out = {
|
|
157
160
|
network: options.network,
|
|
158
161
|
user: account,
|
|
159
162
|
by: options.by,
|
|
@@ -162,8 +165,15 @@ export function linkInputs(receipt, rows, options) {
|
|
|
162
165
|
sim: simFromReceipt(receipt, options.tradeIndex ?? 0),
|
|
163
166
|
fills: selectFills(rows, options.by, options.value),
|
|
164
167
|
};
|
|
168
|
+
if (options.policy !== undefined) {
|
|
169
|
+
v2Contract(receipt);
|
|
170
|
+
v2Contract(options.policy);
|
|
171
|
+
out.policy = JSON.parse(canonical(options.policy));
|
|
172
|
+
out.bounds = receiptBounds(receipt);
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
165
175
|
}
|
|
166
|
-
|
|
176
|
+
function computeBase(inputs) {
|
|
167
177
|
const sim = inputs.sim;
|
|
168
178
|
const by = inputs.by;
|
|
169
179
|
const value = normaliseSelector(by, inputs.value);
|
|
@@ -237,14 +247,539 @@ export function computeLink(inputs) {
|
|
|
237
247
|
time_to_first_fill_ms: first === null ? null : first - sim.decision_time_ms,
|
|
238
248
|
};
|
|
239
249
|
}
|
|
240
|
-
|
|
250
|
+
// --- correspondence (v2): declared-policy checks, never a proof of causation -------------------
|
|
251
|
+
// Port of perpbrain_read.sim.fill_link v2. Shared vectors: fixtures/fill_link/v2-vectors.json.
|
|
252
|
+
const POLICY_KEYS = new Set([
|
|
253
|
+
"sim_provenance",
|
|
254
|
+
"precommit_ref",
|
|
255
|
+
"clock_source",
|
|
256
|
+
"time_unit",
|
|
257
|
+
"clock_uncertainty_ms",
|
|
258
|
+
"window_after_ms",
|
|
259
|
+
"size_mode",
|
|
260
|
+
"size_rel_tol",
|
|
261
|
+
"price_tol_bps",
|
|
262
|
+
"bar_time_convention",
|
|
263
|
+
]);
|
|
264
|
+
const PROVENANCE = ["derived_from_fill", "independent_precommit", "unknown"];
|
|
265
|
+
const CAVEATS = [
|
|
266
|
+
"association is by selector, coin and side; it is not proof the fill executed this decision",
|
|
267
|
+
"decision time is bound to the receipt only when the record is built and verified with the " +
|
|
268
|
+
"receipt; otherwise it is an unverified input and no positive verdict is given",
|
|
269
|
+
"sim_provenance, precommit_ref and the whole policy are declared by the caller, possibly " +
|
|
270
|
+
"after the fact; this module never verifies a precommit reference, so provenance is always " +
|
|
271
|
+
"declared and unverified",
|
|
272
|
+
"CONSISTENT_WITH_DECLARED_POLICY means only that the declared numeric checks passed; " +
|
|
273
|
+
"tolerances are the caller's, not justified here, and it does not make metrics comparable",
|
|
274
|
+
];
|
|
275
|
+
const MS_LOW = 10 ** 12;
|
|
276
|
+
const MS_HIGH = 10 ** 13;
|
|
277
|
+
function stripWs(value) {
|
|
278
|
+
return value.replace(/^[ \t\n\r]+|[ \t\n\r]+$/g, "");
|
|
279
|
+
}
|
|
280
|
+
const MAX_SAFE = Number.MAX_SAFE_INTEGER;
|
|
281
|
+
/** v2 inputs are canonical in both SDKs only when every number is a JSON integer within the
|
|
282
|
+
* double-safe range and every object key is ASCII. Anything else is refused, never coerced. */
|
|
283
|
+
export function checkV2Value(value) {
|
|
284
|
+
v2Contract(value);
|
|
285
|
+
}
|
|
286
|
+
const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
|
|
287
|
+
function v2Contract(value) {
|
|
288
|
+
if (value === null || typeof value === "boolean") {
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
if (typeof value === "string") {
|
|
292
|
+
if (LONE_SURROGATE.test(value)) {
|
|
293
|
+
throw new Error("v2 inputs must not contain unpaired surrogates");
|
|
294
|
+
}
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
if (typeof value === "number") {
|
|
298
|
+
if (!Number.isInteger(value)) {
|
|
299
|
+
throw new Error("v2 inputs must not contain non-integer or float-formatted numbers");
|
|
300
|
+
}
|
|
301
|
+
if (Math.abs(value) > MAX_SAFE) {
|
|
302
|
+
throw new Error("v2 inputs must keep integers within the double-safe range");
|
|
303
|
+
}
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (Array.isArray(value)) {
|
|
307
|
+
value.forEach(v2Contract);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (typeof value === "object") {
|
|
311
|
+
for (const [k, v] of Object.entries(value)) {
|
|
312
|
+
if (!/^[\x00-\x7f]*$/.test(k)) {
|
|
313
|
+
throw new Error("v2 inputs must use ASCII object keys");
|
|
314
|
+
}
|
|
315
|
+
v2Contract(v);
|
|
316
|
+
}
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
throw new Error("v2 inputs must be plain JSON");
|
|
320
|
+
}
|
|
321
|
+
/** Float spellings (1.0, 1e3) parse differently across languages: refused in the raw bytes. */
|
|
322
|
+
export function checkV2Text(raw) {
|
|
323
|
+
const stripped = raw.replace(/"(?:\\.|[^"\\])*"/g, '""');
|
|
324
|
+
for (const token of stripped.match(/-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g) ?? []) {
|
|
325
|
+
if (/[.eE]/.test(token)) {
|
|
326
|
+
throw new Error("v2 inputs must not contain float-formatted numbers");
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
function isInt(value) {
|
|
331
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
332
|
+
}
|
|
333
|
+
function tryFixed(value) {
|
|
334
|
+
try {
|
|
335
|
+
return fixed(value);
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function policyInt(policy, key) {
|
|
342
|
+
const v = policy[key];
|
|
343
|
+
return isInt(v) && v >= 0 ? v : null;
|
|
344
|
+
}
|
|
345
|
+
function policyDec(policy, key) {
|
|
346
|
+
const out = tryFixed(policy[key]);
|
|
347
|
+
return out !== null && out >= 0n ? out : null;
|
|
348
|
+
}
|
|
349
|
+
function uniq(items) {
|
|
350
|
+
return [...new Set(items)];
|
|
351
|
+
}
|
|
352
|
+
function feeUnassessed(r) {
|
|
353
|
+
const token = r.feeToken;
|
|
354
|
+
return (token !== undefined && token !== null && token !== "USDC") || r.fee === undefined || r.fee === null;
|
|
355
|
+
}
|
|
356
|
+
/** Structural facts taken from the receipt: the smallest positive bar gap and where the decision
|
|
357
|
+
* time came from ("bar", "book", or "unknown" when timed bars exist but the decision bar is not). */
|
|
358
|
+
export function receiptBounds(receipt) {
|
|
359
|
+
const inputs = obj(obj(receipt)?.inputs);
|
|
360
|
+
const rawBars = inputs?.bars;
|
|
361
|
+
const bars = Array.isArray(rawBars) ? rawBars : [];
|
|
362
|
+
const times = [];
|
|
363
|
+
for (const b of bars) {
|
|
364
|
+
const t = obj(b)?.time_ms;
|
|
365
|
+
if (isInt(t)) {
|
|
366
|
+
times.push(t);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const gaps = [];
|
|
370
|
+
for (let n = 1; n < times.length; n++) {
|
|
371
|
+
if (times[n] > times[n - 1]) {
|
|
372
|
+
gaps.push(times[n] - times[n - 1]);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
const index = obj(inputs?.decision)?.bar_index;
|
|
376
|
+
const bar = isInt(index) && index >= 0 && index < bars.length ? bars[index] : null;
|
|
377
|
+
const barTimed = isInt(obj(bar)?.time_ms);
|
|
378
|
+
return {
|
|
379
|
+
bar_interval_ms: gaps.length > 0 ? Math.min(...gaps) : null,
|
|
380
|
+
time_field: barTimed ? "bar" : times.length > 0 ? "unknown" : "book",
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
function availability(inputs, policy, na) {
|
|
384
|
+
const bounds = obj(inputs.bounds);
|
|
385
|
+
const field = bounds?.time_field;
|
|
386
|
+
const interval = bounds?.bar_interval_ms;
|
|
387
|
+
const decision = inputs.sim.decision_time_ms;
|
|
388
|
+
if (!isInt(decision)) {
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
if (field === "book") {
|
|
392
|
+
return decision;
|
|
393
|
+
}
|
|
394
|
+
if (field !== "bar") {
|
|
395
|
+
na.push("DECISION_TIME_FIELD_UNKNOWN");
|
|
396
|
+
return null;
|
|
397
|
+
}
|
|
398
|
+
const conv = policy.bar_time_convention;
|
|
399
|
+
if (conv === "close") {
|
|
400
|
+
return decision;
|
|
401
|
+
}
|
|
402
|
+
if (conv === "open") {
|
|
403
|
+
if (isInt(interval) && interval > 0) {
|
|
404
|
+
return decision + interval;
|
|
405
|
+
}
|
|
406
|
+
na.push("BAR_INTERVAL_UNKNOWN_FOR_OPEN_CONVENTION");
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
na.push("BAR_TIME_CONVENTION_MISSING");
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
function partial(inputs, bound) {
|
|
413
|
+
const rawPolicy = obj(inputs.policy);
|
|
414
|
+
const policy = rawPolicy ?? {};
|
|
415
|
+
const na = ["INPUT_MALFORMED"];
|
|
416
|
+
const bad = [];
|
|
417
|
+
if (!bound) {
|
|
418
|
+
na.push("DECISION_TIME_NOT_BOUND_TO_RECEIPT");
|
|
419
|
+
}
|
|
420
|
+
const avail = availability(inputs, policy, na);
|
|
421
|
+
const unc = policyInt(policy, "clock_uncertainty_ms");
|
|
422
|
+
const after = policyInt(policy, "window_after_ms");
|
|
423
|
+
const tol = policyDec(policy, "size_rel_tol");
|
|
424
|
+
const rows = Array.isArray(inputs.fills) ? inputs.fills : [];
|
|
425
|
+
const sim = obj(inputs.sim) ?? {};
|
|
426
|
+
const sideHl = sim.side === "buy" ? "B" : "A";
|
|
427
|
+
let sizes = 0n;
|
|
428
|
+
const tids = [];
|
|
429
|
+
rows.forEach((raw, n) => {
|
|
430
|
+
const r = obj(raw);
|
|
431
|
+
if (r === null) {
|
|
432
|
+
na.push(`ROW_${n}_NOT_AN_OBJECT`);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const t = r.time;
|
|
436
|
+
const tOk = isInt(t) && t >= MS_LOW && t < MS_HIGH;
|
|
437
|
+
if (!tOk) {
|
|
438
|
+
na.push(`ROW_${n}_MALFORMED:time`);
|
|
439
|
+
}
|
|
440
|
+
else if (unc !== null) {
|
|
441
|
+
const floor = avail !== null ? avail : sim.decision_time_ms;
|
|
442
|
+
if (isInt(floor) && t < floor - unc) {
|
|
443
|
+
bad.push("FILL_BEFORE_DECISION");
|
|
444
|
+
}
|
|
445
|
+
else if (avail !== null && after !== null && t > avail + after) {
|
|
446
|
+
bad.push("FILL_AFTER_WINDOW");
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
for (const key of ["sz", "px"]) {
|
|
450
|
+
const v = tryFixed(r[key]);
|
|
451
|
+
if (v === null || v <= 0n) {
|
|
452
|
+
na.push(`ROW_${n}_MALFORMED:${key}`);
|
|
453
|
+
}
|
|
454
|
+
else if (key === "sz") {
|
|
455
|
+
sizes += v;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
if (r.feeToken === undefined || r.feeToken === null || r.feeToken === "USDC") {
|
|
459
|
+
if (tryFixed(r.fee) === null) {
|
|
460
|
+
na.push(`ROW_${n}_MALFORMED:fee`);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
const tid = r.tid;
|
|
464
|
+
if (!isInt(tid)) {
|
|
465
|
+
na.push(`ROW_${n}_MALFORMED:tid`);
|
|
466
|
+
}
|
|
467
|
+
else if (tids.includes(tid)) {
|
|
468
|
+
bad.push("DUPLICATE_OR_MISSING_FILL_ID");
|
|
469
|
+
}
|
|
470
|
+
else {
|
|
471
|
+
tids.push(tid);
|
|
472
|
+
}
|
|
473
|
+
if (typeof r.coin === "string" && r.coin !== sim.market) {
|
|
474
|
+
bad.push("BASE_MISMATCHED_TRADE");
|
|
475
|
+
}
|
|
476
|
+
if (typeof r.side === "string" && r.side !== sideHl) {
|
|
477
|
+
bad.push("BASE_MISMATCHED_TRADE");
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
const simSz = tryFixed(sim.size) ?? 0n;
|
|
481
|
+
if (simSz > 0n && tol !== null && tol < SCALE && sizes > (simSz * (SCALE + tol)) / SCALE) {
|
|
482
|
+
bad.push("SIZE_OUTSIDE_TOLERANCE");
|
|
483
|
+
}
|
|
484
|
+
return {
|
|
485
|
+
verdict: bad.length > 0 ? "INCONSISTENT" : "NOT_ASSESSED",
|
|
486
|
+
inconsistent_reasons: uniq(bad),
|
|
487
|
+
not_assessed_reasons: uniq(na),
|
|
488
|
+
checks_run: ["partial_row_checks"],
|
|
489
|
+
checks_not_run: ["full_correspondence", "underfill_size", "price", "fees"],
|
|
490
|
+
decision_time_source: bound ? "receipt_verified" : "inputs_unbound",
|
|
491
|
+
provenance_status: "DECLARED_UNVERIFIED",
|
|
492
|
+
malformed_reason: "MALFORMED_INPUT",
|
|
493
|
+
caveats: CAVEATS,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function correspondence(inputs, base, bound) {
|
|
497
|
+
const rawPolicy = obj(inputs.policy);
|
|
498
|
+
const policy = rawPolicy ?? {};
|
|
499
|
+
const na = [];
|
|
500
|
+
const bad = [];
|
|
501
|
+
const ran = [];
|
|
502
|
+
const skipped = [];
|
|
503
|
+
if (rawPolicy === null) {
|
|
504
|
+
na.push("POLICY_MISSING");
|
|
505
|
+
}
|
|
506
|
+
if (!bound) {
|
|
507
|
+
na.push("DECISION_TIME_NOT_BOUND_TO_RECEIPT");
|
|
508
|
+
}
|
|
509
|
+
const bounds = obj(inputs.bounds);
|
|
510
|
+
const interval = bounds?.bar_interval_ms;
|
|
511
|
+
if (bounds === null) {
|
|
512
|
+
na.push("BOUNDS_MISSING");
|
|
513
|
+
}
|
|
514
|
+
for (const k of Object.keys(policy).sort()) {
|
|
515
|
+
if (!POLICY_KEYS.has(k)) {
|
|
516
|
+
na.push(`POLICY_UNKNOWN_KEY:${k}`);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
const prov = policy.sim_provenance;
|
|
520
|
+
if (typeof prov !== "string" || !PROVENANCE.includes(prov)) {
|
|
521
|
+
na.push("SIM_PROVENANCE_MISSING");
|
|
522
|
+
}
|
|
523
|
+
else if (prov === "derived_from_fill") {
|
|
524
|
+
na.push("SIM_DERIVED_FROM_FILL");
|
|
525
|
+
}
|
|
526
|
+
else if (prov === "unknown") {
|
|
527
|
+
na.push("SIM_PROVENANCE_UNKNOWN");
|
|
528
|
+
}
|
|
529
|
+
else if (!(typeof policy.precommit_ref === "string" && stripWs(policy.precommit_ref) !== "")) {
|
|
530
|
+
na.push("PRECOMMIT_REF_MISSING");
|
|
531
|
+
}
|
|
532
|
+
const clock = policy.clock_source;
|
|
533
|
+
if (!(typeof clock === "string" && stripWs(clock) !== "")) {
|
|
534
|
+
na.push("CLOCK_SOURCE_MISSING");
|
|
535
|
+
}
|
|
536
|
+
if (policy.time_unit !== "ms_utc") {
|
|
537
|
+
na.push("TIME_UNIT_NOT_MS_UTC");
|
|
538
|
+
}
|
|
539
|
+
const unc = policyInt(policy, "clock_uncertainty_ms");
|
|
540
|
+
const after = policyInt(policy, "window_after_ms");
|
|
541
|
+
if (unc === null) {
|
|
542
|
+
na.push("CLOCK_UNCERTAINTY_MISSING");
|
|
543
|
+
}
|
|
544
|
+
if (after === null) {
|
|
545
|
+
na.push("WINDOW_AFTER_MISSING");
|
|
546
|
+
}
|
|
547
|
+
else if (unc !== null && unc >= after) {
|
|
548
|
+
na.push("POLICY_NOT_DISCRIMINATING:uncertainty_not_below_window");
|
|
549
|
+
}
|
|
550
|
+
if (after !== null && !(isInt(interval) && interval > 0)) {
|
|
551
|
+
na.push("WINDOW_NOT_BOUNDED_BY_RECEIPT");
|
|
552
|
+
}
|
|
553
|
+
else if (after !== null && isInt(interval) && after > interval) {
|
|
554
|
+
na.push("POLICY_NOT_DISCRIMINATING:window_longer_than_receipt_bar_interval");
|
|
555
|
+
}
|
|
556
|
+
const mode = policy.size_mode;
|
|
557
|
+
if (mode === "scale_in") {
|
|
558
|
+
na.push("SIZE_MODE_UNSUPPORTED:scale_in");
|
|
559
|
+
}
|
|
560
|
+
else if (mode !== "single" && mode !== "aggregate") {
|
|
561
|
+
na.push("SIZE_MODE_MISSING");
|
|
562
|
+
}
|
|
563
|
+
const tol = policyDec(policy, "size_rel_tol");
|
|
564
|
+
if (tol === null) {
|
|
565
|
+
na.push("SIZE_TOLERANCE_MISSING");
|
|
566
|
+
}
|
|
567
|
+
else if (tol >= SCALE) {
|
|
568
|
+
na.push("POLICY_NOT_DISCRIMINATING:size_tolerance_at_least_100pct");
|
|
569
|
+
}
|
|
570
|
+
let priceTol = null;
|
|
571
|
+
if ("price_tol_bps" in policy) {
|
|
572
|
+
priceTol = policyDec(policy, "price_tol_bps");
|
|
573
|
+
if (priceTol === null) {
|
|
574
|
+
na.push("PRICE_TOLERANCE_INVALID");
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
const rows = inputs.fills;
|
|
578
|
+
const sim = inputs.sim;
|
|
579
|
+
if (base.status === "NO_FILLS") {
|
|
580
|
+
na.push("NO_FILLS");
|
|
581
|
+
}
|
|
582
|
+
else if (base.status !== "LINKED") {
|
|
583
|
+
bad.push(`BASE_${base.status}`);
|
|
584
|
+
}
|
|
585
|
+
const tids = rows.map((r) => r.tid);
|
|
586
|
+
if (tids.some((t) => !isInt(t))) {
|
|
587
|
+
bad.push("FILL_ID_INVALID");
|
|
588
|
+
}
|
|
589
|
+
else if (new Set(tids).size !== tids.length) {
|
|
590
|
+
bad.push("DUPLICATE_OR_MISSING_FILL_ID");
|
|
591
|
+
}
|
|
592
|
+
if (rows.some(feeUnassessed)) {
|
|
593
|
+
na.push("FEE_UNASSESSED");
|
|
594
|
+
}
|
|
595
|
+
for (const r of rows) {
|
|
596
|
+
const px = tryFixed(r.px);
|
|
597
|
+
if (px === null || px <= 0n) {
|
|
598
|
+
na.push("FILL_PRICE_NOT_POSITIVE");
|
|
599
|
+
break;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
const avail = availability(inputs, policy, na);
|
|
603
|
+
const decision = avail !== null ? avail : sim.decision_time_ms;
|
|
604
|
+
const times = rows.map((r) => r.time);
|
|
605
|
+
const stamps = [decision, ...times];
|
|
606
|
+
let ordering = "NOT_ASSESSED";
|
|
607
|
+
let timeOk = true;
|
|
608
|
+
if (stamps.some((t) => !isInt(t))) {
|
|
609
|
+
na.push("TIMESTAMP_MISSING");
|
|
610
|
+
timeOk = false;
|
|
611
|
+
}
|
|
612
|
+
else if (stamps.some((t) => t < MS_LOW || t >= MS_HIGH)) {
|
|
613
|
+
na.push("TIMESTAMP_UNIT_IMPLAUSIBLE");
|
|
614
|
+
timeOk = false;
|
|
615
|
+
}
|
|
616
|
+
if (timeOk && unc !== null) {
|
|
617
|
+
const ts = times;
|
|
618
|
+
const d = decision;
|
|
619
|
+
if (ts.some((t) => t < d - unc)) {
|
|
620
|
+
bad.push("FILL_BEFORE_DECISION");
|
|
621
|
+
ordering = "BEFORE";
|
|
622
|
+
}
|
|
623
|
+
else if (ts.some((t) => t < d + unc)) {
|
|
624
|
+
na.push("ORDERING_AMBIGUOUS_WITHIN_CLOCK_UNCERTAINTY");
|
|
625
|
+
ordering = "AMBIGUOUS_WITHIN_UNCERTAINTY";
|
|
626
|
+
}
|
|
627
|
+
else if (avail === null) {
|
|
628
|
+
ordering = "NOT_ASSESSED";
|
|
629
|
+
}
|
|
630
|
+
else {
|
|
631
|
+
ordering = "AFTER";
|
|
632
|
+
}
|
|
633
|
+
ran.push("ordering");
|
|
634
|
+
if (avail !== null && after !== null && ts.some((t) => t > d + after)) {
|
|
635
|
+
bad.push("FILL_AFTER_WINDOW");
|
|
636
|
+
}
|
|
637
|
+
if (after !== null && avail !== null) {
|
|
638
|
+
ran.push("window_after");
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
else {
|
|
642
|
+
skipped.push("ordering");
|
|
643
|
+
skipped.push("window_after");
|
|
644
|
+
}
|
|
645
|
+
const simSz = fixed(sim.size);
|
|
646
|
+
if (fixed(sim.price) <= 0n) {
|
|
647
|
+
na.push("SIM_PRICE_NOT_POSITIVE");
|
|
648
|
+
}
|
|
649
|
+
let sizesOk = simSz > 0n && rows.length > 0;
|
|
650
|
+
if (simSz <= 0n) {
|
|
651
|
+
na.push("SIM_SIZE_NOT_POSITIVE");
|
|
652
|
+
}
|
|
653
|
+
for (const r of rows) {
|
|
654
|
+
const sz = tryFixed(r.sz);
|
|
655
|
+
if (sz === null || sz <= 0n) {
|
|
656
|
+
na.push("FILL_SIZE_MISSING_OR_NOT_POSITIVE");
|
|
657
|
+
sizesOk = false;
|
|
658
|
+
break;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
if (sizesOk && tol !== null && (mode === "single" || mode === "aggregate")) {
|
|
662
|
+
const ratio = tdiv(fixed(base.size) * SCALE, simSz);
|
|
663
|
+
if (mode === "single" && rows.length !== 1) {
|
|
664
|
+
bad.push("MULTIPLE_FILLS_UNDER_SINGLE_MODE");
|
|
665
|
+
}
|
|
666
|
+
const dev = ratio - SCALE;
|
|
667
|
+
if ((dev < 0n ? -dev : dev) > tol) {
|
|
668
|
+
bad.push("SIZE_OUTSIDE_TOLERANCE");
|
|
669
|
+
}
|
|
670
|
+
ran.push("size");
|
|
671
|
+
}
|
|
672
|
+
else {
|
|
673
|
+
skipped.push("size");
|
|
674
|
+
}
|
|
675
|
+
if (priceTol !== null && rows.length > 0 && base.status === "LINKED" && fixed(sim.price) > 0n) {
|
|
676
|
+
const simPx = fixed(sim.price);
|
|
677
|
+
const diff = fixed(base.avg_px) - simPx;
|
|
678
|
+
const dev = tdiv((diff < 0n ? -diff : diff) * 10000n * SCALE, simPx);
|
|
679
|
+
if (dev > priceTol) {
|
|
680
|
+
bad.push("PRICE_OUTSIDE_TOLERANCE");
|
|
681
|
+
}
|
|
682
|
+
ran.push("price");
|
|
683
|
+
}
|
|
684
|
+
else {
|
|
685
|
+
skipped.push("price");
|
|
686
|
+
}
|
|
687
|
+
const verdict = bad.length > 0 ? "INCONSISTENT" : na.length > 0 ? "NOT_ASSESSED" : "CONSISTENT_WITH_DECLARED_POLICY";
|
|
688
|
+
return {
|
|
689
|
+
verdict,
|
|
690
|
+
inconsistent_reasons: uniq(bad),
|
|
691
|
+
not_assessed_reasons: uniq(na),
|
|
692
|
+
ordering,
|
|
693
|
+
checks_run: ran,
|
|
694
|
+
checks_not_run: skipped,
|
|
695
|
+
decision_time_ms: sim.decision_time_ms,
|
|
696
|
+
decision_available_ms: avail,
|
|
697
|
+
decision_time_source: bound ? "receipt_verified" : "inputs_unbound",
|
|
698
|
+
provenance_status: "DECLARED_UNVERIFIED",
|
|
699
|
+
receipt_bar_interval_ms: isInt(interval) ? interval : null,
|
|
700
|
+
policy: Object.keys(policy).length > 0 ? JSON.parse(canonical(policy)) : null,
|
|
701
|
+
caveats: CAVEATS,
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
/** v1 inputs (no `policy` key) give the v1 result unchanged and malformed rows throw, as in 0.2.1.
|
|
705
|
+
* v2 inputs add `correspondence`; malformed rows give a structured INVALID_INPUT result.
|
|
706
|
+
* `bound` is true only when the caller verified the inputs against the receipt. */
|
|
707
|
+
export function computeLink(inputs, bound = false) {
|
|
708
|
+
if (!("policy" in inputs)) {
|
|
709
|
+
return computeBase(inputs);
|
|
710
|
+
}
|
|
711
|
+
let out;
|
|
712
|
+
let corr;
|
|
713
|
+
try {
|
|
714
|
+
const base = computeBase(inputs);
|
|
715
|
+
out = { ...base };
|
|
716
|
+
if (inputs.fills.some(feeUnassessed)) {
|
|
717
|
+
out.fee_drag_usd = null;
|
|
718
|
+
out.fees_usdc = null;
|
|
719
|
+
out.fee_note = "FEE_TOKEN_UNSUPPORTED_OR_MISSING";
|
|
720
|
+
}
|
|
721
|
+
corr = correspondence(inputs, base, bound);
|
|
722
|
+
}
|
|
723
|
+
catch {
|
|
724
|
+
return {
|
|
725
|
+
status: "INVALID_INPUT",
|
|
726
|
+
problems: ["malformed input"],
|
|
727
|
+
correspondence: partial(inputs, bound),
|
|
728
|
+
metrics_comparable: false,
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
out.correspondence = corr;
|
|
732
|
+
out.metrics_comparable = false;
|
|
733
|
+
out.comparability_note = "NEVER_TRUE_WITHOUT_INDEPENDENTLY_VALIDATED_PROVENANCE";
|
|
734
|
+
return out;
|
|
735
|
+
}
|
|
736
|
+
function receiptBinding(inputs, receipt) {
|
|
737
|
+
try {
|
|
738
|
+
v2Contract(receipt);
|
|
739
|
+
}
|
|
740
|
+
catch (error) {
|
|
741
|
+
return [`receipt: ${error.message}`];
|
|
742
|
+
}
|
|
743
|
+
if (sha256(canonical(receipt)) !== inputs.receipt_sha256) {
|
|
744
|
+
return ["receipt does not match receipt_sha256"];
|
|
745
|
+
}
|
|
746
|
+
let sim;
|
|
747
|
+
try {
|
|
748
|
+
sim = simFromReceipt(receipt, inputs.sim.trade_index);
|
|
749
|
+
}
|
|
750
|
+
catch (error) {
|
|
751
|
+
return [`receipt: ${error.message}`];
|
|
752
|
+
}
|
|
753
|
+
const problems = [];
|
|
754
|
+
if (canonical(sim) !== canonical(inputs.sim)) {
|
|
755
|
+
problems.push("sim trade differs from the receipt");
|
|
756
|
+
}
|
|
757
|
+
if ("policy" in inputs && canonical(inputs.bounds ?? null) !== canonical(receiptBounds(receipt))) {
|
|
758
|
+
problems.push("bounds differ from the receipt");
|
|
759
|
+
}
|
|
760
|
+
return problems;
|
|
761
|
+
}
|
|
762
|
+
/** Without `receipt` a v2 link is built unbound: it can never be positive. */
|
|
763
|
+
export function buildLink(inputs, receipt) {
|
|
241
764
|
const raw = canonical(inputs);
|
|
242
|
-
const
|
|
765
|
+
const v2 = "policy" in inputs;
|
|
766
|
+
if (v2) {
|
|
767
|
+
v2Contract(inputs);
|
|
768
|
+
}
|
|
769
|
+
let bound = false;
|
|
770
|
+
if (v2 && receipt !== undefined) {
|
|
771
|
+
const problems = receiptBinding(inputs, receipt);
|
|
772
|
+
if (problems.length > 0) {
|
|
773
|
+
throw new Error(problems.join("; "));
|
|
774
|
+
}
|
|
775
|
+
bound = true;
|
|
776
|
+
}
|
|
777
|
+
const result = computeLink(inputs, bound);
|
|
243
778
|
const record = {
|
|
244
779
|
kind: LINK_KIND,
|
|
245
|
-
version: LINK_VERSION,
|
|
780
|
+
version: v2 ? LINK_VERSION_V2 : LINK_VERSION,
|
|
246
781
|
label: inputs.network === "mainnet" ? "MAINNET" : "TESTNET",
|
|
247
|
-
statement: STATEMENT,
|
|
782
|
+
statement: v2 ? STATEMENT_V2 : STATEMENT,
|
|
248
783
|
receipt_sha256: inputs.receipt_sha256,
|
|
249
784
|
user: inputs.user,
|
|
250
785
|
selector: { by: inputs.by, value: inputs.value },
|
|
@@ -258,23 +793,41 @@ export function buildLink(inputs) {
|
|
|
258
793
|
inputsBytes: Buffer.from(`${raw}\n`, "utf8"),
|
|
259
794
|
};
|
|
260
795
|
}
|
|
261
|
-
/** Re-hash the inputs, rerun the comparison and, given the receipt, check the binding.
|
|
796
|
+
/** Re-hash the inputs, rerun the comparison and, given the receipt, check the binding. A v2
|
|
797
|
+
* record that claims a receipt-bound decision time needs the receipt to verify. */
|
|
262
798
|
export function verifyLink(record, inputsBytes, receipt) {
|
|
263
799
|
const problems = [];
|
|
264
800
|
if (record.kind !== LINK_KIND) {
|
|
265
801
|
problems.push("kind");
|
|
266
802
|
}
|
|
267
|
-
if (record.version !== LINK_VERSION) {
|
|
268
|
-
problems.push("version");
|
|
269
|
-
}
|
|
270
803
|
let inputs;
|
|
271
804
|
let result;
|
|
272
805
|
try {
|
|
273
806
|
inputs = JSON.parse(Buffer.from(inputsBytes).toString("utf8"));
|
|
807
|
+
const v2 = "policy" in inputs;
|
|
808
|
+
if (v2) {
|
|
809
|
+
v2Contract(inputs);
|
|
810
|
+
checkV2Text(Buffer.from(inputsBytes).toString("utf8"));
|
|
811
|
+
}
|
|
812
|
+
if (record.version !== (v2 ? LINK_VERSION_V2 : LINK_VERSION)) {
|
|
813
|
+
problems.push("version");
|
|
814
|
+
}
|
|
274
815
|
if (sha256(canonical(inputs)) !== record.inputs_sha256) {
|
|
275
816
|
problems.push("inputs_sha256");
|
|
276
817
|
}
|
|
277
|
-
|
|
818
|
+
const claimed = obj(record.result);
|
|
819
|
+
const corr = obj(claimed?.correspondence);
|
|
820
|
+
const claimsBound = corr?.decision_time_source === "receipt_verified";
|
|
821
|
+
if (claimsBound && v2) {
|
|
822
|
+
if (receipt === undefined) {
|
|
823
|
+
problems.push("receipt required: record claims receipt-bound decision time");
|
|
824
|
+
}
|
|
825
|
+
else {
|
|
826
|
+
problems.push(...receiptBinding(inputs, receipt));
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
const bound = claimsBound && v2 && receipt !== undefined && problems.length === 0;
|
|
830
|
+
result = computeLink(inputs, bound);
|
|
278
831
|
}
|
|
279
832
|
catch (error) {
|
|
280
833
|
return {
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ export { FUNDING_COVERAGE, FUNDING_SCOPE, HOLDING_KIND, HOLDING_STATEMENT, HOLDI
|
|
|
12
12
|
export type { BuiltHolding, HoldingInputs, HoldingLeg, HoldingVerify } from "./holding.ts";
|
|
13
13
|
export { RECON_KIND, RECON_VERSION, reconcile, verifyReconReceipt } from "./fundingRecon.ts";
|
|
14
14
|
export type { ReconVerify } from "./fundingRecon.ts";
|
|
15
|
-
export { LINK_KIND, LINK_VERSION, buildLink, computeLink, linkInputs, normaliseSelector, selectFills, simFromReceipt, verifyLink, } from "./fillLink.ts";
|
|
15
|
+
export { LINK_KIND, LINK_VERSION, LINK_VERSION_V2, buildLink, checkV2Text, checkV2Value, computeLink, linkInputs, normaliseSelector, receiptBounds, selectFills, simFromReceipt, verifyLink, } from "./fillLink.ts";
|
|
16
16
|
export type { BuiltLink, LinkInputs, LinkNetwork, LinkResult, LinkSelector, LinkVerify, SimTrade, } from "./fillLink.ts";
|
|
17
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";
|
|
18
18
|
export type { BuiltReceipt } from "./receipt.ts";
|
package/dist/esm/index.js
CHANGED
|
@@ -6,7 +6,7 @@ export { CALIBRATION_KIND, CALIBRATION_VERSION, CALIBRATION_STATEMENT, MIN_SAMPL
|
|
|
6
6
|
export { CLIENT_META_ALLOWED_KEYS, CLIENT_META_MAX_CANONICAL_BYTES, attachClientMeta, makeEntry, validateClientMeta, } from "./clientMeta.js";
|
|
7
7
|
export { FUNDING_COVERAGE, FUNDING_SCOPE, HOLDING_KIND, HOLDING_STATEMENT, HOLDING_VERSION, VERIFY_SCOPE, buildHolding, computeHolding, verifyHolding, } from "./holding.js";
|
|
8
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";
|
|
9
|
+
export { LINK_KIND, LINK_VERSION, LINK_VERSION_V2, buildLink, checkV2Text, checkV2Value, computeLink, linkInputs, normaliseSelector, receiptBounds, selectFills, simFromReceipt, verifyLink, } from "./fillLink.js";
|
|
10
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";
|
|
11
11
|
export { executionCost } from "./vendor/costs.js";
|
|
12
12
|
export { InfoClient } from "./vendor/info.js";
|