-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroundFinalizationService.ts
More file actions
1474 lines (1350 loc) · 44.5 KB
/
roundFinalizationService.ts
File metadata and controls
1474 lines (1350 loc) · 44.5 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
// Purpose: finalize closed auction rounds with verified winners and ledger settlement.
import { randomUUID } from "node:crypto";
import { ObjectId, type AnyBulkWriteOperation, type WithId } from "mongodb";
import type { ServiceDependencies } from "../../shared/service.js";
import { runMongoTransaction } from "../../shared/storage/mongoTransaction.js";
import { buildMerkleRootFromPayloads } from "../../shared/crypto/merkle.js";
import type { RoundProofPayload, SignedRoundProof } from "../../shared/auctionProof.js";
import {
mongoCollections,
type AuctionDocument,
type AuctionRoundConfig,
type AuctionRoundStateDocument,
type BidDocument,
type DeliveryRecordDocument,
type LedgerAccountDocument,
type LedgerEntryDocument,
type NotificationQueueDocument,
type RoundResultDocument
} from "../../shared/storage/mongoSchemas.js";
import { publishRealtimeEvent } from "../../shared/realtime/events.js";
import { computeExpiresAt, resolveRetentionMs } from "../../shared/storage/retention.js";
import { buildRankingKey, buildTopKey } from "./auctionKeys.js";
import { buildRankingMember, parseRankingMember } from "./bidRanking.js";
const holdLookupBatchSize = 500;
const holdSettlementBatchSize = 250;
const notificationBatchSize = 200;
const topSetTtlSeconds = 10;
const finalizationLockTtlMs = 120000;
const rankingTopSetScript = `
local rankingKey = KEYS[1]
local topKey = KEYS[2]
local topCount = tonumber(ARGV[1])
local topTtl = tonumber(ARGV[2])
local removeCount = tonumber(ARGV[3]) or 0
local index = 4
if removeCount > 0 then
local removeMembers = {}
for i = 1, removeCount do
removeMembers[i] = ARGV[index]
index = index + 1
end
redis.call("ZREM", rankingKey, unpack(removeMembers))
end
redis.call("DEL", topKey)
if topCount and topCount > 0 then
local topMembers = redis.call("ZREVRANGE", rankingKey, 0, topCount - 1)
local bidIds = {}
for i = 1, #topMembers do
local member = topMembers[i]
local sep = string.find(member, ":")
if sep then
local bidId = string.sub(member, sep + 1)
if bidId and bidId ~= "" then
table.insert(bidIds, bidId)
end
end
end
if #bidIds > 0 then
redis.call("SADD", topKey, unpack(bidIds))
if topTtl and topTtl > 0 then
redis.call("EXPIRE", topKey, topTtl)
end
end
end
return 1
`;
type MongoRankedBid = {
bidId: ObjectId;
userId: string;
amount: number;
createdAt: Date;
};
type RoundFinalizationSummary = {
auctionId: ObjectId;
roundIndex: number;
winnerCount: number;
settlementCompleted: boolean;
};
type DeliveryReceipt = {
deliveryRef: string;
deliveryType?: DeliveryRecordDocument["deliveryType"];
deliveryPayload?: Record<string, unknown> | null;
};
type HoldSettlementAction = "capture" | "release";
type SettlementBidSnapshot = Pick<WithId<BidDocument>, "_id" | "userId" | "amount" | "createdAt">;
type HoldSettlementInput = {
bidId: ObjectId;
userId: string;
amount: number;
action: HoldSettlementAction;
};
type HoldSettlement = {
holdId: string;
bidId: ObjectId;
userId: string;
amount: number;
currency: string;
action: HoldSettlementAction;
};
type HoldResolutionEntry = Pick<
LedgerEntryDocument,
"entryType" | "userId" | "amount" | "currency" | "idempotencyKey" | "metadata"
>;
type HoldEntrySnapshot = Pick<
LedgerEntryDocument,
"userId" | "currency" | "amount" | "metadata"
>;
export function createRoundFinalizationService(deps: ServiceDependencies) {
const auctions = deps.mongo.db.collection<AuctionDocument>(mongoCollections.auctions);
const roundStates = deps.mongo.db.collection<AuctionRoundStateDocument>(
mongoCollections.auctionRoundStates
);
const bids = deps.mongo.db.collection<BidDocument>(mongoCollections.bids);
const roundResults = deps.mongo.db.collection<RoundResultDocument>(mongoCollections.roundResults);
const deliveryRecords = deps.mongo.db.collection<DeliveryRecordDocument>(
mongoCollections.deliveryRecords
);
const ledgerAccounts = deps.mongo.db.collection<LedgerAccountDocument>(
mongoCollections.ledgerAccounts
);
const ledgerEntries = deps.mongo.db.collection<LedgerEntryDocument>(mongoCollections.ledgerEntries);
const notificationQueue = deps.mongo.db.collection<NotificationQueueDocument>(
mongoCollections.notificationQueue
);
const ledgerRetentionMs = resolveRetentionMs(deps.config.dataRetention.ledgerDays);
const bidRetentionMs = resolveRetentionMs(deps.config.dataRetention.bidsDays);
async function finalizeClosedRounds(limit = 25): Promise<number> {
const closedRounds = await roundStates
.find({ status: "closed", settlementCompletedAt: { $exists: false } })
.sort({ closedAt: 1, effectiveEndAt: 1 })
.limit(limit)
.toArray();
let finalized = 0;
for (const state of closedRounds) {
const summary = await finalizeRound(state.auctionId, state.roundIndex);
if (summary) {
finalized += 1;
}
}
return finalized;
}
// Finalize a closed round with re-entrant settlement steps.
async function finalizeRound(
auctionId: ObjectId,
roundIndex: number
): Promise<RoundFinalizationSummary | null> {
const auction = await auctions.findOne({ _id: auctionId });
if (!auction) {
throw new Error(`Auction not found for round finalization: ${auctionId.toHexString()}.`);
}
const roundState = await roundStates.findOne({ auctionId, roundIndex });
if (!roundState || roundState.status !== "closed") {
return null;
}
if (!roundState.settlementCompletedAt) {
const locked = await acquireFinalizationLock(auctionId, roundIndex);
if (!locked) {
return null;
}
}
const existingResult = await roundResults.findOne({ auctionId, roundIndex });
let winners = existingResult?.winners ?? [];
let settlementCompleted = Boolean(existingResult?.settlementCompletedAt);
const isFinalRound = isFinalRoundIndex(auction.rounds, roundIndex);
if (existingResult?.finalizedAt) {
await markRoundFinalized(auctionId, roundIndex, existingResult.finalizedAt);
}
if (existingResult?.settlementCompletedAt) {
await markRoundSettlementCompleted(
auctionId,
roundIndex,
existingResult.settlementCompletedAt
);
}
if (!existingResult) {
winners = await resolveRoundWinners(auction, roundIndex);
const now = new Date();
const proof = await buildRoundProof(auction, roundState, roundIndex, winners, now);
const insertDoc: Record<string, unknown> = {
auctionId,
roundIndex,
winners,
merkleRoot: proof.merkleRoot,
merkleCount: proof.merkleCount,
finalizedAt: now,
createdAt: now
};
if (proof.signedProof) {
insertDoc.proof = proof.signedProof;
}
await roundResults.updateOne(
{ auctionId, roundIndex },
{ $setOnInsert: insertDoc },
{ upsert: true }
);
await markRoundFinalized(auctionId, roundIndex, now);
} else if (!existingResult.merkleRoot || !existingResult.proof) {
const finalizedAt = existingResult.finalizedAt ?? new Date();
const proof = await buildRoundProof(
auction,
roundState,
roundIndex,
winners,
finalizedAt
);
const updateDoc: Record<string, unknown> = {
merkleRoot: proof.merkleRoot,
merkleCount: proof.merkleCount
};
if (proof.signedProof) {
updateDoc.proof = proof.signedProof;
}
await roundResults.updateOne(
{ auctionId, roundIndex },
{ $set: updateDoc }
);
}
if (!settlementCompleted) {
const activeBids = await loadActiveBids(auctionId);
const deliveryRefs = await ensureDeliveryRecords(auction, roundIndex, winners);
const winnerUsers = new Set(winners.map((winner) => winner.userId));
const winnerUserIds = Array.from(winnerUsers);
const loserUserIds = Array.from(
new Set(
activeBids.filter((bid) => !winnerUsers.has(bid.userId)).map((bid) => bid.userId)
)
);
const settlementUserIds = isFinalRound
? Array.from(new Set([...winnerUserIds, ...loserUserIds]))
: winnerUserIds;
const settlementBids = await loadUnsettledBids(auctionId, settlementUserIds);
const cutoffBid =
auction.pricingMode === "cutoff"
? await resolveCutoffBid(auction, roundIndex)
: null;
await settleRoundHolds(
auction,
roundIndex,
settlementBids,
winners,
cutoffBid,
isFinalRound
);
await markBidSettlement(auctionId, roundIndex, winnerUserIds, loserUserIds, isFinalRound);
await updateRedisRankingAfterSettlement(
auction,
roundIndex,
activeBids,
winnerUsers,
isFinalRound
);
try {
if (settlementUserIds.length > 0) {
await publishRealtimeEvent(deps.redis, {
type: "bids.active.updated",
userIds: settlementUserIds
});
await publishRealtimeEvent(deps.redis, {
type: "balance.updated",
userIds: settlementUserIds,
currency: auction.currency
});
}
await publishRealtimeEvent(deps.redis, {
type: "auction.bids.updated",
auctionId: auction._id.toHexString()
});
} catch (error) {
deps.logger.warn({ err: error }, "Failed to publish realtime settlement updates");
}
await queueRoundNotifications(auction, roundIndex, activeBids, winners, deliveryRefs);
const settledAt = new Date();
await roundResults.updateOne(
{ auctionId, roundIndex },
{ $set: { settlementCompletedAt: settledAt } }
);
settlementCompleted = true;
await markRoundSettlementCompleted(auctionId, roundIndex, settledAt);
}
return {
auctionId,
roundIndex,
winnerCount: winners.length,
settlementCompleted
};
}
async function markRoundFinalized(
auctionId: ObjectId,
roundIndex: number,
finalizedAt: Date
): Promise<void> {
await roundStates.updateOne(
{ auctionId, roundIndex, finalizedAt: { $exists: false } },
{ $set: { finalizedAt, updatedAt: finalizedAt } }
);
}
async function markRoundSettlementCompleted(
auctionId: ObjectId,
roundIndex: number,
settledAt: Date
): Promise<void> {
await roundStates.updateOne(
{ auctionId, roundIndex, settlementCompletedAt: { $exists: false } },
{ $set: { settlementCompletedAt: settledAt, updatedAt: settledAt } }
);
}
async function acquireFinalizationLock(
auctionId: ObjectId,
roundIndex: number
): Promise<boolean> {
const now = new Date();
const staleBefore = new Date(now.getTime() - finalizationLockTtlMs);
const result = await roundStates.findOneAndUpdate(
{
auctionId,
roundIndex,
status: "closed",
settlementCompletedAt: { $exists: false },
$or: [
{ finalizationLockedAt: { $exists: false } },
{ finalizationLockedAt: { $lte: staleBefore } }
]
},
{ $set: { finalizationLockedAt: now, updatedAt: now } },
{ returnDocument: "after" }
);
return Boolean(result);
}
async function resolveRoundWinners(
auction: WithId<AuctionDocument>,
roundIndex: number
): Promise<RoundResultDocument["winners"]> {
const roundConfig = findRoundConfig(auction.rounds, roundIndex);
const allocationSize = Math.max(0, Math.floor(roundConfig.allocationSize));
if (allocationSize === 0) {
return [];
}
const redisTop = await loadRedisTopBids(
deps,
auction._id.toHexString(),
allocationSize
);
const mongoTop = await loadMongoTopBids(auction._id, allocationSize);
const redisBidIds = redisTop.map((entry) => entry.bidId);
const mongoBidIds = mongoTop.map((entry) => entry.bidId.toHexString());
const rankingMatch = rankingsMatch(redisTop, mongoTop);
if (!rankingMatch && redisBidIds.length > 0) {
deps.logger.warn(
{ auctionId: auction._id.toHexString(), roundIndex, redisBidIds, mongoBidIds },
"Redis ranking mismatch detected; using MongoDB ordering."
);
}
return mongoTop.map((entry, index) => ({
userId: entry.userId,
bidId: entry.bidId,
amount: entry.amount,
rank: index + 1
}));
}
async function resolveCutoffBid(
auction: WithId<AuctionDocument>,
roundIndex: number
): Promise<MongoRankedBid | null> {
const roundConfig = findRoundConfig(auction.rounds, roundIndex);
const allocationSize = Math.max(0, Math.floor(roundConfig.allocationSize));
if (allocationSize <= 0) {
return null;
}
const limit = allocationSize + 1;
const redisTop = await loadRedisTopBids(deps, auction._id.toHexString(), limit);
const mongoTop = await loadMongoTopBids(auction._id, limit);
const redisBidIds = redisTop.map((entry) => entry.bidId);
const mongoBidIds = mongoTop.map((entry) => entry.bidId.toHexString());
const rankingMatch = rankingsMatch(redisTop, mongoTop);
if (!rankingMatch && redisBidIds.length > 0) {
deps.logger.warn(
{ auctionId: auction._id.toHexString(), roundIndex, redisBidIds, mongoBidIds },
"Redis ranking mismatch detected; using MongoDB ordering."
);
}
return mongoTop.length > allocationSize ? mongoTop[allocationSize] ?? null : null;
}
async function buildRoundProof(
auction: WithId<AuctionDocument>,
roundState: WithId<AuctionRoundStateDocument>,
roundIndex: number,
winners: RoundResultDocument["winners"],
finalizedAt: Date
): Promise<{ merkleRoot: string; merkleCount: number; signedProof: SignedRoundProof | null }> {
const roundConfig = findRoundConfig(auction.rounds, roundIndex);
const bidPayloads = await loadRoundBidsForProof(auction._id, roundIndex);
const { root } = buildMerkleRootFromPayloads(bidPayloads);
const payload: RoundProofPayload = {
auctionId: auction._id.toHexString(),
roundIndex,
allocationSize: roundConfig.allocationSize,
roundStartAt: roundConfig.startAt.toISOString(),
roundEndAt: roundConfig.endAt.toISOString(),
effectiveEndAt: roundState.effectiveEndAt?.toISOString() ?? null,
extensionCount: roundState.extensionCount ?? null,
antiSniping: {
triggerWindowSeconds: roundConfig.antiSniping.triggerWindowSeconds,
extensionSeconds: roundConfig.antiSniping.extensionSeconds,
maxExtensions: roundConfig.antiSniping.maxExtensions
},
bidsRoot: root,
bidsCount: bidPayloads.length,
winners: winners.map((winner) => ({
userId: winner.userId,
bidId: winner.bidId.toHexString(),
amount: winner.amount,
rank: winner.rank
})),
finalizedAt: finalizedAt.toISOString()
};
let signedProof: SignedRoundProof | null = null;
try {
signedProof = await signRoundProof(payload);
} catch (error) {
deps.logger.warn({ err: error }, "Failed to sign round proof");
}
return { merkleRoot: root, merkleCount: bidPayloads.length, signedProof };
}
async function loadRoundBidsForProof(
auctionId: ObjectId,
roundIndex: number
): Promise<Array<Record<string, unknown>>> {
const docs = await bids
.find({ auctionId, roundIndex })
.sort({ createdAt: 1, _id: 1 })
.project<Pick<WithId<BidDocument>, "_id" | "userId" | "amount" | "maxAmount" | "createdAt" | "origin">>({
_id: 1,
userId: 1,
amount: 1,
maxAmount: 1,
createdAt: 1,
origin: 1
})
.toArray();
return docs.map((bid) => ({
bidId: bid._id.toHexString(),
userId: bid.userId,
amount: bid.amount,
maxAmount: bid.maxAmount ?? null,
createdAt: bid.createdAt.toISOString(),
origin: bid.origin ?? "manual"
}));
}
async function signRoundProof(payload: RoundProofPayload): Promise<SignedRoundProof | null> {
const signerUrl = deps.config.crypto.signerUrl.trim();
const signerToken = deps.config.crypto.signerToken.trim();
if (!signerUrl || signerUrl.toLowerCase() === "mock") {
return null;
}
if (!signerToken) {
throw new Error("Signer token is required to sign round proofs.");
}
const url = `${normalizeBaseUrl(signerUrl)}/signer/sign-round-result`;
const response = await fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
"x-signer-token": signerToken
},
body: JSON.stringify({ payload })
});
if (!response.ok) {
throw new Error(`Round proof signer failed with ${response.status}.`);
}
const json = (await response.json()) as { signedPayload?: SignedRoundProof };
if (!json?.signedPayload) {
throw new Error("Round proof signer returned an invalid payload.");
}
return json.signedPayload;
}
async function loadActiveBids(
auctionId: ObjectId
): Promise<Array<Pick<WithId<BidDocument>, "_id" | "userId" | "amount" | "createdAt">>> {
return bids
.find({ auctionId, active: true })
.project<Pick<WithId<BidDocument>, "_id" | "userId" | "amount" | "createdAt">>({
_id: 1,
userId: 1,
amount: 1,
createdAt: 1
})
.toArray();
}
async function loadUnsettledBids(
auctionId: ObjectId,
userIds: string[]
): Promise<SettlementBidSnapshot[]> {
if (userIds.length === 0) {
return [];
}
return bids
.find({
auctionId,
userId: { $in: userIds },
settledAt: { $exists: false }
})
.project<SettlementBidSnapshot>({
_id: 1,
userId: 1,
amount: 1,
createdAt: 1
})
.toArray();
}
async function loadMongoTopBids(
auctionId: ObjectId,
limit: number
): Promise<MongoRankedBid[]> {
const docs = await bids
.find({ auctionId, active: true })
.sort({ amount: -1, createdAt: 1, _id: 1, userId: 1 })
.limit(limit)
.project<Pick<WithId<BidDocument>, "_id" | "userId" | "amount" | "createdAt">>({
_id: 1,
userId: 1,
amount: 1,
createdAt: 1
})
.toArray();
return docs.map((doc) => ({
bidId: doc._id,
userId: doc.userId,
amount: doc.amount,
createdAt: doc.createdAt
}));
}
async function loadRedisTopBids(
serviceDeps: ServiceDependencies,
auctionId: string,
limit: number
): Promise<Array<{ bidId: string; amount: number }>> {
if (limit <= 0) {
return [];
}
const rankingKey = buildRankingKey(auctionId);
let entries: string[] = [];
try {
entries = await serviceDeps.redis.zrevrange(
rankingKey,
0,
limit - 1,
"WITHSCORES"
);
} catch (error) {
serviceDeps.logger.warn({ err: error }, "Failed to read Redis ranking for winners");
return [];
}
const results: Array<{ bidId: string; amount: number }> = [];
for (let index = 0; index < entries.length; index += 2) {
const member = entries[index];
const score = entries[index + 1];
if (!member || !score) {
continue;
}
const parsed = parseRankingMember(member);
if (!parsed.bidId) {
continue;
}
const amount = Number(score);
if (!Number.isFinite(amount)) {
continue;
}
results.push({ bidId: parsed.bidId, amount });
}
return results;
}
async function ensureDeliveryRecords(
auction: WithId<AuctionDocument>,
roundIndex: number,
winners: RoundResultDocument["winners"]
): Promise<Map<string, DeliveryReceipt>> {
const deliveryRefByUser = new Map<string, DeliveryReceipt>();
if (winners.length === 0) {
return deliveryRefByUser;
}
const now = new Date();
const deliveryType = resolveDeliveryType(auction);
const operations = winners.map((winner) => {
const receipt = buildDeliveryReceipt(
deliveryType,
auction._id.toHexString(),
roundIndex,
winner.userId,
winner.rank
);
deliveryRefByUser.set(winner.userId, receipt);
return {
updateOne: {
filter: { auctionId: auction._id, roundIndex, userId: winner.userId },
update: {
$setOnInsert: {
auctionId: auction._id,
roundIndex,
userId: winner.userId,
deliveryRef: receipt.deliveryRef,
deliveryType: receipt.deliveryType,
deliveryPayload: receipt.deliveryPayload ?? undefined,
status: "delivered" as const,
deliveredAt: now,
createdAt: now
}
},
upsert: true
}
};
});
await deliveryRecords.bulkWrite(operations, { ordered: false });
return deliveryRefByUser;
}
async function settleRoundHolds(
auction: WithId<AuctionDocument>,
roundIndex: number,
settlementBids: SettlementBidSnapshot[],
winners: RoundResultDocument["winners"],
cutoffBid: MongoRankedBid | null,
isFinalRound: boolean
): Promise<void> {
if (settlementBids.length === 0) {
return;
}
const settlements = await buildHoldSettlementPlan(
auction,
settlementBids,
winners,
cutoffBid,
isFinalRound
);
if (settlements.length === 0) {
return;
}
const operations = await buildHoldSettlements(auction, settlements);
await settleHoldOperations(auction, roundIndex, operations);
}
// Resolve per-bid hold allocations so winners pay the correct price and escrow is fully released.
async function buildHoldSettlementPlan(
auction: WithId<AuctionDocument>,
settlementBids: SettlementBidSnapshot[],
winners: RoundResultDocument["winners"],
cutoffBid: MongoRankedBid | null,
isFinalRound: boolean
): Promise<HoldSettlementInput[]> {
if (settlementBids.length === 0) {
return [];
}
const holdIds = settlementBids.map((bid) => buildHoldId(bid._id.toHexString()));
const holdEntries = await loadHoldEntries(holdIds);
const bidsByUser = new Map<
string,
Array<{ bid: SettlementBidSnapshot; holdId: string; holdAmount: number }>
>();
for (const bid of settlementBids) {
const holdId = buildHoldId(bid._id.toHexString());
const holdEntry = holdEntries.get(holdId);
if (!holdEntry) {
throw new Error(`Hold entry missing for bid ${bid._id.toHexString()}.`);
}
if (holdEntry.userId !== bid.userId) {
throw new Error(`Hold user mismatch for bid ${bid._id.toHexString()}.`);
}
if (holdEntry.currency !== auction.currency) {
throw new Error(`Hold currency mismatch for bid ${bid._id.toHexString()}.`);
}
const existing = bidsByUser.get(bid.userId);
const entry = {
bid,
holdId,
holdAmount: holdEntry.amount
};
if (existing) {
existing.push(entry);
} else {
bidsByUser.set(bid.userId, [entry]);
}
}
const winnersByUser = new Map(
winners.map((winner) => [winner.userId, winner] as const)
);
const minIncrement = normalizeNonNegative(auction.minIncrement);
const cutoffPrice =
auction.pricingMode === "cutoff" && cutoffBid
? normalizeNonNegative(cutoffBid.amount + minIncrement)
: null;
const settlements: HoldSettlementInput[] = [];
for (const [userId, bids] of bidsByUser) {
const winner = winnersByUser.get(userId) ?? null;
if (!winner) {
if (!isFinalRound) {
continue;
}
for (const entry of bids) {
if (entry.holdAmount > 0) {
settlements.push({
bidId: entry.bid._id,
userId,
amount: entry.holdAmount,
action: "release"
});
}
}
continue;
}
const targetCharge =
cutoffPrice !== null
? Math.min(normalizeNonNegative(winner.amount), cutoffPrice)
: normalizeNonNegative(winner.amount);
const totalHold = bids.reduce((sum, entry) => sum + entry.holdAmount, 0);
if (targetCharge > totalHold + 1e-9) {
throw new Error(`Hold total below required charge for user ${userId}.`);
}
const ordered = [...bids].sort((left, right) => {
const timeDelta = left.bid.createdAt.getTime() - right.bid.createdAt.getTime();
if (timeDelta !== 0) {
return timeDelta;
}
return left.bid._id.toHexString().localeCompare(right.bid._id.toHexString());
});
let remaining = targetCharge;
for (const entry of ordered) {
const captureAmount = remaining > 0 ? Math.min(remaining, entry.holdAmount) : 0;
const releaseAmount = entry.holdAmount - captureAmount;
if (captureAmount > 1e-9) {
settlements.push({
bidId: entry.bid._id,
userId,
amount: normalizeSettlementAmount(captureAmount),
action: "capture"
});
}
if (releaseAmount > 1e-9) {
settlements.push({
bidId: entry.bid._id,
userId,
amount: normalizeSettlementAmount(releaseAmount),
action: "release"
});
}
remaining -= captureAmount;
}
if (remaining > 1e-6) {
throw new Error(`Hold allocation incomplete for user ${userId}.`);
}
}
return settlements;
}
async function buildHoldSettlements(
auction: WithId<AuctionDocument>,
bidsForSettlement: HoldSettlementInput[]
): Promise<HoldSettlement[]> {
if (bidsForSettlement.length === 0) {
return [];
}
const holdIds = new Set<string>();
const totalsByHoldId = new Map<string, number>();
const bidsByHoldKey = new Map<string, HoldSettlementInput>();
for (const bid of bidsForSettlement) {
const holdId = buildHoldId(bid.bidId.toHexString());
const key = `${holdId}:${bid.action}`;
if (bidsByHoldKey.has(key)) {
throw new Error(`Duplicate hold settlement requested for ${key}.`);
}
bidsByHoldKey.set(key, bid);
holdIds.add(holdId);
totalsByHoldId.set(holdId, (totalsByHoldId.get(holdId) ?? 0) + bid.amount);
}
const holdEntries = await loadHoldEntries(Array.from(holdIds));
const settlements: HoldSettlement[] = [];
for (const bid of bidsByHoldKey.values()) {
const holdId = buildHoldId(bid.bidId.toHexString());
const holdEntry = holdEntries.get(holdId);
if (!holdEntry) {
throw new Error(`Hold entry missing for bid ${bid.bidId.toHexString()}.`);
}
if (holdEntry.userId !== bid.userId) {
throw new Error(`Hold user mismatch for bid ${bid.bidId.toHexString()}.`);
}
if (holdEntry.currency !== auction.currency) {
throw new Error(`Hold currency mismatch for bid ${bid.bidId.toHexString()}.`);
}
if (bid.amount > holdEntry.amount + 1e-9) {
throw new Error(`Hold settlement exceeds hold amount for ${holdId}.`);
}
settlements.push({
holdId,
bidId: bid.bidId,
userId: bid.userId,
amount: bid.amount,
currency: holdEntry.currency,
action: bid.action
});
}
for (const [holdId, total] of totalsByHoldId) {
const holdEntry = holdEntries.get(holdId);
if (!holdEntry) {
continue;
}
if (Math.abs(total - holdEntry.amount) > 1e-6) {
throw new Error(`Hold settlement incomplete for ${holdId}.`);
}
}
return settlements;
}
async function loadHoldEntries(holdIds: string[]): Promise<Map<string, HoldEntrySnapshot>> {
const entries = new Map<string, HoldEntrySnapshot>();
for (let index = 0; index < holdIds.length; index += holdLookupBatchSize) {
const batch = holdIds.slice(index, index + holdLookupBatchSize);
const results = await ledgerEntries
.find({ entryType: "hold_created", "metadata.holdId": { $in: batch } })
.project<HoldEntrySnapshot>({
userId: 1,
currency: 1,
amount: 1,
metadata: 1
})
.toArray();
for (const entry of results) {
const holdId = extractHoldId(entry.metadata);
if (holdId) {
entries.set(holdId, entry);
}
}
}
return entries;
}
async function settleHoldOperations(
auction: WithId<AuctionDocument>,
roundIndex: number,
operations: HoldSettlement[]
): Promise<void> {
if (operations.length === 0) {
return;
}
for (let index = 0; index < operations.length; index += holdSettlementBatchSize) {
const batch = operations.slice(index, index + holdSettlementBatchSize);
await settleHoldOperationsBatch(auction, roundIndex, batch);
}
}
async function settleHoldOperationsBatch(
auction: WithId<AuctionDocument>,
roundIndex: number,
operations: HoldSettlement[]
): Promise<void> {
// Bulk resolve holds per batch, preserving idempotency checks while reducing round trips.
if (operations.length === 0) {
return;
}
const auctionId = auction._id.toHexString();
await runMongoTransaction(deps.mongo, async (session) => {
const holdIds = operations.map((entry) => entry.holdId);
const existingResolutions = await ledgerEntries
.find(
{
entryType: { $in: ["hold_released", "hold_captured"] },
"metadata.holdId": { $in: holdIds }
},
{ session }
)
.project<HoldResolutionEntry>({
entryType: 1,
userId: 1,
amount: 1,
currency: 1,
idempotencyKey: 1,
metadata: 1
})
.toArray();
const existingByHoldKey = new Map<string, HoldResolutionEntry>();
for (const entry of existingResolutions) {
const holdId = extractHoldId(entry.metadata);
if (!holdId) {
continue;
}
const key = `${holdId}:${entry.entryType}`;
if (existingByHoldKey.has(key)) {
throw new Error(`Hold resolved multiple times for ${key}.`);
}
existingByHoldKey.set(key, entry);
}
const now = new Date();
const entryOps: Array<AnyBulkWriteOperation<LedgerEntryDocument>> = [];
const accountIncrements = new Map<
string,
{
userId: string;
currency: string;
count: number;
totals: Partial<Record<LedgerEntryDocument["entryType"], number>>;
}
>();
const expiresAt = computeExpiresAt(now, ledgerRetentionMs);
for (const settlement of operations) {
const entryType = toHoldResolutionEntryType(settlement.action);
const idempotencyKey = buildSettlementIdempotencyKey(
auctionId,
roundIndex,
settlement.action,
settlement.holdId
);
const existing = existingByHoldKey.get(`${settlement.holdId}:${entryType}`);
if (existing) {
assertHoldResolutionMatches(existing, settlement, entryType, idempotencyKey);
continue;
}
const metadata = {
auctionId,
roundIndex,
bidId: settlement.bidId.toHexString(),
action: settlement.action,
holdId: settlement.holdId
};