-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauction.test.ts
More file actions
1589 lines (1291 loc) · 74.7 KB
/
Copy pathauction.test.ts
File metadata and controls
1589 lines (1291 loc) · 74.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
import { beforeAll, beforeEach, describe, setDefaultTimeout, test } from 'bun:test'
import { createWriteClient, WriteClient } from '../testsuite/simulator/utils/viem'
import { AnvilWindowEthereum } from '../testsuite/simulator/AnvilWindowEthereum'
import { TEST_TIMEOUT_MS, useIsolatedAnvilNode } from '../testsuite/simulator/useIsolatedAnvilNode'
import { TEST_ADDRESSES } from '../testsuite/simulator/utils/constants'
import { contractExists, getETHBalance, setupTestAccounts } from '../testsuite/simulator/utils/utilities'
import { encodeAbiParameters, keccak256, type Address } from 'viem'
import {
computeClearing,
deployUniformPriceDualCapBatchAuction,
finalize,
activeTickCount,
getActiveTickPage,
getBidCountAtTick,
getBidPageAtTick,
getBidderBidCount,
getBidderBidPage,
getClearingTick,
getMinBidSize,
getTickCount,
getTickSummary,
getTickPage,
getTotalRepPurchased,
simulateWithdrawBids,
isFinalized,
refundLosingBids,
startAuction,
submitBid,
withdrawBids,
getEthRaiseCap,
getEthRaised,
} from '../testsuite/simulator/utils/contracts/auction'
import { approximatelyEqual, ensureDefined, strictEqual18Decimal, strictEqualTypeSafe } from '../testsuite/simulator/utils/testUtils'
import { priceToClosestTick, tickToPrice } from '../testsuite/simulator/utils/tickMath'
import assert from 'assert'
import { ensureZoltarDeployed } from '../testsuite/simulator/utils/contracts/zoltar'
import { ensureInfraDeployed } from '../testsuite/simulator/utils/contracts/deployPeripherals'
import { getUniformPriceDualCapBatchAuctionAddress } from '../testsuite/simulator/utils/contracts/deployments'
import { addressString } from '../testsuite/simulator/utils/bigint'
import { peripherals_UniformPriceDualCapBatchAuction_UniformPriceDualCapBatchAuction } from '../types/contractArtifact'
// ============ MODULE-LEVEL CONSTANTS ============
const ATTOETH_PER_ETH = 10n ** 18n
const PRICE_PRECISION = ATTOETH_PER_ETH
const AUCTION_TIME = 604800n
const MIN_TICK = -524288n
const MAX_TICK = 524288n
const DEFAULT_TOLERANCE = 1000n
const DEFAULT_ETH_RAISE_CAP = 200_000n
const DEFAULT_MAX_REP = 100n
const AUCTION_NODES_SLOT = 0n
const AUCTION_BIDS_AT_TICK_SLOT = 1n
const AUCTION_REFUNDED_BID_PREFIX_TREE_SLOT = 2n
const AUCTION_ROOT_SLOT = 3n
const AUCTION_NEXT_ID_SLOT = 4n
const AUCTION_MAX_REP_BEING_SOLD_SLOT = 5n
const AUCTION_ETH_RAISE_CAP_SLOT = 6n
const BID_STRUCT_SLOT_COUNT = 4n
const NODE_STRUCT_SLOT_COUNT = 8n
const MAX_DISTINCT_TICK_COUNT = MAX_TICK - MIN_TICK + 1n
const FINALIZE_GAS_LIMIT = 20_000_000n
setDefaultTimeout(TEST_TIMEOUT_MS)
describe('Auction', () => {
const { getAnvilWindowEthereum, setBaselineSnapshot } = useIsolatedAnvilNode()
let mockWindow: AnvilWindowEthereum
let client: WriteClient
let auctionAddress: Address
// ============ Helper Functions ============
function createTestClient(idx: number): WriteClient {
const address = ensureDefined(TEST_ADDRESSES[idx], `TEST_ADDRESSES[${idx}] is undefined`)
return createWriteClient(mockWindow, address, 0)
}
function tickForPrice(price: bigint): bigint {
return priceToClosestTick(price)
}
async function submitBidAndVerifyLock(client: WriteClient, auctionAddress: Address, tick: bigint, bidAmount: bigint): Promise<bigint> {
const before = await getETHBalance(client, client.account.address)
await submitBid(client, auctionAddress, tick, bidAmount)
const after = await getETHBalance(client, client.account.address)
strictEqualTypeSafe(before - bidAmount, after, `bid ${bidAmount} not locked`)
return before
}
function assertClearing(clearing: { hitCap: boolean; foundTick: bigint; accumulatedEth: bigint }, expectedHitCap: boolean, expectedTick?: bigint, expectedAccumulatedEth?: bigint) {
strictEqualTypeSafe(clearing.hitCap, expectedHitCap, 'clearing.hitCap mismatch')
if (expectedHitCap && expectedTick !== undefined) strictEqualTypeSafe(clearing.foundTick, expectedTick, 'clearing.foundTick mismatch')
if (expectedAccumulatedEth !== undefined) strictEqualTypeSafe(clearing.accumulatedEth, expectedAccumulatedEth, 'clearing.accumulatedEth mismatch')
}
function assertExpectedClearing(clearing: { hitCap: boolean; foundTick: bigint; accumulatedEth: bigint }, expectedTick: bigint, expectedAccumulatedEth?: bigint): void {
assertClearing(clearing, true)
if (clearing.hitCap) strictEqualTypeSafe(clearing.foundTick, expectedTick, 'clearing tick mismatch')
if (expectedAccumulatedEth !== undefined) strictEqualTypeSafe(clearing.accumulatedEth, expectedAccumulatedEth, 'accumulatedEth mismatch')
}
async function finalizeAndVerify(client: WriteClient, auctionAddress: Address): Promise<void> {
await mockWindow.advanceTime(AUCTION_TIME + 1n)
await finalize(client, auctionAddress)
strictEqualTypeSafe(await isFinalized(client, auctionAddress), true, 'auction not finalized')
}
function assertWithdrawal(amounts: { totalFilledRep: bigint; totalEthRefund: bigint }, expectedFilledRep: bigint, expectedRefund: bigint, tolerance?: bigint) {
if (tolerance !== undefined) {
approximatelyEqual(amounts.totalFilledRep, expectedFilledRep, tolerance, 'filledRep mismatch')
approximatelyEqual(amounts.totalEthRefund, expectedRefund, tolerance, 'ethRefund mismatch')
} else {
strictEqualTypeSafe(amounts.totalFilledRep, expectedFilledRep, 'filledRep mismatch')
strictEqualTypeSafe(amounts.totalEthRefund, expectedRefund, 'ethRefund mismatch')
}
}
async function assertContractEmpty(client: WriteClient, auctionAddress: Address, tolerance: bigint = 1000n): Promise<void> {
approximatelyEqual(await getETHBalance(client, auctionAddress), 0n, tolerance, 'contract not empty')
}
async function setupStandardAuction(client: WriteClient, auctionAddress: Address, ethRaiseCapEth: bigint = DEFAULT_ETH_RAISE_CAP, maxRepBeingSold: bigint = DEFAULT_MAX_REP): Promise<void> {
await startAuction(client, auctionAddress, ethRaiseCapEth * ATTOETH_PER_ETH, maxRepBeingSold * ATTOETH_PER_ETH)
}
async function assertFairPayoutForUser(auctionCreator: WriteClient, auctionAddress: Address, userId: Address, bids: { tick: bigint; bidSize: bigint; bidIndex: bigint }[], clearingTick: bigint, tolerance: bigint = DEFAULT_TOLERANCE): Promise<{ totalFilledRep: bigint; totalEthRefund: bigint }> {
const clearingPrice = tickToPrice(clearingTick)
let totalFilledRep = 0n
let totalEthRefund = 0n
for (const bid of bids) {
const amounts = await simulateWithdrawBids(auctionCreator, auctionAddress, userId, [{ tick: bid.tick, bidIndex: bid.bidIndex }])
const bidPrice = tickToPrice(bid.tick)
let minRepBackOnFullBuy: bigint
if (bidPrice === 0n) {
// Zero price means no REP can be bought; expect 0 filled REP
minRepBackOnFullBuy = 0n
} else {
minRepBackOnFullBuy = (bid.bidSize * ATTOETH_PER_ETH) / bidPrice
}
if (bid.tick < clearingTick) {
// Losing bid: full refund, no REP
assert.strictEqual(amounts.totalFilledRep, 0n, `Bid ${bid.bidIndex} (losing): should get 0 REP`)
approximatelyEqual(amounts.totalEthRefund, bid.bidSize, tolerance, `Bid ${bid.bidIndex} (losing): full ETH refund`)
totalEthRefund += amounts.totalEthRefund
} else if (bid.tick === clearingTick) {
// At-clearing: partial fill, partial refund
if (amounts.totalEthRefund !== bid.bidSize) assert.ok(amounts.totalFilledRep > 0n, `Bid ${bid.bidIndex} (clearing): should get some REP`)
assert.ok(amounts.totalFilledRep <= minRepBackOnFullBuy, `Bid ${bid.bidIndex} (clearing): filled REP <= demand`)
const ethUsed = (amounts.totalFilledRep * clearingPrice) / ATTOETH_PER_ETH
approximatelyEqual(amounts.totalEthRefund, bid.bidSize - ethUsed, tolerance, `Bid ${bid.bidIndex} (clearing): correct ETH refund`)
totalFilledRep += amounts.totalFilledRep
totalEthRefund += amounts.totalEthRefund
} else {
// Winning bid: full REP demand, no ETH refund
assert.ok(amounts.totalFilledRep >= minRepBackOnFullBuy, `Bid ${bid.bidIndex} (winning): REP fill`)
assert.strictEqual(amounts.totalEthRefund, 0n, `Bid ${bid.bidIndex} (winning): no ETH refund`)
totalFilledRep += amounts.totalFilledRep
}
await withdrawBids(auctionCreator, auctionAddress, userId, [{ tick: bid.tick, bidIndex: bid.bidIndex }])
}
return { totalFilledRep, totalEthRefund }
}
function assertClearingTickInRange(tick: bigint): void {
assert.ok(tick >= MIN_TICK && tick <= MAX_TICK, `clearing tick ${tick} outside [${MIN_TICK}, ${MAX_TICK}]`)
}
const buildFenwickTreeEntries = (bidCount: bigint, refundedBidCount: bigint, bidAmount: bigint) => {
const entries = new Map<bigint, bigint>()
const addAtIndex = (oneBasedIndex: bigint, amount: bigint) => {
let treeIndex = oneBasedIndex
while (treeIndex <= bidCount) {
entries.set(treeIndex, (entries.get(treeIndex) ?? 0n) + amount)
treeIndex += treeIndex & -treeIndex
}
}
for (let refundedIndex = 1n; refundedIndex <= refundedBidCount; refundedIndex++) {
addAtIndex(refundedIndex, bidAmount)
}
return entries
}
const estimateWithdrawGasWithManyRefundedPredecessors = async (bidCount: bigint, clientIndex: number) => {
const ownerClient = createTestClient(clientIndex)
await deployUniformPriceDualCapBatchAuction(client, ownerClient.account.address)
const localAuctionAddress = getUniformPriceDualCapBatchAuctionAddress(ownerClient.account.address)
const sameTick = 0n
const bidAmount = 1n * ATTOETH_PER_ETH
await startAuction(ownerClient, localAuctionAddress, 10n * bidAmount, bidAmount)
for (let bidIndex = 0n; bidIndex < bidCount; bidIndex++) {
await submitBid(ownerClient, localAuctionAddress, sameTick, bidAmount)
}
const bidArraySlot = keccak256(encodeAbiParameters([{ type: 'int256' }, { type: 'uint256' }], [sameTick, AUCTION_BIDS_AT_TICK_SLOT]))
const bidDataStartSlot = BigInt(keccak256(encodeAbiParameters([{ type: 'bytes32' }], [bidArraySlot])))
const nodeBaseSlot = BigInt(keccak256(encodeAbiParameters([{ type: 'uint256' }, { type: 'uint256' }], [1n, AUCTION_NODES_SLOT])))
const refundedTreeOuterSlot = keccak256(encodeAbiParameters([{ type: 'int256' }, { type: 'uint256' }], [sameTick, AUCTION_REFUNDED_BID_PREFIX_TREE_SLOT]))
const stateDiff: Record<string, bigint> = {
[`0x${(nodeBaseSlot + 1n).toString(16)}`]: bidAmount,
[`0x${(nodeBaseSlot + 2n).toString(16)}`]: bidAmount,
}
for (let bidIndex = 0n; bidIndex < bidCount - 1n; bidIndex++) {
const claimedSlot = bidDataStartSlot + bidIndex * BID_STRUCT_SLOT_COUNT + 3n
const ethAmountSlot = bidDataStartSlot + bidIndex * BID_STRUCT_SLOT_COUNT + 1n
stateDiff[`0x${claimedSlot.toString(16)}`] = 1n
stateDiff[`0x${ethAmountSlot.toString(16)}`] = 0n
}
for (const [treeIndex, value] of buildFenwickTreeEntries(bidCount, bidCount - 1n, bidAmount)) {
const treeSlot = keccak256(encodeAbiParameters([{ type: 'uint256' }, { type: 'bytes32' }], [treeIndex, refundedTreeOuterSlot]))
stateDiff[treeSlot] = value
}
await mockWindow.addStateOverrides({
[localAuctionAddress]: {
stateDiff,
},
})
await finalizeAndVerify(ownerClient, localAuctionAddress)
return await ownerClient.estimateContractGas({
abi: peripherals_UniformPriceDualCapBatchAuction_UniformPriceDualCapBatchAuction.abi,
functionName: 'withdrawBids',
address: localAuctionAddress,
args: [ownerClient.account.address, [{ bidIndex: bidCount - 1n, tick: sameTick }]],
})
}
const estimateFinalizeGasWithBidDistribution = async (bidCount: bigint, distinctTicks: boolean, clientIndex: number) => {
const ownerClient = createTestClient(clientIndex)
await deployUniformPriceDualCapBatchAuction(client, ownerClient.account.address)
const localAuctionAddress = getUniformPriceDualCapBatchAuctionAddress(ownerClient.account.address)
const bidAmount = 1n * ATTOETH_PER_ETH
const totalBidAmount = bidCount * bidAmount
await startAuction(ownerClient, localAuctionAddress, totalBidAmount + bidAmount, totalBidAmount + bidAmount)
for (let bidIndex = 0n; bidIndex < bidCount; bidIndex++) {
const tick = distinctTicks ? bidIndex : 0n
await submitBid(ownerClient, localAuctionAddress, tick, bidAmount)
}
await mockWindow.advanceTime(AUCTION_TIME + 1n)
return await ownerClient.estimateContractGas({
abi: peripherals_UniformPriceDualCapBatchAuction_UniformPriceDualCapBatchAuction.abi,
functionName: 'finalize',
address: localAuctionAddress,
args: [],
})
}
const formatStorageSlot = (slot: bigint) => `0x${slot.toString(16)}`
const getMappingBaseSlot = (key: bigint, slot: bigint) => BigInt(keccak256(encodeAbiParameters([{ type: 'uint256' }, { type: 'uint256' }], [key, slot])))
const getMinAvlNodesForHeight = (height: bigint): bigint => {
if (height === 0n) return 0n
if (height === 1n) return 1n
let previousPrevious = 0n
let previous = 1n
for (let currentHeight = 2n; currentHeight <= height; currentHeight++) {
const current = 1n + previous + previousPrevious
previousPrevious = previous
previous = current
}
return previous
}
const getMaxAvlHeightWithinNodeCap = (nodeCap: bigint): bigint => {
let height = 0n
while (getMinAvlNodesForHeight(height + 1n) <= nodeCap) {
height++
}
return height
}
const buildSyntheticWorstCaseFinalizeStateDiff = (height: bigint, bidAmount: bigint, maxRepBeingSold: bigint = 1n, ethRaiseCap: bigint = height * bidAmount + bidAmount) => {
const stateDiff: Record<string, bigint> = {
[formatStorageSlot(AUCTION_ROOT_SLOT)]: 1n,
[formatStorageSlot(AUCTION_NEXT_ID_SLOT)]: height + 1n,
[formatStorageSlot(AUCTION_MAX_REP_BEING_SOLD_SLOT)]: maxRepBeingSold,
[formatStorageSlot(AUCTION_ETH_RAISE_CAP_SLOT)]: ethRaiseCap,
}
for (let nodeId = 1n; nodeId <= height; nodeId++) {
const remainingNodes = height - nodeId + 1n
const nodeBaseSlot = getMappingBaseSlot(nodeId, AUCTION_NODES_SLOT)
const tick = nodeId - 1n
const values = [tick, bidAmount, remainingNodes * bidAmount, 0n, nodeId === height ? 0n : nodeId + 1n, remainingNodes, remainingNodes * bidAmount, tick]
strictEqualTypeSafe(BigInt(values.length), NODE_STRUCT_SLOT_COUNT, 'synthetic node slot count mismatch')
for (let index = 0; index < values.length; index++) {
stateDiff[formatStorageSlot(nodeBaseSlot + BigInt(index))] = values[index] ?? 0n
}
}
return stateDiff
}
const estimateFinalizeGasForSyntheticWorstCaseDepth = async (height: bigint, clientIndex: number) => {
const ownerClient = createTestClient(clientIndex)
await deployUniformPriceDualCapBatchAuction(client, ownerClient.account.address)
const localAuctionAddress = getUniformPriceDualCapBatchAuctionAddress(ownerClient.account.address)
const bidAmount = 1n * ATTOETH_PER_ETH
await startAuction(ownerClient, localAuctionAddress, height * bidAmount + bidAmount, 1n)
await mockWindow.advanceTime(AUCTION_TIME + 1n)
await mockWindow.addStateOverrides({
[localAuctionAddress]: {
balance: height * bidAmount,
stateDiff: buildSyntheticWorstCaseFinalizeStateDiff(height, bidAmount),
},
})
return await ownerClient.estimateContractGas({
abi: peripherals_UniformPriceDualCapBatchAuction_UniformPriceDualCapBatchAuction.abi,
functionName: 'finalize',
address: localAuctionAddress,
args: [],
})
}
const estimateUnderfundedFinalizeGasForSyntheticWorstCaseDepth = async (height: bigint, clientIndex: number) => {
const ownerClient = createTestClient(clientIndex)
await deployUniformPriceDualCapBatchAuction(client, ownerClient.account.address)
const localAuctionAddress = getUniformPriceDualCapBatchAuctionAddress(ownerClient.account.address)
const bidAmount = 1n * ATTOETH_PER_ETH
const totalEth = height * bidAmount
const maxRepBeingSold = totalEth + 1n
const ethRaiseCap = totalEth + bidAmount
await startAuction(ownerClient, localAuctionAddress, ethRaiseCap, maxRepBeingSold)
await mockWindow.advanceTime(AUCTION_TIME + 1n)
await mockWindow.addStateOverrides({
[localAuctionAddress]: {
balance: totalEth,
stateDiff: buildSyntheticWorstCaseFinalizeStateDiff(height, bidAmount, maxRepBeingSold, ethRaiseCap),
},
})
return await ownerClient.estimateContractGas({
abi: peripherals_UniformPriceDualCapBatchAuction_UniformPriceDualCapBatchAuction.abi,
functionName: 'finalize',
address: localAuctionAddress,
args: [],
})
}
beforeAll(async () => {
mockWindow = getAnvilWindowEthereum()
await setupTestAccounts(mockWindow)
client = createWriteClient(mockWindow, TEST_ADDRESSES[0], 0)
await ensureZoltarDeployed(client)
await ensureInfraDeployed(client)
await deployUniformPriceDualCapBatchAuction(client, client.account.address)
auctionAddress = getUniformPriceDualCapBatchAuctionAddress(client.account.address)
assert.ok(await contractExists(client, auctionAddress), 'auction exists')
await setBaselineSnapshot()
})
beforeEach(() => {
mockWindow = getAnvilWindowEthereum()
client = createWriteClient(mockWindow, TEST_ADDRESSES[0], 0)
})
// ============ Test Suites ============
describe('Lifecycle & Finalization', () => {
test('finalize rejects before the auction starts or ends', async () => {
await assert.rejects(async () => await finalize(client, auctionAddress), /not started/)
const raiseCap = DEFAULT_ETH_RAISE_CAP * ATTOETH_PER_ETH
await setupStandardAuction(client, auctionAddress)
await submitBid(client, auctionAddress, tickForPrice(PRICE_PRECISION), raiseCap)
await assert.rejects(async () => await finalize(client, auctionAddress), /auction active/)
})
test('can start auction and make a single bid that finalizes', async () => {
const raiseCap = DEFAULT_ETH_RAISE_CAP * ATTOETH_PER_ETH
await setupStandardAuction(client, auctionAddress)
const tick = tickForPrice(PRICE_PRECISION)
const bidSize = raiseCap
const startBalance = await submitBidAndVerifyLock(client, auctionAddress, tick, bidSize)
strictEqual18Decimal(await getEthRaiseCap(client, auctionAddress), bidSize, 'we bid the same as cap')
const clearing = await computeClearing(client, auctionAddress)
assertExpectedClearing(clearing, tick)
await finalizeAndVerify(client, auctionAddress)
const bids = [{ tick, bidSize, bidIndex: 0n }]
await assertFairPayoutForUser(client, auctionAddress, client.account.address, bids, clearing.foundTick)
const finalBalance = await getETHBalance(client, client.account.address)
strictEqualTypeSafe(startBalance, finalBalance, 'did not get eth back')
})
test('multiple bids', async () => {
const maxRepBeingSold = DEFAULT_MAX_REP * ATTOETH_PER_ETH
const startBalance = await getETHBalance(client, client.account.address)
await setupStandardAuction(client, auctionAddress)
const bids = [
{ bidSize: maxRepBeingSold / 5n, priceRepEth: PRICE_PRECISION / 4n },
{ bidSize: maxRepBeingSold / 5n, priceRepEth: PRICE_PRECISION / 2n },
{ bidSize: maxRepBeingSold / 5n, priceRepEth: PRICE_PRECISION },
{ bidSize: maxRepBeingSold / 5n, priceRepEth: PRICE_PRECISION * 2n },
{ bidSize: maxRepBeingSold / 5n, priceRepEth: PRICE_PRECISION * 3n },
{ bidSize: maxRepBeingSold / 5n, priceRepEth: PRICE_PRECISION * 4n },
]
for (const bid of bids) {
const tick = tickForPrice(bid.priceRepEth)
await submitBidAndVerifyLock(client, auctionAddress, tick, bid.bidSize)
}
const clearing = await computeClearing(client, auctionAddress)
assertClearing(clearing, true)
assertClearingTickInRange(clearing.foundTick)
await finalizeAndVerify(client, auctionAddress)
const fairPayoutBids = bids.map(bid => ({ tick: tickForPrice(bid.priceRepEth), bidSize: bid.bidSize, bidIndex: 0n }))
await assertFairPayoutForUser(client, auctionAddress, client.account.address, fairPayoutBids, clearing.foundTick)
await assertContractEmpty(client, auctionAddress)
const finalBalance = await getETHBalance(client, client.account.address)
strictEqualTypeSafe(startBalance, finalBalance, 'did not get eth back')
})
test('multiple users bids', async () => {
const maxRepBeingSold = DEFAULT_MAX_REP * ATTOETH_PER_ETH
await setupStandardAuction(client, auctionAddress)
const bids = [
{ bidSize: (2n * maxRepBeingSold) / 7n, tick: priceToClosestTick(PRICE_PRECISION / 4n), address: TEST_ADDRESSES[0], bidIndex: 0n },
{ bidSize: (2n * maxRepBeingSold) / 7n, tick: priceToClosestTick(PRICE_PRECISION / 4n), address: TEST_ADDRESSES[1], bidIndex: 1n },
{ bidSize: (2n * maxRepBeingSold) / 7n, tick: priceToClosestTick(PRICE_PRECISION), address: TEST_ADDRESSES[2], bidIndex: 0n },
{ bidSize: (2n * maxRepBeingSold) / 7n, tick: priceToClosestTick(PRICE_PRECISION), address: TEST_ADDRESSES[3], bidIndex: 1n },
{ bidSize: (2n * maxRepBeingSold) / 7n, tick: priceToClosestTick(PRICE_PRECISION * 4n), address: TEST_ADDRESSES[4], bidIndex: 0n },
{ bidSize: (2n * maxRepBeingSold) / 7n, tick: priceToClosestTick(PRICE_PRECISION * 4n), address: TEST_ADDRESSES[5], bidIndex: 1n },
]
for (const bid of bids) {
const bidClient = createWriteClient(mockWindow, bid.address, 0)
await submitBid(bidClient, auctionAddress, bid.tick, bid.bidSize)
}
//const expectedClearing = computeClearingTypeScript(bids, maxRepBeingSold, DEFAULT_MAX_REP * ATTOETH_PER_ETH )
const clearing = await computeClearing(client, auctionAddress)
const completelyFilling = bids.filter(x => x.tick > clearing.foundTick)
const completelyFillingRep = completelyFilling.reduce((a, b) => a + (b.bidSize * PRICE_PRECISION) / tickToPrice(clearing.foundTick), 0n)
assert.ok(completelyFillingRep < maxRepBeingSold, 'selling too much rep with that tick')
//assertExpectedClearing(clearing, expectedClearing.clearingTick)
await finalizeAndVerify(client, auctionAddress)
const bidsByUser = new Map<bigint, typeof bids>()
for (const bid of bids) {
const addr = bid.address
if (!bidsByUser.has(addr)) bidsByUser.set(addr, [])
const bidsForAddr = ensureDefined(bidsByUser.get(addr), `No bids array for address ${addr}`)
bidsForAddr.push(bid)
}
let grandTotalFilled = 0n
for (const [userAddress, userBids] of bidsByUser) {
const fairPayoutBids = userBids.map(b => ({ tick: b.tick, bidSize: b.bidSize, bidIndex: b.bidIndex }))
const result = await assertFairPayoutForUser(client, auctionAddress, addressString(userAddress), fairPayoutBids, clearing.foundTick)
grandTotalFilled += result.totalFilledRep
}
// Total filled REP across all users should not exceed the amount sold
assert.ok(grandTotalFilled <= maxRepBeingSold, 'total filled REP exceeds maxRepBeingSold')
})
test('computeClearing selects the lower price tick when only lower-price cumulative demand exhausts supply', async () => {
await setupStandardAuction(client, auctionAddress, 1_000n, 100n)
const expensiveTick = tickForPrice(4n * PRICE_PRECISION)
const cheapTick = tickForPrice(PRICE_PRECISION)
const bidAmount = 100n * ATTOETH_PER_ETH
await submitBid(client, auctionAddress, expensiveTick, bidAmount)
await submitBid(client, auctionAddress, cheapTick, bidAmount)
const clearing = await computeClearing(client, auctionAddress)
assertExpectedClearing(clearing, cheapTick, bidAmount)
})
test('winning bids receive their requested REP and clearing-tick bids refund excess ETH', async () => {
await setupStandardAuction(client, auctionAddress)
const alice = createTestClient(0)
const bob = createTestClient(1)
const aliceTick = tickForPrice(PRICE_PRECISION * 2n)
const aliceEth = 190n * 10n ** 18n
const bobTick = tickForPrice(PRICE_PRECISION * 4n)
const bobEth = 20n * 10n ** 18n
await submitBidAndVerifyLock(alice, auctionAddress, aliceTick, aliceEth)
await submitBidAndVerifyLock(bob, auctionAddress, bobTick, bobEth)
const clearingPre = await computeClearing(client, auctionAddress)
strictEqualTypeSafe(clearingPre.hitCap, true, 'auction should have price')
await finalizeAndVerify(client, auctionAddress)
const clearingTick = await getClearingTick(client, auctionAddress)
strictEqualTypeSafe(clearingTick, aliceTick, 'clearing tick should be alice tick')
const aliceBids = [{ tick: aliceTick, bidSize: aliceEth, bidIndex: 0n }]
const bobBids = [{ tick: bobTick, bidSize: bobEth, bidIndex: 0n }]
const aliceResult = await assertFairPayoutForUser(client, auctionAddress, alice.account.address, aliceBids, clearingTick)
const bobResult = await assertFairPayoutForUser(client, auctionAddress, bob.account.address, bobBids, clearingTick)
const totalFilled = aliceResult.totalFilledRep + bobResult.totalFilledRep
const maxRep = DEFAULT_MAX_REP * ATTOETH_PER_ETH
assert.ok(totalFilled <= maxRep, 'total filled exceeds maxRep')
})
test('multiple bids at same tick from same bidder (FIFO pro-rata)', async () => {
const ethRaiseCap = 100n * 10n ** 18n
const maxRepBeingSold = 10n * 10n ** 18n
const alice = createTestClient(0)
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const sameTick = 0n
const bid1Amount = 7n * 10n ** 18n
const bid2Amount = 7n * 10n ** 18n
await submitBidAndVerifyLock(alice, auctionAddress, sameTick, bid1Amount)
await submitBidAndVerifyLock(alice, auctionAddress, sameTick, bid2Amount)
const raisecap = await getEthRaiseCap(client, auctionAddress)
strictEqual18Decimal(raisecap, ethRaiseCap, 'raisecap for eth is same')
await finalizeAndVerify(client, auctionAddress)
const aliceBids = [
{ tick: sameTick, bidSize: bid1Amount, bidIndex: 0n },
{ tick: sameTick, bidSize: bid2Amount, bidIndex: 1n },
]
await assertFairPayoutForUser(client, auctionAddress, alice.account.address, aliceBids, 0n, 10n)
})
test('combined refundLosingBids and withdrawBids for same user with mixed winning/losing bids', async () => {
const ethRaiseCap = 200_000n * 10n ** 18n
const maxRepBeingSold = 50n * 10n ** 18n
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const alice = createTestClient(0)
const losingTick = -20000n
const clearingTickBid = 0n
const winningTick = 10000n
const losingEth = 2n * 10n ** 18n
const mediumEth = 40n * 10n ** 18n
const highEth = 150n * 10n ** 18n
await submitBid(alice, auctionAddress, losingTick, losingEth)
await submitBid(alice, auctionAddress, clearingTickBid, mediumEth)
await submitBid(alice, auctionAddress, winningTick, highEth)
const clearingPre = await computeClearing(client, auctionAddress)
assert.ok(clearingPre.hitCap, 'price not found')
const clearingTick = clearingPre.foundTick
assert.strictEqual(clearingTick, winningTick, 'clearing tick expected to be winningTick')
assert.ok(losingTick < clearingTick, 'losing tick should be below clearing')
assert.ok(winningTick >= clearingTick, 'winning tick should be equal clearing')
await refundLosingBids(alice, auctionAddress, [{ tick: losingTick, bidIndex: 0n }])
// Compute expected ethRaised after refund (matches what finalize will use)
const clearingAfterRefund = await computeClearing(client, auctionAddress)
const expectedEthRaised = clearingAfterRefund.accumulatedEth
await mockWindow.advanceTime(AUCTION_TIME + 1n)
await finalize(client, auctionAddress)
strictEqualTypeSafe(await getEthRaised(client, auctionAddress), expectedEthRaised, 'raised amount mismatch')
strictEqualTypeSafe(await isFinalized(client, auctionAddress), true, 'Did not finalize')
const clearingPost = await computeClearing(client, auctionAddress)
strictEqualTypeSafe(clearingPost.foundTick, clearingTick, 'clearing tick changed after refund')
strictEqualTypeSafe(clearingPost.hitCap, true, 'price found after refund')
const remainingBids = [
{ tick: clearingTickBid, bidSize: mediumEth, bidIndex: 0n },
{ tick: winningTick, bidSize: highEth, bidIndex: 0n },
]
await assertFairPayoutForUser(client, auctionAddress, alice.account.address, remainingBids, clearingTick)
await assertContractEmpty(client, auctionAddress)
})
test('partial fill calculations ignore cleared earlier bids at the same tick', async () => {
const raiseCap = 1_000n * ATTOETH_PER_ETH
const maxRepBeingSold = 100n * ATTOETH_PER_ETH
const sameTick = 0n
const bidAmount = 60n * ATTOETH_PER_ETH
await startAuction(client, auctionAddress, raiseCap, maxRepBeingSold)
const alice = createTestClient(0)
await submitBid(alice, auctionAddress, sameTick, bidAmount)
await submitBid(alice, auctionAddress, sameTick, bidAmount)
await submitBid(alice, auctionAddress, sameTick, bidAmount)
const nodeBaseSlot = keccak256(encodeAbiParameters([{ type: 'uint256' }, { type: 'uint256' }], [1n, AUCTION_NODES_SLOT]))
const bidArraySlot = keccak256(encodeAbiParameters([{ type: 'int256' }, { type: 'uint256' }], [sameTick, AUCTION_BIDS_AT_TICK_SLOT]))
const bidDataSlot = keccak256(encodeAbiParameters([{ type: 'bytes32' }], [bidArraySlot]))
const refundedTreeOuterSlot = keccak256(encodeAbiParameters([{ type: 'int256' }, { type: 'uint256' }], [sameTick, AUCTION_REFUNDED_BID_PREFIX_TREE_SLOT]))
const firstBidEthAmountSlot = `0x${(BigInt(bidDataSlot) + 1n).toString(16)}`
const nodeTotalEthSlot = `0x${(BigInt(nodeBaseSlot) + 1n).toString(16)}`
const nodeSubtreeEthSlot = `0x${(BigInt(nodeBaseSlot) + 2n).toString(16)}`
const activeTotalEth = 2n * bidAmount
const refundedTreeStateDiff: Record<string, bigint> = {}
for (const [treeIndex, value] of buildFenwickTreeEntries(3n, 1n, bidAmount)) {
const treeSlot = keccak256(encodeAbiParameters([{ type: 'uint256' }, { type: 'bytes32' }], [treeIndex, refundedTreeOuterSlot]))
refundedTreeStateDiff[treeSlot] = value
}
await mockWindow.addStateOverrides({
[auctionAddress]: {
stateDiff: {
[firstBidEthAmountSlot]: 0n,
[nodeTotalEthSlot]: activeTotalEth,
[nodeSubtreeEthSlot]: activeTotalEth,
...refundedTreeStateDiff,
},
},
})
await finalizeAndVerify(client, auctionAddress)
const secondBidWithdrawal = await simulateWithdrawBids(client, auctionAddress, alice.account.address, [{ tick: sameTick, bidIndex: 1n }])
const expectedSecondBidRep = bidAmount
strictEqualTypeSafe(secondBidWithdrawal.totalFilledRep, expectedSecondBidRep, 'the second active bid should receive its full fill after an earlier bid is cleared from the tick')
strictEqualTypeSafe(secondBidWithdrawal.totalEthRefund, 0n, 'the fully filled second active bid should not receive an ETH refund')
})
test('withdraw gas for a same-tick bid with many refunded predecessors avoids linear growth', async () => {
const gasWithSixteenBids = await estimateWithdrawGasWithManyRefundedPredecessors(16n, 1)
const gasWithOneHundredTwentyEightBids = await estimateWithdrawGasWithManyRefundedPredecessors(128n, 2)
assert.ok(gasWithOneHundredTwentyEightBids < gasWithSixteenBids * 4n, `withdraw gas should stay sublinear in the number of refunded same-tick predecessors: 16 bids=${gasWithSixteenBids.toString()}, 128 bids=${gasWithOneHundredTwentyEightBids.toString()}`)
})
test('finalize gas stays bounded when many bids land on the same tick', async () => {
const gasWithSixteenBids = await estimateFinalizeGasWithBidDistribution(16n, false, 3)
const gasWithOneHundredTwentyEightBids = await estimateFinalizeGasWithBidDistribution(128n, false, 4)
assert.ok(gasWithOneHundredTwentyEightBids < gasWithSixteenBids * 2n, `finalize gas should track price levels rather than raw bid count when bids share a tick: 16 bids=${gasWithSixteenBids.toString()}, 128 bids=${gasWithOneHundredTwentyEightBids.toString()}`)
})
test('distinct-tick finalize gas stays close to same-tick finalize gas after subtree pruning', async () => {
const gasWithThirtyTwoSameTickBids = await estimateFinalizeGasWithBidDistribution(32n, false, 5)
const gasWithThirtyTwoDistinctTicks = await estimateFinalizeGasWithBidDistribution(32n, true, 6)
assert.ok(gasWithThirtyTwoDistinctTicks < gasWithThirtyTwoSameTickBids * 2n, `distinct price levels should stay close to same-tick finalize gas after subtree pruning: same tick=${gasWithThirtyTwoSameTickBids.toString()}, distinct ticks=${gasWithThirtyTwoDistinctTicks.toString()}`)
})
test('finalize stays under 20 million gas on a synthetic max-depth clearing path for the full tick domain', async () => {
const maxAvlHeightWithinTickDomain = getMaxAvlHeightWithinNodeCap(MAX_DISTINCT_TICK_COUNT)
strictEqualTypeSafe(maxAvlHeightWithinTickDomain, 28n, 'unexpected AVL height bound for the tick domain')
const finalizeGas = await estimateFinalizeGasForSyntheticWorstCaseDepth(maxAvlHeightWithinTickDomain, 1)
console.info(`auction max-depth funded finalize gas: ${finalizeGas.toString()} (height=${maxAvlHeightWithinTickDomain.toString()}, limit=${FINALIZE_GAS_LIMIT.toString()})`)
assert.ok(finalizeGas < FINALIZE_GAS_LIMIT, `finalize gas should stay below ${FINALIZE_GAS_LIMIT.toString()} for the synthetic max-depth clearing path: gas=${finalizeGas.toString()}, height=${maxAvlHeightWithinTickDomain.toString()}`)
})
test('underfunded finalize stays under 20 million gas on a synthetic max-depth tick domain', async () => {
const maxAvlHeightWithinTickDomain = getMaxAvlHeightWithinNodeCap(MAX_DISTINCT_TICK_COUNT)
strictEqualTypeSafe(maxAvlHeightWithinTickDomain, 28n, 'unexpected AVL height bound for the tick domain')
const finalizeGas = await estimateUnderfundedFinalizeGasForSyntheticWorstCaseDepth(maxAvlHeightWithinTickDomain, 1)
console.info(`auction max-depth underfunded finalize gas: ${finalizeGas.toString()} (height=${maxAvlHeightWithinTickDomain.toString()}, limit=${FINALIZE_GAS_LIMIT.toString()})`)
assert.ok(finalizeGas < FINALIZE_GAS_LIMIT, `underfunded finalize gas should stay below ${FINALIZE_GAS_LIMIT.toString()} for the synthetic max-depth tree: gas=${finalizeGas.toString()}, height=${maxAvlHeightWithinTickDomain.toString()}`)
})
test('winner unaffected after bidder refunds multiple losing bids', async () => {
await setupStandardAuction(client, auctionAddress)
const alice = createTestClient(0)
const bob = createTestClient(1)
const lowTicks = [tickForPrice(PRICE_PRECISION / 4n), tickForPrice(PRICE_PRECISION / 3n), tickForPrice(PRICE_PRECISION / 2n)]
const minBidSize = await getMinBidSize(client, auctionAddress)
const lowBid = minBidSize
for (const t of lowTicks) {
await submitBid(alice, auctionAddress, t, lowBid)
}
const bobTick = 0n
const bobEth = 120n * 10n ** 18n
await submitBidAndVerifyLock(bob, auctionAddress, bobTick, bobEth)
const clearingPre = await computeClearing(client, auctionAddress)
assert.ok(clearingPre.hitCap, 'price found')
strictEqualTypeSafe(clearingPre.foundTick, bobTick, 'clearing tick is bobTick')
const aliceBalanceBefore = await getETHBalance(client, alice.account.address)
const refundIndices = lowTicks.map(t => ({ tick: t, bidIndex: 0n }))
await refundLosingBids(alice, auctionAddress, refundIndices)
const aliceBalanceAfter = await getETHBalance(client, alice.account.address)
strictEqualTypeSafe(aliceBalanceAfter - aliceBalanceBefore, 3n * lowBid, 'Alice total refund')
await finalizeAndVerify(client, auctionAddress)
const bobBids = [{ tick: bobTick, bidSize: bobEth, bidIndex: 0n }]
await assertFairPayoutForUser(client, auctionAddress, bob.account.address, bobBids, bobTick, 10n)
})
test('should correctly handle underfunded auctions', async () => {
const ethRaiseCap = 100n * 10n ** 18n
const maxRepBeingSold = 100n * 10n ** 18n
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const price = PRICE_PRECISION
const alice = createTestClient(0)
await submitBid(alice, auctionAddress, tickForPrice(price), 1n * 10n ** 18n)
await mockWindow.advanceTime(AUCTION_TIME + 1n)
await finalize(client, auctionAddress)
const clearing = await computeClearing(client, auctionAddress)
strictEqualTypeSafe(clearing.hitCap, false, 'auction should not have price')
})
test('underfunded auction distributes all REP proportionally', async () => {
const ethRaiseCap = 1000n * 10n ** 18n // large enough to not bind
const maxRepBeingSold = 100n * 10n ** 18n // 100 REP
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const alice = createTestClient(0)
const bob = createTestClient(1)
const aliceEth = 4n * 10n ** 18n
const bobEth = 6n * 10n ** 18n
// Use prices that make the auction underfunded (hitCap false)
const aliceTick = tickForPrice(2n * 10n ** 18n) // 2 ETH/REP
const bobTick = tickForPrice(4n * 10n ** 18n) // 4 ETH/REP
await submitBid(alice, auctionAddress, aliceTick, aliceEth)
await submitBid(bob, auctionAddress, bobTick, bobEth)
// Check clearing result before finalize to verify underfunded condition
const clearingPre = await computeClearing(client, auctionAddress)
strictEqualTypeSafe(clearingPre.hitCap, false, 'hitCap should be false (underfunded)')
// Finalize the auction
await mockWindow.advanceTime(AUCTION_TIME + 1n)
await finalize(client, auctionAddress)
// Verify total REP purchased equals maxRepBeingSold (all rep sold)
const totalRep = await getTotalRepPurchased(client, auctionAddress)
strictEqualTypeSafe(totalRep, maxRepBeingSold, 'totalRepPurchased should equal maxRep')
// Alice withdraws her proportional share
const aliceBids = [{ tick: aliceTick, bidIndex: 0n }]
const aliceResult = await simulateWithdrawBids(client, auctionAddress, alice.account.address, aliceBids)
const expectedAliceRep = (aliceEth * maxRepBeingSold) / (aliceEth + bobEth) // 4/10 * 100 = 40
strictEqualTypeSafe(aliceResult.totalFilledRep, expectedAliceRep, 'alice proportional REP')
strictEqualTypeSafe(aliceResult.totalEthRefund, 0n, 'alice no ETH refund')
// Bob withdraws his proportional share
const bobBids = [{ tick: bobTick, bidIndex: 0n }]
const bobResult = await simulateWithdrawBids(client, auctionAddress, bob.account.address, bobBids)
const expectedBobRep = (bobEth * maxRepBeingSold) / (aliceEth + bobEth) // 6/10 * 100 = 60
strictEqualTypeSafe(bobResult.totalFilledRep, expectedBobRep, 'bob proportional REP')
strictEqualTypeSafe(bobResult.totalEthRefund, 0n, 'bob no ETH refund')
// Contract should have no ETH balance after finalization
await assertContractEmpty(client, auctionAddress)
})
test('underfunded auctions treat bids exactly at the threshold price as winners', async () => {
const ethRaiseCap = 1_000n * 10n ** 18n
const maxRepBeingSold = 100n * 10n ** 18n
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const alice = createTestClient(0)
const thresholdPrice = PRICE_PRECISION / 2n
const thresholdTick = tickForPrice(thresholdPrice)
const aliceEth = (maxRepBeingSold * tickToPrice(thresholdTick)) / PRICE_PRECISION
await submitBid(alice, auctionAddress, thresholdTick, aliceEth)
await mockWindow.advanceTime(AUCTION_TIME + 1n)
await finalize(client, auctionAddress)
const totalRep = await getTotalRepPurchased(client, auctionAddress)
strictEqualTypeSafe(totalRep, maxRepBeingSold, 'all REP should clear when demand sits exactly at the underfunded threshold')
const withdrawal = await simulateWithdrawBids(client, auctionAddress, alice.account.address, [{ tick: thresholdTick, bidIndex: 0n }])
strictEqualTypeSafe(withdrawal.totalEthRefund, 0n, 'threshold-clearing winner should not receive an ETH refund')
approximatelyEqual(withdrawal.totalFilledRep, maxRepBeingSold, DEFAULT_TOLERANCE, 'threshold-clearing winner should receive the full REP allocation')
})
test('auction time limit prevents bids after expiration', async () => {
const ethRaiseCap = 100n * 10n ** 18n
const maxRepBeingSold = 10n * 10n ** 18n
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
await mockWindow.advanceTime(AUCTION_TIME + 1n)
const tick = tickForPrice(PRICE_PRECISION)
const bidAmount = 1n * 10n ** 18n
await assert.rejects(async () => await submitBid(client, auctionAddress, tick, bidAmount), /auction ended/)
})
})
describe('Bid Submission', () => {
test('minimum bid size enforcement', async () => {
const ethRaiseCap = 50000n
const maxRepBeingSold = 1n * 10n ** 18n
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const minBid = await getMinBidSize(client, auctionAddress)
strictEqualTypeSafe(minBid, 1n, 'minBidSize should be 1')
await assert.rejects(async () => await submitBid(client, auctionAddress, 0n, 0n), /bid too small/)
await submitBid(client, auctionAddress, 0n, 1n)
})
test('submitBid accepts both finite tick-domain edges', async () => {
const ethRaiseCap = 100n * 10n ** 18n
const maxRepBeingSold = 10n * 10n ** 18n
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
await submitBid(client, auctionAddress, MIN_TICK, 1n * 10n ** 18n)
await submitBid(client, auctionAddress, MAX_TICK, 1n * 10n ** 18n)
strictEqualTypeSafe(await getBidCountAtTick(client, auctionAddress, MIN_TICK), 1n, 'minimum tick bid count')
strictEqualTypeSafe(await getBidCountAtTick(client, auctionAddress, MAX_TICK), 1n, 'maximum tick bid count')
})
test('submitBid invalid states: before auction start and after finalize', async () => {
const ethRaiseCap = 100n * 10n ** 18n
const maxRepBeingSold = 10n * 10n ** 18n
const tick = tickForPrice(PRICE_PRECISION)
const bidAmount = 1n * 10n ** 18n
const freshAddress = getUniformPriceDualCapBatchAuctionAddress(addressString(TEST_ADDRESSES[3]))
await deployUniformPriceDualCapBatchAuction(client, addressString(TEST_ADDRESSES[3]))
await assert.rejects(async () => await submitBid(client, freshAddress, tick, bidAmount), /not started/)
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
await submitBid(client, auctionAddress, tick, ethRaiseCap)
await mockWindow.advanceTime(AUCTION_TIME + 1n)
await finalize(client, auctionAddress)
strictEqualTypeSafe(await isFinalized(client, auctionAddress), true, 'auction should be finalized before post-finalization assertions')
await assert.rejects(async () => await submitBid(client, auctionAddress, tick, bidAmount), /finalized/)
})
test('withdrawBids reverts before finalize', async () => {
const ethRaiseCap = 100n * 10n ** 18n
const maxRepBeingSold = 10n * 10n ** 18n
const tick = tickForPrice(PRICE_PRECISION)
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
await submitBid(client, auctionAddress, tick, 1n * 10n ** 18n)
await assert.rejects(async () => await withdrawBids(client, auctionAddress, client.account.address, [{ tick, bidIndex: 0n }]), /not finalized/)
})
})
describe('Enumeration Views', () => {
test('getTickPage returns one historical tick per unique tick and tracks same-tick submission counts', async () => {
const ethRaiseCap = 1_000n * ATTOETH_PER_ETH
const maxRepBeingSold = 1_000n * ATTOETH_PER_ETH
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const firstTick = 0n
const secondTick = 10_000n
const firstTickBidOne = 2n * ATTOETH_PER_ETH
const firstTickBidTwo = 3n * ATTOETH_PER_ETH
const secondTickBid = 5n * ATTOETH_PER_ETH
await submitBid(client, auctionAddress, firstTick, firstTickBidOne)
await submitBid(client, auctionAddress, firstTick, firstTickBidTwo)
await submitBid(client, auctionAddress, secondTick, secondTickBid)
strictEqualTypeSafe(await getTickCount(client, auctionAddress), 2n, 'unique tick count mismatch')
const tickPage = await getTickPage(client, auctionAddress, 0n, 100n)
assert.strictEqual(tickPage.length, 2, 'tick page length mismatch')
const firstSummary = ensureDefined(tickPage[0], 'missing first tick summary')
strictEqualTypeSafe(firstSummary.tick, firstTick, 'first historical tick mismatch')
strictEqualTypeSafe(firstSummary.submissionCount, 2n, 'same-tick submission count mismatch')
strictEqualTypeSafe(firstSummary.currentTotalEth, firstTickBidOne + firstTickBidTwo, 'same-tick active ETH mismatch')
strictEqualTypeSafe(firstSummary.active, true, 'same-tick should stay active')
const secondSummary = ensureDefined(tickPage[1], 'missing second tick summary')
strictEqualTypeSafe(secondSummary.tick, secondTick, 'second historical tick mismatch')
strictEqualTypeSafe(secondSummary.submissionCount, 1n, 'second tick submission count mismatch')
strictEqualTypeSafe(secondSummary.currentTotalEth, secondTickBid, 'second tick active ETH mismatch')
strictEqualTypeSafe(secondSummary.active, true, 'second tick should stay active')
})
test('a fully refunded tick remains enumerable with zero active ETH', async () => {
const ethRaiseCap = 20n * ATTOETH_PER_ETH
const maxRepBeingSold = 10n * ATTOETH_PER_ETH
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const losingTick = -20_000n
const winningTick = 0n
const losingBid = 2n * ATTOETH_PER_ETH
const winningBid = 12n * ATTOETH_PER_ETH
await submitBid(client, auctionAddress, losingTick, losingBid)
await submitBid(client, auctionAddress, winningTick, winningBid)
await refundLosingBids(client, auctionAddress, [{ tick: losingTick, bidIndex: 0n }])
const tickPage = await getTickPage(client, auctionAddress, 0n, 100n)
const refundedSummary = tickPage.find(summary => summary.tick === losingTick)
const activeSummary = tickPage.find(summary => summary.tick === winningTick)
strictEqualTypeSafe(refundedSummary?.currentTotalEth, 0n, 'refunded-away tick should have zero active ETH')
strictEqualTypeSafe(refundedSummary?.submissionCount, 1n, 'refunded-away tick should keep historical submission count')
strictEqualTypeSafe(refundedSummary?.active, false, 'refunded-away tick should be inactive')
strictEqualTypeSafe(activeSummary?.active, true, 'winning tick should remain active')
})
test('active tick pages stay sorted by descending tick and exclude refunded-away historical levels', async () => {
const ethRaiseCap = 20n * ATTOETH_PER_ETH
const maxRepBeingSold = 10n * ATTOETH_PER_ETH
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const lowTick = -20_000n
const middleTick = 0n
const highTick = 20_000n
await submitBid(client, auctionAddress, lowTick, 2n * ATTOETH_PER_ETH)
await submitBid(client, auctionAddress, middleTick, 4n * ATTOETH_PER_ETH)
await submitBid(client, auctionAddress, highTick, 6n * ATTOETH_PER_ETH)
await refundLosingBids(client, auctionAddress, [{ tick: lowTick, bidIndex: 0n }])
strictEqualTypeSafe(await activeTickCount(client, auctionAddress), 2n, 'active tick count mismatch after refund')
assert.deepStrictEqual(
(await getActiveTickPage(client, auctionAddress, 0n, 100n)).map(summary => summary.tick),
[highTick, middleTick],
)
})
test('getTickSummary returns historical summaries even after a tick is fully refunded away', async () => {
const ethRaiseCap = 20n * ATTOETH_PER_ETH
const maxRepBeingSold = 10n * ATTOETH_PER_ETH
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const losingTick = -20_000n
const winningTick = 0n
await submitBid(client, auctionAddress, losingTick, 2n * ATTOETH_PER_ETH)
await submitBid(client, auctionAddress, winningTick, 12n * ATTOETH_PER_ETH)
await refundLosingBids(client, auctionAddress, [{ tick: losingTick, bidIndex: 0n }])
const summary = await getTickSummary(client, auctionAddress, losingTick)
strictEqualTypeSafe(summary.tick, losingTick, 'historical tick mismatch')
strictEqualTypeSafe(summary.currentTotalEth, 0n, 'historical tick should have zero active ETH')
strictEqualTypeSafe(summary.submissionCount, 1n, 'historical tick should retain submission count')
strictEqualTypeSafe(summary.active, false, 'historical tick should be inactive')
})
test('getBidPageAtTick returns bid indices, cumulative ETH, and refund state while preserving refunded bid amounts', async () => {
const ethRaiseCap = 20n * ATTOETH_PER_ETH
const maxRepBeingSold = 10n * ATTOETH_PER_ETH
await startAuction(client, auctionAddress, ethRaiseCap, maxRepBeingSold)
const losingTick = -20_000n
const winningTick = 0n
const firstLosingBid = 2n * ATTOETH_PER_ETH
const secondLosingBid = 3n * ATTOETH_PER_ETH