-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
1424 lines (1332 loc) · 64.7 KB
/
Copy pathplugin.js
File metadata and controls
1424 lines (1332 loc) · 64.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// markets — prediction markets with an LMSR automated market maker, as a
// #206 loader plugin. Paper credits: the FanDuel *shape* (markets, live
// prices, positions, cash-out, settlement) with play money.
//
// plugins: [{ module: 'markets/plugin.js', prefix: '/predict',
// config: { grantCredits: 1000, feeBps: 100,
// admins: ['https://alice.example/profile/card#me'] } }]
//
// Layout: lmsr.js (the AMM math + TWAP), store.js (journal + snapshot +
// reducer), lifecycle.js (the settlement state machine), guard.js
// (sessions, CSRF, rate limiting, headers), ui.js (the trading UI), this
// file (policy + routes).
//
// MONEY. Integer micro-credits (1 credit = 1e6 micro). Costs round up,
// proceeds and payouts round down, fees round up — every rounding
// direction favours the pool, so float drift can never over-draw it.
// Shares are integer micro-shares; one share of the winning outcome
// redeems for exactly one credit.
//
// SOLVENCY. The creator escrows LMSR's worst-case maker loss b·ln n at
// creation, so payouts provably fit inside subsidy + collected (see
// lmsr.js for the two Gibbs-inequality bounds this rests on). A pro-rata
// clamp at settlement is the belt-and-braces backstop; it logs loudly and
// has never fired.
//
// SETTLEMENT is a state machine, not a single privileged call, because a
// unilateral instant oracle is a credit-theft primitive:
//
// open --closesAt--> (closed: no trading)
// | |
// | oracle resolve | nobody resolves within settlementWindow
// v v
// resolving --disputeWindow--> resolved auto-void at TWAP
// | (funds are NEVER stuck:
// | any holder disputes anyone may trigger this)
// v
// disputed --admin: uphold / re-resolve / void--> settled
// --disputeGrace with no admin--> the resolution STANDS
// (bonds forfeited: silence must not be a free refund)
//
// Three separate defences against the oracle stealing the pool:
// 1. the oracle and creator MAY NOT TRADE in their own market;
// 2. the creator's settlement claim is CAPPED AT THEIR OWN ESCROW —
// residual beyond it goes to the house, so resolving to an outcome
// nobody holds wins the attacker nothing;
// 3. holders can dispute inside the window, which parks the market for
// an admin instead of paying out.
//
// VOID REDEEMS AT A TWAP over the window ending at close, never at spot.
// Redeeming at spot is a guaranteed arbitrage — by strict convexity,
// buying x shares costs less than x·p_final, so buy-then-void extracts
// b·ln n risk-free, partly out of other holders' redemptions. A TWAP is
// still conserving (the bound holds for ANY probability vector) but a
// last-second pump barely moves it, so the pump is a pure loss.
//
// ATOMICITY. Every mutating handler awaits auth FIRST, then validates and
// calls store.commit() with no await in between — Node's single thread
// makes the journal-append-then-apply a transaction. commit() journals
// (fsync) BEFORE mutating memory, so a failed write cannot leave the
// in-memory ledger ahead of the durable one.
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { lmsrPrices, tradeCostRaw, sharesForBudget, twapPrices, uniformPrices } from './lmsr.js';
import { createStore, dict, TWAP_PROTECT_MS } from './store.js';
import { createLifecycle } from './lifecycle.js';
import {
createSessions, createRateLimiter, isSameOrigin, isAmbientCredential, UI_HEADERS, API_HEADERS,
} from './guard.js';
import { renderUi } from './ui.js';
export { lmsrCost, lmsrPrices, twapPrices } from './lmsr.js';
const MICRO = 1_000_000;
const B62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const HOUSE = '(house)'; // reserved ledger key — not a valid agent id, so unclaimable
const LIMITS = {
titleLen: 200,
descriptionLen: 2000,
categoryLen: 40,
outcomeLabelLen: 80,
outcomesMin: 2,
outcomesMax: 12,
bMinCredits: 10,
bMaxCredits: 100_000,
maxMarkets: 10_000,
maxMarketsPerAgent: 50,
maxTradeShares: 1_000_000,
maxHorizonMs: 5 * 365 * 24 * 3600 * 1000,
listLimit: 50,
listLimitMax: 200,
leaderboard: 20,
tradeFeedLimit: 100,
idempotencyTtlMs: 10 * 60 * 1000,
maxIdempotencyKeys: 10_000,
maxAdjustCredits: 1_000_000,
maxSockets: 500,
maxSocketsPerIp: 10,
wsBufferBytes: 1 << 20,
};
export function randomId(len = 8) {
const bytes = crypto.randomBytes(len);
let s = '';
for (const b of bytes) s += B62[b % 62];
return s;
}
/** A persistent per-deployment secret, created 0600 on first boot. */
function readOrCreateSecret(file) {
try {
return fs.readFileSync(file);
} catch {
const s = crypto.randomBytes(32);
fs.writeFileSync(file, s, { mode: 0o600 });
return s;
}
}
/** An agent id is a WebID (http/https URL) or a DID — the two shapes
* getAgent can ever return. Rejecting anything else at creation stops a
* typo'd oracle from being an unsatisfiable settlement condition. */
export function isAgentId(s) {
if (typeof s !== 'string' || !s || s.length > 512) return false;
if (s.startsWith('did:')) return /^did:[a-z0-9]+:[\w.:%-]+$/i.test(s);
try {
const u = new URL(s);
return u.protocol === 'http:' || u.protocol === 'https:';
} catch { return false; }
}
export async function activate(api) {
const prefix = api.prefix ?? '/markets'; // '' = site root (standalone host)
const cfg = api.config || {};
// ------------------------------------------------------------ config
const num = (v, d) => (v === undefined ? d : v);
const grantMicro = Math.round(num(cfg.grantCredits, 1000) * MICRO);
const accountsUi = !!cfg.accountsUi; // standalone hosts: register/login form instead of pod-bearer paste
const feeBps = num(cfg.feeBps, 100);
const houseFeeShareBps = num(cfg.houseFeeShareBps, 5000);
const disputeWindowMs = num(cfg.disputeWindowMs, 60 * 60 * 1000);
const disputeBondMicro = Math.round(num(cfg.disputeBondCredits, 25) * MICRO);
const disputeBondBps = num(cfg.disputeBondBps, 2000); // 20% of the disputed position
const disputeGraceMs = num(cfg.disputeGraceMs, 7 * 24 * 3600 * 1000);
const settlementWindowMs = num(cfg.settlementWindowMs, 7 * 24 * 3600 * 1000);
const twapWindowMs = num(cfg.twapWindowMs, 30 * 60 * 1000);
const sessionTtlMs = num(cfg.sessionTtlMs, 12 * 3600 * 1000);
const rateCapacity = num(cfg.rateCapacity, 120);
const rateRefillPerSec = num(cfg.rateRefillPerSec, 2);
const allowInsiderTrading = cfg.allowInsiderTrading === true;
const admins = new Set(Array.isArray(cfg.admins) ? cfg.admins : []);
if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > 1000) {
throw new Error('markets: config.feeBps must be an integer 0..1000 (basis points)');
}
if (!Number.isInteger(houseFeeShareBps) || houseFeeShareBps < 0 || houseFeeShareBps > 10_000) {
throw new Error('markets: config.houseFeeShareBps must be an integer 0..10000');
}
if (!Number.isFinite(grantMicro) || grantMicro < 0) {
throw new Error('markets: config.grantCredits must be a non-negative number');
}
for (const a of admins) {
if (!isAgentId(a)) throw new Error(`markets: config.admins contains a non-agent id: ${a}`);
}
// These windows are load-bearing, not cosmetic: twapWindowMs = 0 makes
// voidPrices() degenerate to the SPOT price, which resurrects the
// buy-then-void arbitrage the TWAP exists to prevent. Refuse to boot on
// a value that would silently disable a defence.
for (const [name, v] of Object.entries({
disputeWindowMs, disputeGraceMs, settlementWindowMs, twapWindowMs, sessionTtlMs,
snapshotIntervalMs: num(cfg.snapshotIntervalMs, 30_000),
})) {
if (!Number.isFinite(v) || v <= 0) {
throw new Error(`markets: config.${name} must be a positive number of milliseconds (got ${v})`);
}
}
// "> 0" is not the property that matters: a 1ms window gives the last
// price full weight, i.e. the TWAP IS spot — the very arbitrage the
// window exists to prevent.
if (twapWindowMs < 60_000) {
throw new Error('markets: config.twapWindowMs must be at least 60000ms — a shorter window is spot pricing in disguise');
}
// Get these two the wrong way round and a resolution is still inside
// its dispute window when the abandoned-market backstop opens — which
// made every resolution voidable by every loser.
if (disputeWindowMs >= settlementWindowMs) {
throw new Error(
`markets: config.disputeWindowMs (${disputeWindowMs}) must be shorter than `
+ `settlementWindowMs (${settlementWindowMs})`,
);
}
if (!Number.isFinite(disputeBondBps) || disputeBondBps < 0 || disputeBondBps > 10_000) {
throw new Error('markets: config.disputeBondBps must be 0..10000');
}
if (!Number.isFinite(rateCapacity) || rateCapacity <= 0
|| !Number.isFinite(rateRefillPerSec) || rateRefillPerSec <= 0) {
throw new Error('markets: config.rateCapacity and config.rateRefillPerSec must be positive');
}
if (twapWindowMs > TWAP_PROTECT_MS) {
throw new Error(
`markets: config.twapWindowMs (${twapWindowMs}) must not exceed ${TWAP_PROTECT_MS}ms — beyond that, `
+ 'price-history thinning reaches inside the redemption window and makes the void price steerable by trade timing',
);
}
if (!Number.isFinite(disputeBondMicro) || disputeBondMicro < 0) {
throw new Error('markets: config.disputeBondCredits must be a non-negative number');
}
if (/["'<>]/.test(prefix)) throw new Error(`markets: refusing an unsafe prefix: ${prefix}`);
// -------------------------------------------------- store & security
const dir = api.storage.pluginDir();
const store = createStore({ dir, log: api.log, prices: lmsrPrices });
const { state } = store;
const sessions = createSessions({ dir, ttlMs: sessionTtlMs });
const pseudonymSalt = readOrCreateSecret(path.join(dir, 'pseudonym.salt'));
const limiter = createRateLimiter({ capacity: rateCapacity, refillPerSec: rateRefillPerSec });
/** agent → Set(marketId) — so /api/me is O(your markets), not O(all). */
const byAgent = new Map();
const indexPosition = (agent, id) => {
let s = byAgent.get(agent);
if (!s) byAgent.set(agent, (s = new Set()));
s.add(id);
};
for (const m of Object.values(state.markets)) {
for (const agent of Object.keys(m.positions)) indexPosition(agent, m.id);
}
const ownOrigin = () => {
try {
if (typeof api.serverInfo === 'function') {
const info = api.serverInfo();
if (info && info.baseUrl) return info.baseUrl;
}
} catch { /* not listening yet */ }
return cfg.baseUrl || null;
};
// ------------------------------------------------------------- auth
const cookieName = 'markets_session';
function cookieToken(request) {
const raw = request.headers.cookie;
if (!raw) return null;
for (const part of raw.split(';')) {
const [k, ...v] = part.trim().split('=');
if (k === cookieName) return decodeURIComponent(v.join('='));
}
return null;
}
/**
* Resolve the caller. Order matters: our own scoped session token (the
* only credential a browser is ever asked to hold) is checked first, so
* the pod bearer path is reserved for API clients that send it
* explicitly.
*/
/** Resolve a session token to an agent id. A session is live only
* while its epoch matches the agent's current epoch — that comparison
* is what makes sign-out, freeze and revoke actually end a session,
* since a self-verifying token is otherwise valid for its whole TTL. */
function liveSession(token) {
const claims = sessions.verify(token);
if (!claims) return null;
const row = state.ledger[claims.agent];
if ((row ? row.epoch || 0 : 0) !== claims.epoch) return null;
return claims.agent;
}
/**
* @returns {Promise<{agent:string|null, ambient:boolean}>} `ambient` is
* true when the credential is one a browser attaches by itself — a
* cookie, or a WebID-TLS client certificate — i.e. one a cross-origin
* page could borrow without knowing it.
*/
async function resolveAgentFull(request) {
const cookie = cookieToken(request);
if (cookie) {
const agent = liveSession(cookie);
if (agent) return { agent, ambient: true };
}
const auth = request.headers.authorization;
if (auth && auth.startsWith('Bearer v1.')) {
const agent = liveSession(auth.slice(7));
if (agent) return { agent, ambient: false };
}
const agent = await api.auth.getAgent(request);
// getAgent may have authenticated from an ambient TLS client
// certificate; only an explicit Authorization header proves the
// caller actually held a secret.
return { agent, ambient: agent ? !auth : false };
}
async function resolveAgent(request) {
return (await resolveAgentFull(request)).agent;
}
// ------------------------------------------------------------ replies
const err = (reply, code, error, extra) => reply.code(code).send({ error, ...extra });
/** Guard for every mutating route: same-origin required whenever the
* credential is ambient (cookie/TLS cert), because those are exactly
* the credentials a cross-origin page can borrow. */
/** The origin to compare against, preferring configured/serverInfo and
* falling back to the request's own Host so a deployment without
* baseUrl doesn't silently refuse every browser mutation. */
function originFor(request) {
const known = ownOrigin();
if (known) return known;
const host = request.headers.host;
if (!host) return null;
// Fastify reports the SOCKET's protocol unless trustProxy is on,
// which a plugin cannot set; behind nginx/Caddy that is 'http' while
// the browser's Origin says https, and every mutation would 403.
const proto = request.headers['x-forwarded-proto'] || request.protocol || 'https';
return `${String(proto).split(',')[0].trim()}://${host}`;
}
function csrfOk(request) {
// A session cookie makes the request ambient REGARDLESS of any
// Authorization header: resolveAgent checks the cookie first, so an
// attacker could otherwise bolt on a junk bearer to look
// "explicitly credentialed", skip this check, and still be
// authenticated by the victim's cookie.
if (!cookieToken(request) && !isAmbientCredential(request)) return true;
return isSameOrigin(request, originFor(request));
}
async function authed(request, reply, { mutating = true } = {}) {
// Resolve first so an anonymous caller gets a 401 rather than a
// confusing 403; nothing is acted on before the CSRF check below.
const { agent, ambient } = await resolveAgentFull(request);
if (!agent) { err(reply, 401, 'authentication required'); return null; }
if (mutating && ambient && !isSameOrigin(request, originFor(request))) {
err(reply, 403, 'cross-origin request refused — this endpoint is same-origin only');
return null;
}
if (state.ledger[agent] && state.ledger[agent].frozen) {
err(reply, 403, 'this account is frozen; contact the operator');
return null;
}
return agent;
}
/** Grant the signup credits the first time we ever see an agent. */
function ensureAccount(agent) {
const row = state.ledger[agent];
if (row && row.created) return row;
store.commit({ type: 'grant', agent, amountMicro: grantMicro });
api.log.info(`markets: granted ${grantMicro / MICRO} credits to ${agent}`);
return state.ledger[agent];
}
const balanceOf = (agent) => (state.ledger[agent] ? state.ledger[agent].balanceMicro : 0);
// ------------------------------------------------- rate limit + CORS
//
// FINDING: hooks added via api.fastify are NOT scoped to the plugin's
// own routes — they run for EVERY request the server handles, including
// other plugins' and core's. An unguarded rate-limit hook here 429'd
// the metrics and dashboard plugins in the compose suite. Every hook
// below therefore gates on `mine(request)` first. (metrics/ hit the
// same edge from the other side and documented it as "scope: all
// plugins, never core".)
const mine = (request) => {
const u = request.url;
return u === prefix || u.startsWith(`${prefix}/`) || u.startsWith(`${prefix}?`);
};
api.fastify.addHook('onRequest', async (request, reply) => {
if (!mine(request)) return undefined;
const key = liveSession(cookieToken(request) || '') || request.ip;
const cost = request.method === 'GET' || request.method === 'HEAD' ? 1 : 4;
const waitMs = limiter.take(key, cost);
if (waitMs) {
return reply.code(429)
.header('retry-after', Math.ceil(waitMs / 1000))
.send({ error: 'rate limit exceeded — slow down' });
}
return undefined;
});
// The host reflects arbitrary Origins with Allow-Credentials on its LDP
// routes; those defaults must not apply to money endpoints. Pin ACAO to
// our own origin and drop credential sharing entirely.
api.fastify.addHook('onSend', async (request, reply, payload) => {
if (!mine(request)) return payload;
const origin = ownOrigin();
reply.header('access-control-allow-origin', origin || 'null');
reply.removeHeader('access-control-allow-credentials');
if (request.url.startsWith(`${prefix}/api`)) {
for (const [k, v] of Object.entries(API_HEADERS)) reply.header(k, v);
}
return payload;
});
// ------------------------------------------------------- projections
const tradable = (m) => m.status === 'open' && Date.now() < m.closesAt;
const displayStatus = (m) => (m.status === 'open' && !tradable(m) ? 'closed' : m.status);
function positionOut(m, pos) {
const prices = lmsrPrices(m.q, m.bMicro);
const shares = pos.shares.map((s) => s / MICRO);
const cost = pos.costMicro.map((c) => c / MICRO);
// Value a live position at what the AMM would actually pay to close
// it (proceeds net of fee), not at mark — "cash out" must not quote a
// number the sell path won't honour.
const value = pos.shares.map((s, i) => (s > 0 ? sellQuote(m, i, s).totalMicro / MICRO : 0));
const totalValue = value.reduce((a, x) => a + x, 0);
const totalCost = cost.reduce((a, x) => a + x, 0);
return {
shares,
cost,
prices: prices.map((p) => Number(p.toFixed(6))),
value,
totalCost: Number(totalCost.toFixed(6)),
totalValue: Number(totalValue.toFixed(6)),
unrealizedPnl: Number((totalValue - totalCost).toFixed(6)),
};
}
function marketOut(m, { agent = null, history = false } = {}) {
const prices = lmsrPrices(m.q, m.bMicro);
const out = {
id: m.id,
title: m.title,
description: m.description,
category: m.category || null,
outcomes: m.outcomes,
prices: prices.map((p) => Number(p.toFixed(6))),
status: displayStatus(m),
// The RAW lifecycle state, distinct from the display status: a
// market past closesAt displays as 'closed' while its raw status is
// still 'open', and that is exactly when the oracle must resolve.
// Without this a client can't tell "closed, awaiting resolution"
// from "settled", and hides the resolve controls at the only moment
// they matter.
rawStatus: m.status,
tradable: tradable(m),
canResolve: m.status === 'open',
canVoid: m.status === 'open' && !tradable(m),
closesAt: new Date(m.closesAt).toISOString(),
createdAt: m.createdAt,
creator: m.creator,
oracle: m.oracle,
b: m.bMicro / MICRO,
volume: m.volumeMicro / MICRO,
fees: m.feesMicro / MICRO,
trades: m.trades,
liquidity: (m.subsidyMicro + m.collectedMicro) / MICRO,
resolvedOutcome: m.resolvedOutcome ?? null,
settleAt: m.settleAt ? new Date(m.settleAt).toISOString() : null,
resolvedAt: m.resolvedAt ?? null,
settledPrices: m.settledPrices ?? null,
disputes: (m.disputes || []).length,
hidden: !!m.hidden,
};
if (agent && m.positions[agent]) out.position = positionOut(m, m.positions[agent]);
if (history) out.history = m.history.map((h) => ({ t: h.t, p: h.p.map((x) => Number(x.toFixed(6))) }));
return out;
}
// ------------------------------------------------------------ pricing
function buyQuote(m, i, sharesMicro) {
const costMicro = Math.ceil(tradeCostRaw(m.q, m.bMicro, i, sharesMicro));
const feeMicro = Math.ceil((costMicro * feeBps) / 10_000);
return { sharesMicro, costMicro, feeMicro, totalMicro: costMicro + feeMicro };
}
function sellQuote(m, i, sharesMicro) {
const proceedsMicro = Math.floor(-tradeCostRaw(m.q, m.bMicro, i, -sharesMicro));
const feeMicro = Math.ceil((proceedsMicro * feeBps) / 10_000);
return { sharesMicro, proceedsMicro, feeMicro, totalMicro: proceedsMicro - feeMicro };
}
/** Validate a trade request into micro units. Returns { error } or the
* priced trade. `spend` is the stake-first path: how many shares does
* this many credits buy? (Consumers think in stakes, not shares.) */
function priceTrade(m, side, outcomeRaw, sharesRaw, spendRaw) {
const outcome = Number(outcomeRaw);
if (!Number.isInteger(outcome) || outcome < 0 || outcome >= m.outcomes.length) {
return { error: 'outcome must be a valid outcome index' };
}
if (side !== 'buy' && side !== 'sell') return { error: "side must be 'buy' or 'sell'" };
let sharesMicro;
if (spendRaw !== undefined && spendRaw !== null && spendRaw !== '') {
if (side !== 'buy') return { error: 'spend is only meaningful for a buy' };
const spend = Number(spendRaw);
if (!Number.isFinite(spend) || spend <= 0) return { error: 'spend must be a positive number of credits' };
const budget = Math.floor(spend * MICRO);
sharesMicro = sharesForBudget(m.q, m.bMicro, outcome, budget,
(x) => buyQuote(m, outcome, x).totalMicro, LIMITS.maxTradeShares * MICRO);
if (sharesMicro <= 0) return { error: 'that stake is too small to buy any shares' };
} else {
const shares = Number(sharesRaw);
if (!Number.isFinite(shares) || shares <= 0 || shares > LIMITS.maxTradeShares) {
return { error: `shares must be > 0 and ≤ ${LIMITS.maxTradeShares}` };
}
sharesMicro = Math.round(shares * MICRO);
if (sharesMicro <= 0) return { error: 'shares too small (min 0.000001)' };
}
const t = side === 'buy' ? buyQuote(m, outcome, sharesMicro) : sellQuote(m, outcome, sharesMicro);
return { ...t, outcome, side };
}
/** The consumer-facing framing: stake in, payout out, decimal odds. */
function quoteOut(m, t) {
const shares = t.sharesMicro / MICRO;
const stake = t.totalMicro / MICRO;
const base = {
side: t.side,
outcome: t.outcome,
outcomeLabel: m.outcomes[t.outcome],
shares: Number(shares.toFixed(6)),
fee: Number((t.feeMicro / MICRO).toFixed(6)),
total: Number(stake.toFixed(6)),
};
if (t.side === 'buy') {
base.cost = Number((t.costMicro / MICRO).toFixed(6));
base.toWin = Number(shares.toFixed(6)); // a winning share pays 1 credit
base.profit = Number((shares - stake).toFixed(6));
base.avgPrice = shares > 0 ? Number((stake / shares).toFixed(6)) : null;
base.odds = stake > 0 ? Number((shares / stake).toFixed(3)) : null; // decimal odds
} else {
base.proceeds = Number((t.proceedsMicro / MICRO).toFixed(6));
base.avgPrice = shares > 0 ? Number((stake / shares).toFixed(6)) : null;
}
return base;
}
// ----------------------------------------------------------- lifecycle
// The settlement state machine lives in lifecycle.js — see that file
// for why it is not inline here (a state change that skipped the
// reducer made the audit trail contradict the money).
const {
voidPrices, settleResolved, settleVoid, tick, tickOne, maybeTick, disputeDeadline,
} = createLifecycle({
state,
commit: store.commit,
broadcast: (type, m) => broadcast(type, m),
log: api.log,
cfg: { twapWindowMs, houseFeeShareBps, settlementWindowMs, disputeGraceMs, HOUSE },
});
// --------------------------------------------------------- websocket
const sockets = new Set();
const perIp = new Map();
await api.ws.route(`${prefix}/ws`, (socket, request) => {
// Reject cross-origin upgrades: public data today, but an unchecked
// origin makes any future per-agent field on the wire a leak.
const wsOrigin = request.headers && request.headers.origin;
if (wsOrigin && !isSameOrigin({ headers: { origin: wsOrigin } }, originFor(request))) {
try { socket.close(1008, 'cross-origin'); } catch { /* gone */ }
return;
}
const ip = request.socket ? request.socket.remoteAddress : 'unknown';
const n = perIp.get(ip) || 0;
if (sockets.size >= LIMITS.maxSockets || n >= LIMITS.maxSocketsPerIp) {
try { socket.close(1013, 'too many connections'); } catch { /* gone */ }
return;
}
// A live price feed is public (prices are public), but an unbounded,
// never-reaped socket set is a memory DoS — hence the caps, the idle
// reaper below, and the backpressure check in broadcast().
perIp.set(ip, n + 1);
socket.isAlive = true;
socket.on('pong', () => { socket.isAlive = true; });
const drop = () => {
sockets.delete(socket);
const c = (perIp.get(ip) || 1) - 1;
if (c <= 0) perIp.delete(ip); else perIp.set(ip, c);
};
socket.on('close', drop);
socket.on('error', drop);
sockets.add(socket);
});
const reaper = setInterval(() => {
for (const s of sockets) {
if (!s.isAlive) { try { s.terminate ? s.terminate() : s.close(); } catch { /* gone */ } continue; }
s.isAlive = false;
try { s.ping ? s.ping() : null; } catch { /* gone */ }
}
}, 30_000);
reaper.unref?.();
const ticker = setInterval(tick, 15_000);
ticker.unref?.();
function broadcast(type, m) {
// A withdrawn market must not push its title and description to
// every connected client when it settles.
if (m.hidden) return;
const msg = JSON.stringify({ type, market: marketOut(m) });
for (const s of sockets) {
// Drop a client that isn't draining rather than buffering without
// bound on its behalf.
if (s.bufferedAmount > LIMITS.wsBufferBytes) { try { s.close(1013, 'too slow'); } catch { /* gone */ } continue; }
try { s.send(msg); } catch { /* dead socket; close event reaps it */ }
}
}
// ------------------------------------------------------- idempotency
// A retried trade (double-click, network timeout) must not execute
// twice. Keyed by agent + Idempotency-Key; the original response is
// replayed verbatim.
const idem = new Map();
const fingerprint = (request) => crypto.createHash('sha256')
.update(`${request.method} ${request.url} ${JSON.stringify(request.body || {})}`)
.digest('hex');
/** @returns {{code,body}|'conflict'|null} */
function idemGet(agent, key, fp) {
if (!key) return null;
const hit = idem.get(`${agent}