@rbxts/scribe 2.5.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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +21 -0
  3. package/README.md +100 -0
  4. package/Scribe-source-map.json +1 -0
  5. package/licenses/ProfileStore-Apache-2.0.txt +201 -0
  6. package/package.json +32 -0
  7. package/src/Client/DebugHook.luau +457 -0
  8. package/src/Client/init.luau +1607 -0
  9. package/src/Internal/Addons.luau +68 -0
  10. package/src/Internal/Big.luau +582 -0
  11. package/src/Internal/Budget.luau +377 -0
  12. package/src/Internal/Clock.luau +75 -0
  13. package/src/Internal/Config.luau +17 -0
  14. package/src/Internal/Conform.luau +400 -0
  15. package/src/Internal/Datatypes.luau +653 -0
  16. package/src/Internal/Defaults.luau +12 -0
  17. package/src/Internal/Derived.luau +428 -0
  18. package/src/Internal/Exchange.luau +556 -0
  19. package/src/Internal/ExchangeLeg.luau +1368 -0
  20. package/src/Internal/ExchangeVerdict.luau +179 -0
  21. package/src/Internal/Failure.luau +148 -0
  22. package/src/Internal/Health.luau +320 -0
  23. package/src/Internal/LeaderboardDiagnostics.luau +36 -0
  24. package/src/Internal/Log.luau +378 -0
  25. package/src/Internal/Marker.luau +76 -0
  26. package/src/Internal/Metrics.luau +152 -0
  27. package/src/Internal/Node.luau +3954 -0
  28. package/src/Internal/Profile.luau +69 -0
  29. package/src/Internal/Rng.luau +83 -0
  30. package/src/Internal/Sched.luau +56 -0
  31. package/src/Internal/Signal.luau +199 -0
  32. package/src/Internal/Store/ProfileStore.luau +3019 -0
  33. package/src/Internal/Store/init.luau +18 -0
  34. package/src/Internal/StudioCodec.luau +155 -0
  35. package/src/Internal/Template.luau +1848 -0
  36. package/src/Internal/Transport.luau +169 -0
  37. package/src/Internal/Util.luau +517 -0
  38. package/src/Internal/Version.luau +4 -0
  39. package/src/Internal/Wire.luau +1283 -0
  40. package/src/Server/Analytics.luau +223 -0
  41. package/src/Server/Commands.luau +728 -0
  42. package/src/Server/DebugHook.luau +1490 -0
  43. package/src/Server/Exchanges.luau +737 -0
  44. package/src/Server/Leaderboards.luau +2143 -0
  45. package/src/Server/Monetization.luau +3212 -0
  46. package/src/Server/Persistence.luau +3775 -0
  47. package/src/Server/Replication.luau +1253 -0
  48. package/src/Server/ServerStore.luau +81 -0
  49. package/src/Server/Timed.luau +579 -0
  50. package/src/Server/init.luau +672 -0
  51. package/src/Types.luau +480 -0
  52. package/src/init.luau +2231 -0
  53. package/types/api.d.ts +252 -0
  54. package/types/common.d.ts +355 -0
  55. package/types/index.d.ts +226 -0
  56. package/types/schema.d.ts +276 -0
@@ -0,0 +1,556 @@
1
+ --!strict
2
+ -- ClaimExchange orchestration: one same-server exchange, start to finish.
3
+ --
4
+ -- Everything fallible happens BEFORE the verdict. After it there are two kinds of step:
5
+ -- SETTLE, which writes only under the reserved root and cannot be refused by any shape,
6
+ -- cap or bound; and DELIVER, which can fail but rolls back and is retried for ever.
7
+ -- Never decide what happened from a pcall boundary: every step re-reads the record out
8
+ -- of the tree, and the pcall result only picks which question to ask.
9
+ --
10
+ -- The taker's payload is durable on its own key BEFORE any verdict exists (both forced
11
+ -- flushes return true first), so a Commit that drops the giver's escrow cannot destroy
12
+ -- the only copy. The flushes are not an optimisation.
13
+ local Clock = require(script.Parent.Clock)
14
+ local Util = require(script.Parent.Util)
15
+ local ExchangeLeg = require(script.Parent.ExchangeLeg)
16
+ local ExchangeVerdict = require(script.Parent.ExchangeVerdict)
17
+
18
+ local Exchange = {}
19
+
20
+ local DEFAULT_DEADLINE = 20
21
+
22
+ --- One leg, in the shape something player-facing needs and nothing more.
23
+ ---
24
+ --- No digest, no role, no payload: the payload is the stored form and may be packed, so
25
+ --- handing it out would put buffers in front of game code for no benefit.
26
+ export type OpenLeg = {
27
+ Path: { string | number },
28
+ Kind: string,
29
+ Key: any?,
30
+ Amount: number?,
31
+ }
32
+
33
+ --- What a profile still has in flight, and what it is holding while it does.
34
+ export type OpenExchange = {
35
+ Id: string,
36
+ State: "Claimed" | "Staked" | "Delivering",
37
+ Partner: number?,
38
+ Staked: { OpenLeg }, -- what this profile handed over
39
+ Owed: { OpenLeg }, -- what this profile is owed
40
+ Since: number?,
41
+ }
42
+
43
+ export type Side = {
44
+ Ctx: any, -- the ExchangeLeg context for this player
45
+ UserId: number,
46
+ Legs: { any }, -- what this side GIVES
47
+ }
48
+
49
+ local function fail(message: string): ()
50
+ error(`Exchange: {message}`, 0)
51
+ end
52
+
53
+ --- A stable digest over the basket, so a verdict can only settle the exchange it names.
54
+ --- Order-independent per side and then concatenated, because two servers must derive the
55
+ --- identical string from the identical basket.
56
+ local function digestOf(exchangeId: string, sideA: Side, sideB: Side): string
57
+ local parts = {}
58
+ for _, side in { sideA, sideB } do
59
+ local legs = {}
60
+ for _, leg in side.Legs do
61
+ table.insert(legs, `{table.concat(leg.Path, ".")}|{leg.Kind}|{tostring(leg.Key)}|{tostring(leg.Amount)}`)
62
+ end
63
+ table.sort(legs)
64
+ table.insert(parts, `{side.UserId}:{table.concat(legs, ";")}`)
65
+ end
66
+ return `{exchangeId}#{table.concat(parts, "#")}`
67
+ end
68
+
69
+ --- The record this profile currently holds for the exchange, read fresh. The only thing
70
+ --- allowed to decide what state a side is in.
71
+ local function recordOf(side: Side, exchangeId: string): any
72
+ return side.Ctx.Tree.Reserved.Exchange[exchangeId].Get()
73
+ end
74
+
75
+ --- Run a step and decide from the TREE whether it landed, never from the call.
76
+ ---
77
+ --- `landed` is given the record as it stands afterwards. The pcall result supplies the
78
+ --- message and nothing else, because `raised == false` has five causes in Node and only
79
+ --- ONE is "committed": a dead tree, a nested transaction, a transaction open on another
80
+ --- player, a failed rollback where the tree may be partly restored, and a throw from OnOp
81
+ --- or OnEconomy where the writes already committed. That last one is dispatched after
82
+ --- `_txn` is cleared, so a listener that throws would otherwise make this module abandon
83
+ --- a slot it genuinely holds, or re-run a stake that has already moved value.
84
+ local function stepped(
85
+ side: Side,
86
+ exchangeId: string,
87
+ run: () -> (boolean, string?),
88
+ landed: (record: any) -> boolean
89
+ ): (boolean, string?)
90
+ local pok, ok, err = pcall(run)
91
+ local record = recordOf(side, exchangeId)
92
+ if landed(record) then
93
+ return true, nil
94
+ end
95
+ local reason = if pok then tostring(err) else tostring(ok)
96
+ return false, `{reason} (record={if record == nil then "absent" else tostring(record.Phase)})`
97
+ end
98
+
99
+ --- The record exists at all: what a claim leaves behind.
100
+ local function isClaimed(record: any): boolean
101
+ return record ~= nil
102
+ end
103
+
104
+ --- The record is holding staked value: what an escrow leaves behind. A stake that
105
+ --- rolled back leaves the CLAIM, so testing for the record alone would read a failed
106
+ --- stake as a successful one.
107
+ local function isStaked(record: any): boolean
108
+ return record ~= nil and record.Phase == "Staked"
109
+ end
110
+
111
+ --- The record carries what this profile is owed: what filling a take leaves behind.
112
+ local function hasTake(record: any): boolean
113
+ return record ~= nil and type(record.Take) == "table"
114
+ end
115
+
116
+ --- Admission: everything that can refuse an exchange for free, before any value moves.
117
+ local function admit(sideA: Side, sideB: Side, options: any, inFlight: any): (boolean, string?)
118
+ if sideA.UserId == sideB.UserId then
119
+ return false, "a player cannot exchange with themselves"
120
+ end
121
+ if #sideA.Legs == 0 and #sideB.Legs == 0 then
122
+ return false, "an exchange must move something"
123
+ end
124
+ for _, side in { sideA, sideB } do
125
+ -- The record below is the durable check, and it is BLIND for a long ordinary
126
+ -- window: Settle removes it, and two resolve flushes and two deliveries all yield
127
+ -- afterwards, so a second exchange admitted in that window sees an empty
128
+ -- container. The in-flight set is the only thing covering that on this server.
129
+ if inFlight ~= nil and inFlight[side.UserId] ~= nil then
130
+ return false, `player {side.UserId} already has an exchange in flight`
131
+ end
132
+ if side.Ctx == nil or side.Ctx.Tree == nil or side.Ctx.Tree.Dead then
133
+ return false, `player {side.UserId} has no live profile`
134
+ end
135
+ local exchange = side.Ctx.Tree.Reserved.Exchange.Get()
136
+ if type(exchange) == "table" and next(exchange) ~= nil then
137
+ return false, `player {side.UserId} already has an exchange in flight`
138
+ end
139
+ -- The inbox is untyped and so has no cap of its own, and unbounded accumulation
140
+ -- ends in a profile that cannot save.
141
+ local inbox = side.Ctx.Tree.Reserved.ExchangeInbox.Get()
142
+ local pending = 0
143
+ if type(inbox) == "table" then
144
+ for _ in inbox do
145
+ pending += 1
146
+ end
147
+ end
148
+ local cap = if options and options.MaxInbox then options.MaxInbox else 8
149
+ if pending >= cap then
150
+ return false, `player {side.UserId} has {pending} undelivered exchanges, at the cap of {cap}`
151
+ end
152
+ end
153
+ return true, nil
154
+ end
155
+
156
+ --- Attempt one exchange between two loaded, same-server players.
157
+ ---
158
+ --- Yields. Returns (outcome, err) where outcome is "Committed", "Aborted" or nil.
159
+ function Exchange.Attempt(deps: any, sideA: Side, sideB: Side): (string?, string?)
160
+ if type(deps) ~= "table" or deps.VerdictStore == nil or type(deps.Flush) ~= "function" then
161
+ fail("Attempt needs a VerdictStore and a Flush")
162
+ end
163
+ local exchangeId = deps.ExchangeId
164
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
165
+ fail("Attempt needs an exchange id")
166
+ end
167
+ if #exchangeId > 50 or not Util.isUtf8(exchangeId) then
168
+ return nil, "exchange id must be valid UTF-8 and at most 50 bytes"
169
+ end
170
+
171
+ local admitted, why = admit(sideA, sideB, deps.Options, deps.InFlight)
172
+ if not admitted then
173
+ return nil, why
174
+ end
175
+
176
+ local digest = digestOf(exchangeId, sideA, sideB)
177
+ local deadline = Clock.Monotonic() + (deps.Deadline or DEFAULT_DEADLINE)
178
+ local inFlight = deps.InFlight
179
+
180
+ -- Registered BEFORE the first claim, not after the escrows. A deferred ancestor
181
+ -- listener can yield on this thread after each commit, so registering later leaves
182
+ -- the same-server guard blind for the whole construction window.
183
+ if inFlight ~= nil then
184
+ inFlight[sideA.UserId] = exchangeId
185
+ inFlight[sideB.UserId] = exchangeId
186
+ end
187
+
188
+ -- Cleared by OWNERSHIP, never by user id alone. The set maps a userId to the exchange
189
+ -- that registered it, and deleting by id deletes whatever that player currently
190
+ -- holds, which after the settle window above can be a different, live exchange.
191
+ local function release()
192
+ if inFlight ~= nil then
193
+ if inFlight[sideA.UserId] == exchangeId then
194
+ inFlight[sideA.UserId] = nil
195
+ end
196
+ if inFlight[sideB.UserId] == exchangeId then
197
+ inFlight[sideB.UserId] = nil
198
+ end
199
+ end
200
+ end
201
+
202
+ -- 0.3 CLAIM BOTH, no yield between them, so neither profile ever advertises a free
203
+ -- slot while the other is already committed to this exchange.
204
+ local okA = stepped(sideA, exchangeId, function()
205
+ return ExchangeLeg.Claim(sideA.Ctx, exchangeId, { Digest = digest, Role = "A", Partner = sideB.UserId })
206
+ end, isClaimed)
207
+ if not okA then
208
+ release()
209
+ return nil, "could not claim the first slot"
210
+ end
211
+ local okB, whyB = stepped(sideB, exchangeId, function()
212
+ return ExchangeLeg.Claim(sideB.Ctx, exchangeId, { Digest = digest, Role = "B", Partner = sideA.UserId })
213
+ end, isClaimed)
214
+ if not okB then
215
+ -- A claim carries no value, so releasing it here is safe and is the ONLY place
216
+ -- in this function where a record is dropped without a verdict.
217
+ pcall(ExchangeLeg.Unclaim, sideA.Ctx, exchangeId)
218
+ release()
219
+ return nil, `could not claim the second slot: {tostring(whyB)}`
220
+ end
221
+
222
+ --- Give up before any verdict exists. Free, because escrowed value is returned by
223
+ --- unclaiming a record that never took any, and a record that DID take value is
224
+ --- left for the verdict-gated abort below.
225
+ local function abandon(reason: string): (string?, string?)
226
+ for _, side in { sideA, sideB } do
227
+ local record = recordOf(side, exchangeId)
228
+ if record ~= nil and record.Phase == "Claimed" then
229
+ pcall(ExchangeLeg.Unclaim, side.Ctx, exchangeId)
230
+ end
231
+ end
232
+ -- Anything that reached "Staked" holds value and must go through the verdict.
233
+ local staked = false
234
+ for _, side in { sideA, sideB } do
235
+ local record = recordOf(side, exchangeId)
236
+ if record ~= nil then
237
+ staked = true
238
+ end
239
+ end
240
+ if not staked then
241
+ release()
242
+ return nil, reason
243
+ end
244
+ return Exchange.Resolve(deps, sideA, sideB, exchangeId, digest, "Abort", reason)
245
+ end
246
+
247
+ -- 0.4 to 0.6 ESCROW BOTH SIDES, then fill each side's Take from the OTHER side's
248
+ -- escrow, so what a taker receives is provably what the giver actually gave up.
249
+ if #sideA.Legs > 0 then
250
+ local ok = stepped(sideA, exchangeId, function()
251
+ return ExchangeLeg.Escrow(sideA.Ctx, exchangeId, sideA.Legs)
252
+ end, isStaked)
253
+ if not ok then
254
+ return abandon("could not stake the first side")
255
+ end
256
+ end
257
+ if #sideB.Legs > 0 then
258
+ local ok = stepped(sideB, exchangeId, function()
259
+ return ExchangeLeg.Escrow(sideB.Ctx, exchangeId, sideB.Legs)
260
+ end, isStaked)
261
+ if not ok then
262
+ return abandon("could not stake the second side")
263
+ end
264
+ end
265
+
266
+ local recordA, recordB = recordOf(sideA, exchangeId), recordOf(sideB, exchangeId)
267
+ if recordA == nil or recordB == nil then
268
+ return abandon("a stake vanished before the takes could be filled")
269
+ end
270
+ local takeForA = if recordB.Escrow ~= nil then recordB.Escrow else {}
271
+ local takeForB = if recordA.Escrow ~= nil then recordA.Escrow else {}
272
+
273
+ local okTakeB = stepped(sideB, exchangeId, function()
274
+ return ExchangeLeg.FillTake(sideB.Ctx, exchangeId, takeForB)
275
+ end, hasTake)
276
+ if not okTakeB then
277
+ return abandon("could not record the second side's take")
278
+ end
279
+ local okTakeA = stepped(sideA, exchangeId, function()
280
+ return ExchangeLeg.FillTake(sideA.Ctx, exchangeId, takeForA)
281
+ end, hasTake)
282
+ if not okTakeA then
283
+ return abandon("could not record the first side's take")
284
+ end
285
+
286
+ -- 0.8 and 0.9 FORCED FLUSHES, which YIELD. These are the ordering proof: no verdict
287
+ -- can exist until both takes are durable. A false is UNRESOLVED, never "failed":
288
+ -- Force is per-entry and a concurrent autosave can consume it. pcalled because a
289
+ -- raise means the same thing a false does, and unguarded it left Attempt with both
290
+ -- records staked, no verdict proposed and both in-flight registrations still held,
291
+ -- which admission now reads as a permanent exchanging ban for both players.
292
+ local okFlushA, flushedA = pcall(deps.Flush, sideA)
293
+ local okFlushB, flushedB = pcall(deps.Flush, sideB)
294
+ if not okFlushA or not okFlushB or flushedA ~= true or flushedB ~= true then
295
+ return Exchange.Resolve(deps, sideA, sideB, exchangeId, digest, "Abort", "a stake could not be proved durable")
296
+ end
297
+ if Clock.Monotonic() > deadline then
298
+ return Exchange.Resolve(deps, sideA, sideB, exchangeId, digest, "Abort", "the attempt passed its deadline")
299
+ end
300
+
301
+ return Exchange.Resolve(deps, sideA, sideB, exchangeId, digest, "Commit", nil)
302
+ end
303
+
304
+ --- Propose a verdict and carry both profiles to their terminal state. Separated from
305
+ --- Attempt because this is exactly what a later load or cadence tick runs to finish an
306
+ --- exchange nobody is watching any more.
307
+ function Exchange.Resolve(
308
+ deps: any,
309
+ sideA: Side,
310
+ sideB: Side,
311
+ exchangeId: string,
312
+ digest: string,
313
+ proposed: string,
314
+ note: string?
315
+ ): (string?, string?)
316
+ -- Released by OWNERSHIP, never by user id alone, on every exit including the ones
317
+ -- that give up. See the registration in Attempt.
318
+ local function release()
319
+ if deps.InFlight == nil then
320
+ return
321
+ end
322
+ if deps.InFlight[sideA.UserId] == exchangeId then
323
+ deps.InFlight[sideA.UserId] = nil
324
+ end
325
+ if deps.InFlight[sideB.UserId] == exchangeId then
326
+ deps.InFlight[sideB.UserId] = nil
327
+ end
328
+ end
329
+
330
+ local verdict, _decided, err = ExchangeVerdict.Propose(deps.VerdictStore, exchangeId, {
331
+ V = proposed,
332
+ A = sideA.UserId,
333
+ B = sideB.UserId,
334
+ D = digest,
335
+ })
336
+ if verdict == nil then
337
+ -- No verdict is KNOWN, which is not the same as none existing. The records stay
338
+ -- exactly as they are and the next resolution settles which.
339
+ release()
340
+ return nil, `no verdict could be established: {tostring(err)}`
341
+ end
342
+
343
+ local matches, whyNot = ExchangeVerdict.Matches(verdict, digest, sideA.UserId, sideB.UserId)
344
+ if not matches then
345
+ -- Corruption, not an expected branch. Refuse to settle and leave both records in
346
+ -- place for an operator rather than move value nobody agreed to move.
347
+ --
348
+ -- The registrations are still RELEASED: the sweep skips any player named in the set,
349
+ -- so holding them would silence the one exchange that needs a human to look at it.
350
+ release()
351
+ return nil, `verdict does not govern this exchange: {tostring(whyNot)}`
352
+ end
353
+
354
+ -- 0.12 SETTLE BOTH. Infallible by construction; a failure here is a bug, not a
355
+ -- data-dependent refusal, and it leaves the record for the next resolution.
356
+ for _, side in { sideA, sideB } do
357
+ pcall(ExchangeLeg.Settle, side.Ctx, exchangeId, verdict)
358
+ end
359
+
360
+ -- 0.13 and 0.14. A false from these flushes is unresolved, not failed, and delivery
361
+ -- failures PARK rather than failing the exchange.
362
+ pcall(deps.Flush, sideA)
363
+ pcall(deps.Flush, sideB)
364
+ for _, side in { sideA, sideB } do
365
+ pcall(ExchangeLeg.Deliver, side.Ctx, exchangeId)
366
+ end
367
+
368
+ release()
369
+
370
+ local outcome = if verdict.V == "Commit" then "Committed" else "Aborted"
371
+ return outcome, note
372
+ end
373
+
374
+ --- Who the two participants are, from one side's own record.
375
+ ---
376
+ --- A resolution usually runs with only ONE profile loaded, so the userIds cannot come
377
+ --- from the caller. Role says which side this profile is and Partner is the other.
378
+ --- Getting it backwards fails the Matches check rather than settling the wrong exchange.
379
+ local function participantsOf(record: any, ownerId: number): (number, number)
380
+ local partner = record.Partner
381
+ if type(partner) ~= "number" then
382
+ return ownerId, ownerId
383
+ end
384
+ if record.Role == "B" then
385
+ return partner, ownerId
386
+ end
387
+ return ownerId, partner
388
+ end
389
+
390
+ --- Carry ONE profile's side of an exchange to its terminal state, without the
391
+ --- counterparty. What a load or a cadence tick runs. Safe alone because settle and
392
+ --- delivery are per-profile and idempotent: the verdict key is first-writer-wins, so
393
+ --- the other side reaches the identical verdict whenever it next looks. Proposes ABORT
394
+ --- when no verdict exists, the conserving default. Yields; never call it with a
395
+ --- transaction open.
396
+ function Exchange.ResolveOne(deps: any, side: Side, exchangeId: string): (string?, string?)
397
+ if type(deps) ~= "table" or deps.VerdictStore == nil then
398
+ fail("ResolveOne needs a VerdictStore")
399
+ end
400
+ if type(exchangeId) ~= "string" or #exchangeId == 0 then
401
+ fail("ResolveOne needs an exchange id")
402
+ end
403
+
404
+ local record = recordOf(side, exchangeId)
405
+ if record == nil then
406
+ -- No record: either nothing was ever staked here, or this side has already
407
+ -- settled. Either way an inbox entry may still be waiting, and delivering it is
408
+ -- the whole reason a resolution runs on every load.
409
+ pcall(ExchangeLeg.Deliver, side.Ctx, exchangeId)
410
+ return "Settled", nil
411
+ end
412
+
413
+ local userIdA, userIdB = participantsOf(record, side.UserId)
414
+ local digest = record.Digest
415
+ if type(digest) ~= "string" then
416
+ return nil, `exchange "{exchangeId}" has no digest to settle against`
417
+ end
418
+
419
+ local verdict, _decided, err = ExchangeVerdict.Propose(deps.VerdictStore, exchangeId, {
420
+ V = "Abort",
421
+ A = userIdA,
422
+ B = userIdB,
423
+ D = digest,
424
+ })
425
+ if verdict == nil then
426
+ -- No verdict is KNOWN, which is not the same as none existing. Nothing may be
427
+ -- released and the record stays as it is.
428
+ return nil, `no verdict could be established: {tostring(err)}`
429
+ end
430
+
431
+ local matches, whyNot = ExchangeVerdict.Matches(verdict, digest, userIdA, userIdB)
432
+ if not matches then
433
+ return nil, `verdict does not govern this exchange: {tostring(whyNot)}`
434
+ end
435
+
436
+ -- Settle then deliver, both per-profile. A settle that reverts and re-runs from the
437
+ -- same verdict produces the identical result.
438
+ pcall(ExchangeLeg.Settle, side.Ctx, exchangeId, verdict)
439
+ pcall(ExchangeLeg.Deliver, side.Ctx, exchangeId)
440
+
441
+ return (if verdict.V == "Commit" then "Committed" else "Aborted"), nil
442
+ end
443
+
444
+ --- One leg, copied out rather than aliased.
445
+ local function openLeg(leg: any): OpenLeg
446
+ return {
447
+ Path = if type(leg.Path) == "table" then table.clone(leg.Path) else {},
448
+ Kind = tostring(leg.Kind),
449
+ -- An array leg's key IS its value and may be a table, so it is cloned rather
450
+ -- than handed out of the reserved root by reference.
451
+ Key = if type(leg.Key) == "table" then Util.deepClone(leg.Key) else leg.Key,
452
+ Amount = if type(leg.Amount) == "number" then leg.Amount else nil,
453
+ }
454
+ end
455
+
456
+ local function openLegs(legs: any): { OpenLeg }
457
+ local out = {}
458
+ if type(legs) == "table" then
459
+ for _, leg in legs do
460
+ if type(leg) == "table" then
461
+ table.insert(out, openLeg(leg))
462
+ end
463
+ end
464
+ end
465
+ return out
466
+ end
467
+
468
+ --- Everything this profile still has in flight, WITH what it is holding.
469
+ ---
470
+ --- Escrow takes value out of the balance on purpose, and the resolution time is
471
+ --- deliberately not bounded, so a player whose exchange stalls has to be shown what they
472
+ --- staked and what they are owed. The game cannot read either otherwise: the ledger is
473
+ --- ServerOnly and the accessor refuses reserved-root reads.
474
+ ---
475
+ --- Every table returned is freshly built. Nothing here aliases the reserved root.
476
+ function Exchange.OpenExchanges(side: Side): { OpenExchange }
477
+ local reserved = side.Ctx.Tree.Reserved
478
+ local records = reserved.Exchange.Get() :: { [string]: any }?
479
+ local inbox = reserved.ExchangeInbox.Get() :: { [string]: any }?
480
+ local byId: { [string]: OpenExchange } = {}
481
+ local ids: { string } = {}
482
+
483
+ if type(records) == "table" then
484
+ for exchangeId, record in records do
485
+ if type(record) == "table" then
486
+ byId[exchangeId] = {
487
+ Id = exchangeId,
488
+ State = if record.Phase == "Staked" then "Staked" else "Claimed",
489
+ Partner = if type(record.Partner) == "number" then record.Partner else nil,
490
+ Staked = openLegs(record.Escrow),
491
+ Owed = openLegs(record.Take),
492
+ Since = if type(record.StakedAt) == "number" then record.StakedAt else nil,
493
+ }
494
+ table.insert(ids, exchangeId)
495
+ end
496
+ end
497
+ end
498
+
499
+ -- An inbox entry outranks the record: it means the verdict landed and the only
500
+ -- thing left is putting the value somewhere, which is a different thing to tell a
501
+ -- player than "still being agreed".
502
+ if type(inbox) == "table" then
503
+ for exchangeId, entry in inbox do
504
+ if type(entry) == "table" then
505
+ -- Bound non-optional up front rather than assigned inside the nil
506
+ -- branch: an assignment there does not narrow the local, so every use
507
+ -- below would still carry the optional.
508
+ local existing: OpenExchange? = byId[exchangeId]
509
+ local open: OpenExchange = existing
510
+ or {
511
+ Id = exchangeId,
512
+ State = "Delivering",
513
+ Partner = nil,
514
+ Staked = {},
515
+ Owed = {},
516
+ Since = nil,
517
+ }
518
+ if existing == nil then
519
+ byId[exchangeId] = open
520
+ table.insert(ids, exchangeId)
521
+ end
522
+ open.State = "Delivering"
523
+ open.Owed = openLegs(entry.Legs)
524
+ if type(entry.SettledAt) == "number" then
525
+ open.Since = entry.SettledAt
526
+ end
527
+ end
528
+ end
529
+ end
530
+
531
+ table.sort(ids)
532
+ local out = {}
533
+ for _, exchangeId in ids do
534
+ table.insert(out, byId[exchangeId])
535
+ end
536
+ return out
537
+ end
538
+
539
+ function Exchange.OpenExchangeIds(side: Side): { string }
540
+ local ids, seen = {}, {}
541
+ local reserved = side.Ctx.Tree.Reserved
542
+ for _, container in { reserved.Exchange.Get(), reserved.ExchangeInbox.Get() } do
543
+ if type(container) == "table" then
544
+ for exchangeId in container do
545
+ if not seen[exchangeId] then
546
+ seen[exchangeId] = true
547
+ table.insert(ids, exchangeId)
548
+ end
549
+ end
550
+ end
551
+ end
552
+ table.sort(ids)
553
+ return ids
554
+ end
555
+
556
+ return Exchange