-
Notifications
You must be signed in to change notification settings - Fork 2
/
AlgebraPool.spec.ts
3186 lines (2823 loc) · 131 KB
/
AlgebraPool.spec.ts
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 { ethers } from 'hardhat';
import { ContractTransactionReceipt, Wallet, MaxUint256, ZeroAddress } from 'ethers';
import { loadFixture } from '@nomicfoundation/hardhat-network-helpers';
import { expect } from './shared/expect';
import { poolFixture } from './shared/fixtures';
import {
expandTo18Decimals,
FeeAmount,
getPositionKey,
getMaxTick,
getMinTick,
encodePriceSqrt,
encodeCallback,
createPoolFunctions,
SwapFunction,
MintFunction,
FlashFunction,
MaxUint128,
MAX_SQRT_RATIO,
MIN_SQRT_RATIO,
SwapToPriceFunction,
MAX_TICK,
MIN_TICK,
} from './shared/utilities';
import {
TestERC20,
AlgebraFactory,
MockTimeAlgebraPool,
TestAlgebraSwapPay,
TestAlgebraCallee,
TestAlgebraReentrantCallee,
MockPoolPlugin,
TickMathTest,
PriceMovementMathTest,
IERC20Minimal,
} from '../typechain';
type ThenArg<T> = T extends PromiseLike<infer U> ? U : T;
describe('AlgebraPool', () => {
let wallet: Wallet, other: Wallet;
let token0: TestERC20;
let token1: TestERC20;
let token2: TestERC20;
let factory: AlgebraFactory;
let pool: MockTimeAlgebraPool;
let swapTarget: TestAlgebraCallee;
let swapToLowerPrice: SwapToPriceFunction;
let swapToHigherPrice: SwapToPriceFunction;
let swapExact0For1SupportingFee: SwapFunction;
let swapExact1For0SupportingFee: SwapFunction;
let swapExact0For1: SwapFunction;
let swap0ForExact1: SwapFunction;
let swapExact1For0: SwapFunction;
let swap1ForExact0: SwapFunction;
let tickSpacing: number;
let minTick: number;
let maxTick: number;
let mint: MintFunction;
let flash: FlashFunction;
let createPoolWrapped: ThenArg<ReturnType<typeof poolFixture>>['createPool'];
let vaultAddress: string;
beforeEach('deploy fixture', async () => {
[wallet, other] = await (ethers as any).getSigners();
let vault;
let _createPool: ThenArg<ReturnType<typeof poolFixture>>['createPool'];
({
token0,
token1,
token2,
factory,
vault,
createPool: _createPool,
swapTargetCallee: swapTarget,
} = await loadFixture(poolFixture));
vaultAddress = await vault.getAddress();
createPoolWrapped = async () => {
const pool = await _createPool();
({
swapToLowerPrice,
swapToHigherPrice,
swapExact0For1,
swapExact0For1SupportingFee,
swap0ForExact1,
swapExact1For0,
swapExact1For0SupportingFee,
swap1ForExact0,
mint,
flash,
} = createPoolFunctions({
token0,
token1,
swapTarget,
pool,
}));
minTick = getMinTick(60);
maxTick = getMaxTick(60);
tickSpacing = 60;
return pool;
};
pool = await createPoolWrapped();
});
it('constructor initializes immutables', async () => {
expect(await pool.factory()).to.eq(await factory.getAddress());
expect(await pool.token0()).to.eq(await token0.getAddress());
expect(await pool.token1()).to.eq(await token1.getAddress());
expect(await pool.maxLiquidityPerTick()).to.eq(BigInt('191757638537527648490752896198553'));
});
it('_blockTimestamp works', async () => {
expect(await pool.checkBlockTimestamp()).to.be.eq(true);
});
it('isUnlocked', async () => {
expect(await pool.isUnlocked()).to.be.true; // false checked inside of TestAlgebraReentrantCallee.sol
});
it('tickTreeRoot is clear', async () => {
expect(await pool.tickTreeRoot()).to.be.eq(0);
});
describe('#initialize', () => {
it('fails if already initialized', async () => {
await pool.initialize(encodePriceSqrt(1, 1));
await expect(pool.initialize(encodePriceSqrt(1, 1))).to.be.reverted;
});
it('fails if starting price is too low', async () => {
await expect(pool.initialize(1)).to.be.revertedWithCustomError(pool, 'priceOutOfRange');
await expect(pool.initialize(MIN_SQRT_RATIO - 1n)).to.be.revertedWithCustomError(pool, 'priceOutOfRange');
});
it('fails if starting price is too high', async () => {
await expect(pool.initialize(MAX_SQRT_RATIO)).to.be.revertedWithCustomError(pool, 'priceOutOfRange');
await expect(pool.initialize(2n ** 160n - 1n)).to.be.revertedWithCustomError(pool, 'priceOutOfRange');
});
it('fails if community fee nonzero without vault', async () => {
const _factory = await ethers.getContractFactory('FaultyVaultFactoryStub');
const faultyVaultFactory = await _factory.deploy(ZeroAddress);
await factory.setDefaultCommunityFee(100);
await factory.setVaultFactory(faultyVaultFactory);
await expect(pool.initialize(MIN_SQRT_RATIO)).to.be.revertedWithCustomError(pool, 'invalidNewCommunityFee');
});
it('can be initialized at MIN_SQRT_RATIO', async () => {
await pool.initialize(MIN_SQRT_RATIO);
expect((await pool.globalState()).tick).to.eq(getMinTick(1));
});
it('can be initialized at MAX_SQRT_RATIO - 1', async () => {
await pool.initialize(MAX_SQRT_RATIO - 1n);
expect((await pool.globalState()).tick).to.eq(getMaxTick(1) - 1);
});
it('sets initial variables', async () => {
const initPrice = encodePriceSqrt(1, 2);
await pool.initialize(initPrice);
const { price } = await pool.globalState();
expect(price).to.eq(price);
//expect(timepointIndex).to.eq(0) TODO check plugin
expect((await pool.globalState()).tick).to.eq(-6932);
});
it('emits a Initialized event with the input tick', async () => {
const price = encodePriceSqrt(1, 2);
await expect(pool.initialize(price)).to.emit(pool, 'Initialize').withArgs(price, -6932);
});
it('emits configuration events', async () => {
const price = encodePriceSqrt(1, 2);
await expect(pool.initialize(price))
.to.emit(pool, 'TickSpacing')
.withArgs(tickSpacing)
.to.emit(pool, 'CommunityFee')
.withArgs(0);
});
});
it('safelyGetStateOfAMM', async () => {
await pool.initialize(encodePriceSqrt(1, 1));
const state = await pool.safelyGetStateOfAMM();
expect(state.sqrtPrice).to.eq(encodePriceSqrt(1, 1));
expect(state.tick).to.eq(0);
// revert case checked inside of TestAlgebraReentrantCallee.sol
});
describe('#mint', () => {
it('fails if not initialized', async () => {
await expect(mint(wallet.address, -tickSpacing, tickSpacing, 1)).to.be.revertedWithCustomError(
pool,
'notInitialized'
);
await expect(mint(wallet.address, getMinTick(1), getMaxTick(1), 100)).to.be.revertedWithCustomError(
pool,
'notInitialized'
);
await expect(mint(wallet.address, 0, getMaxTick(1), 100)).to.be.revertedWithCustomError(pool, 'notInitialized');
await expect(mint(wallet.address, getMinTick(1), 0, 100)).to.be.revertedWithCustomError(pool, 'notInitialized');
await expect(mint(wallet.address, getMaxTick(1) - 1, getMaxTick(1), 100)).to.be.revertedWithCustomError(
pool,
'notInitialized'
);
await expect(mint(wallet.address, getMinTick(1), getMinTick(1) + 1, 100)).to.be.revertedWithCustomError(
pool,
'notInitialized'
);
});
describe('after initialization', () => {
beforeEach('initialize the pool at price of 10:1', async () => {
await pool.initialize(encodePriceSqrt(1, 10));
await mint(wallet.address, minTick, maxTick, 3161);
});
describe('failure cases', () => {
describe('underpayment', () => {
let payer: TestAlgebraSwapPay;
beforeEach(async () => {
const factory = await ethers.getContractFactory('TestAlgebraSwapPay');
payer = (await factory.deploy()) as any as TestAlgebraSwapPay;
await token0.approve(payer, 2n ** 256n - 1n);
await token1.approve(payer, 2n ** 256n - 1n);
});
it('fails if token0 paid 0', async () => {
await expect(
payer.mint(pool, wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 100, 0, 100)
).to.be.revertedWithCustomError(pool, 'zeroLiquidityActual');
await expect(payer.mint(pool, wallet.address, -22980, 0, 10000, 0, 100)).to.be.revertedWithCustomError(
pool,
'zeroLiquidityActual'
);
});
it('fails if token1 paid 0', async () => {
await expect(
payer.mint(pool, wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 100, 100, 0)
).to.be.revertedWithCustomError(pool, 'zeroLiquidityActual');
await expect(
payer.mint(
pool,
wallet.address,
minTick + tickSpacing,
Math.floor((-23028 - tickSpacing) / tickSpacing) * tickSpacing,
10000,
100,
0
)
).to.be.revertedWithCustomError(pool, 'zeroLiquidityActual');
});
it('fails if token0 hardly underpaid', async () => {
await expect(
payer.mint(
pool,
wallet.address,
minTick + tickSpacing,
maxTick - tickSpacing,
100,
1,
expandTo18Decimals(100)
)
).to.be.revertedWithCustomError(pool, 'zeroLiquidityActual');
});
it('fails if token1 hardly underpaid', async () => {
await swapToHigherPrice(encodePriceSqrt(10, 1), wallet.address);
await expect(
payer.mint(
pool,
wallet.address,
minTick + tickSpacing,
maxTick - tickSpacing,
100,
expandTo18Decimals(100),
1
)
).to.be.revertedWithCustomError(pool, 'zeroLiquidityActual');
});
});
it('fails if bottomTick greater than topTick', async () => {
await expect(mint(wallet.address, 1, 0, 1)).to.be.revertedWithCustomError(pool, 'topTickLowerOrEqBottomTick');
});
it('fails if invalid tickspacing', async () => {
await expect(mint(wallet.address, tickSpacing - 1, tickSpacing * 2 - 1, 1)).to.be.revertedWithCustomError(
pool,
'tickIsNotSpaced'
);
await expect(mint(wallet.address, -(tickSpacing - 1), 0, 1)).to.be.revertedWithCustomError(
pool,
'tickIsNotSpaced'
);
await expect(mint(wallet.address, 0, tickSpacing - 1, 1)).to.be.revertedWithCustomError(
pool,
'tickIsNotSpaced'
);
});
it('fails if bottomTick less than min tick', async () => {
await expect(mint(wallet.address, -887273, 0, 1)).to.be.revertedWithCustomError(
pool,
'bottomTickLowerThanMIN'
);
});
it('fails if topTick greater than max tick', async () => {
await expect(mint(wallet.address, 0, 887273, 1)).to.be.revertedWithCustomError(pool, 'topTickAboveMAX');
});
it('fails if amount exceeds the max', async () => {
const maxLiquidityGross = await pool.maxLiquidityPerTick();
await expect(
mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, maxLiquidityGross + 1n)
).to.be.revertedWithCustomError(pool, 'liquidityOverflow');
await expect(mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, maxLiquidityGross)).to.not.be
.reverted;
});
it('fails if amount exceeds the max uint128', async () => {
await expect(mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, MaxUint128)).to.be.reverted;
});
it('fails if amount exceeds the 2**127', async () => {
await expect(mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 2n ** 127n)).to.be.reverted;
});
it('fails if total amount at tick exceeds the max', async () => {
await mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 1000);
const maxLiquidityGross = await pool.maxLiquidityPerTick();
await expect(
mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, maxLiquidityGross - 1000n + 1n)
).to.be.revertedWithCustomError(pool, 'liquidityOverflow');
await expect(
mint(wallet.address, minTick + tickSpacing * 2, maxTick - tickSpacing, maxLiquidityGross - 1000n + 1n)
).to.be.revertedWithCustomError(pool, 'liquidityOverflow');
await expect(
mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing * 2, maxLiquidityGross - 1000n + 1n)
).to.be.revertedWithCustomError(pool, 'liquidityOverflow');
await expect(mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, maxLiquidityGross - 1000n)).to
.not.be.reverted;
});
it('fails if amount is 0', async () => {
await expect(
mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 0)
).to.be.revertedWithCustomError(pool, 'zeroLiquidityDesired');
});
});
describe('success cases', () => {
afterEach('check reserves', async () => {
const reserves = await pool.getReserves();
const balances = [await token0.balanceOf(pool), await token1.balanceOf(pool)];
expect(reserves[0]).to.be.eq(balances[0]);
expect(reserves[1]).to.be.eq(balances[1]);
});
it('initial balances', async () => {
expect(await token0.balanceOf(pool)).to.eq(9996);
expect(await token1.balanceOf(pool)).to.eq(1000);
});
it('initial tick', async () => {
expect((await pool.globalState()).tick).to.eq(-23028);
});
it('emits event', async () => {
await expect(mint(wallet.address, 0, tickSpacing, expandTo18Decimals(1)))
.to.emit(pool, 'Mint')
.withArgs(
await swapTarget.getAddress(),
wallet.address,
0,
tickSpacing,
expandTo18Decimals(1),
'2995354955910781',
0
);
});
const hasRefund = async (_receipt: ContractTransactionReceipt | null, _token: IERC20Minimal, to: string) => {
const tokenAddress = await _token.getAddress();
if (!_receipt) return false;
return _receipt.logs?.some((x) => {
if (x.address != tokenAddress) return false;
const decoded = _token.interface.parseLog({ topics: [...x.topics], data: x.data });
if (!decoded) return false;
return decoded.name == 'Transfer' && decoded.args && decoded.args[1] == to;
});
};
it('refund if overpayment', async () => {
const factory = await ethers.getContractFactory('TestAlgebraSwapPay');
let payer = (await factory.deploy()) as any as TestAlgebraSwapPay;
await token0.approve(payer, 2n ** 256n - 1n);
await token1.approve(payer, 2n ** 256n - 1n);
const receipt = await (
await payer.mint(
pool,
wallet.address,
minTick + tickSpacing,
maxTick - tickSpacing,
10,
expandTo18Decimals(1000),
expandTo18Decimals(1000)
)
).wait();
const hasRefund0 = await hasRefund(receipt, token0, wallet.address);
const hasRefund1 = await hasRefund(receipt, token1, wallet.address);
expect(hasRefund0).to.be.true;
expect(hasRefund1).to.be.true;
});
it('do not refund if not overpaid', async () => {
const factory = await ethers.getContractFactory('TestAlgebraSwapPay');
let payer = (await factory.deploy()) as any as TestAlgebraSwapPay;
await token0.approve(payer, 2n ** 256n - 1n);
await token1.approve(payer, 2n ** 256n - 1n);
const tx = await mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, expandTo18Decimals(1000));
const receipt = await tx.wait();
const hasRefund0 = await hasRefund(receipt, token0, wallet.address);
const hasRefund1 = await hasRefund(receipt, token1, wallet.address);
expect(hasRefund0).to.be.false;
expect(hasRefund1).to.be.false;
});
describe('underpayment', () => {
let payer: TestAlgebraSwapPay;
// TODO improve tests, check liquiditys
beforeEach(async () => {
const factory = await ethers.getContractFactory('TestAlgebraSwapPay');
payer = (await factory.deploy()) as any as TestAlgebraSwapPay;
await token0.approve(payer, 2n ** 256n - 1n);
await token1.approve(payer, 2n ** 256n - 1n);
});
it('handle underpayment in both tokens', async () => {
await expect(
payer.mint(pool, wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 1000000, 100, 100)
).to.not.be.reverted;
});
it('handle underpayment in both tokens, token0 less', async () => {
await expect(
payer.mint(pool, wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 1000000, 50, 100)
).to.not.be.reverted;
});
it('handle underpayment in both tokens, token1 less', async () => {
await expect(
payer.mint(pool, wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 1000000, 100, 50)
).to.not.be.reverted;
});
it('handle underpayment in token0', async () => {
await expect(
payer.mint(pool, wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 1000000, 100, 100000000)
).to.not.be.reverted;
});
it('handle underpayment in token1', async () => {
await expect(
payer.mint(pool, wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 1000000, 100000000, 100)
).to.not.be.reverted;
});
});
describe('above current price', () => {
it('transfers token0 only', async () => {
const poolAddress = await pool.getAddress();
await expect(mint(wallet.address, -22980, 0, 10000))
.to.emit(token0, 'Transfer')
.withArgs(wallet.address, poolAddress, 21549)
.to.not.emit(token1, 'Transfer');
expect(await token0.balanceOf(pool)).to.eq(9996 + 21549);
expect(await token1.balanceOf(pool)).to.eq(1000);
});
it('max tick with max leverage', async () => {
await mint(wallet.address, maxTick - tickSpacing, maxTick, 2n ** 102n);
expect(await token0.balanceOf(pool)).to.eq(9996 + 828011525);
expect(await token1.balanceOf(pool)).to.eq(1000);
});
it('works for max tick', async () => {
await expect(mint(wallet.address, -22980, maxTick, 10000))
.to.emit(token0, 'Transfer')
.withArgs(wallet.address, await pool.getAddress(), 31549);
expect(await token0.balanceOf(pool)).to.eq(9996 + 31549);
expect(await token1.balanceOf(pool)).to.eq(1000);
});
it('removing works', async () => {
await mint(wallet.address, -240, 0, 10000);
await pool.burn(-240, 0, 10000, '0x');
const { amount0, amount1 } = await pool.collect.staticCall(wallet.address, -240, 0, MaxUint128, MaxUint128);
expect(amount0, 'amount0').to.eq(120);
expect(amount1, 'amount1').to.eq(0);
});
it('removing works with min amounts', async () => {
await mint(wallet.address, -240, 0, 10000);
await pool.burn(-240, 0, 10000, '0x');
const { amount0, amount1 } = await pool.collect.staticCall(wallet.address, -240, 0, 1, 1);
expect(amount0, 'amount0').to.eq(1);
expect(amount1, 'amount1').to.eq(0);
});
it('removing works after tickSpacing increase', async () => {
await mint(wallet.address, -240, 0, 10000);
await pool.setTickSpacing(100);
await pool.burn(-240, 0, 10000, '0x');
const { amount0, amount1 } = await pool.collect.staticCall(wallet.address, -240, 0, MaxUint128, MaxUint128);
expect(amount0, 'amount0').to.eq(120);
expect(amount1, 'amount1').to.eq(0);
});
it('removing works after tickSpacing decrease', async () => {
await mint(wallet.address, -240, 0, 10000);
await pool.setTickSpacing(1);
await pool.burn(-240, 0, 10000, '0x');
const { amount0, amount1 } = await pool.collect.staticCall(wallet.address, -240, 0, MaxUint128, MaxUint128);
expect(amount0, 'amount0').to.eq(120);
expect(amount1, 'amount1').to.eq(0);
});
it('adds liquidity to liquidityTotal', async () => {
await mint(wallet.address, -240, 0, 100);
expect((await pool.ticks(-240)).liquidityTotal).to.eq(100);
expect((await pool.ticks(0)).liquidityTotal).to.eq(100);
expect((await pool.ticks(tickSpacing)).liquidityTotal).to.eq(0);
expect((await pool.ticks(tickSpacing * 2)).liquidityTotal).to.eq(0);
await mint(wallet.address, -240, tickSpacing, 150);
expect((await pool.ticks(-240)).liquidityTotal).to.eq(250);
expect((await pool.ticks(0)).liquidityTotal).to.eq(100);
expect((await pool.ticks(tickSpacing)).liquidityTotal).to.eq(150);
expect((await pool.ticks(tickSpacing * 2)).liquidityTotal).to.eq(0);
await mint(wallet.address, 0, tickSpacing * 2, 60);
expect((await pool.ticks(-240)).liquidityTotal).to.eq(250);
expect((await pool.ticks(0)).liquidityTotal).to.eq(160);
expect((await pool.ticks(tickSpacing)).liquidityTotal).to.eq(150);
expect((await pool.ticks(tickSpacing * 2)).liquidityTotal).to.eq(60);
});
it('removes liquidity from liquidityTotal', async () => {
await mint(wallet.address, -240, 0, 100);
await mint(wallet.address, -240, 0, 40);
await pool.burn(-240, 0, 90, '0x');
expect((await pool.ticks(-240)).liquidityTotal).to.eq(50);
expect((await pool.ticks(0)).liquidityTotal).to.eq(50);
});
it('clears tick lower if last position is removed', async () => {
await mint(wallet.address, -240, 0, 100);
await pool.burn(-240, 0, 100, '0x');
const { liquidityTotal, outerFeeGrowth0Token, outerFeeGrowth1Token } = await pool.ticks(-240);
expect(liquidityTotal).to.eq(0);
expect(outerFeeGrowth0Token).to.eq(0);
expect(outerFeeGrowth1Token).to.eq(0);
});
it('clears tick upper if last position is removed', async () => {
await mint(wallet.address, -240, 0, 100);
await pool.burn(-240, 0, 100, '0x');
const { liquidityTotal, outerFeeGrowth0Token, outerFeeGrowth1Token } = await pool.ticks(0);
expect(liquidityTotal).to.eq(0);
expect(outerFeeGrowth0Token).to.eq(0);
expect(outerFeeGrowth1Token).to.eq(0);
});
it('only clears the tick that is not used at all', async () => {
await mint(wallet.address, -240, 0, 100);
await mint(wallet.address, -tickSpacing, 0, 250);
await pool.burn(-240, 0, 100, '0x');
let { liquidityTotal, outerFeeGrowth0Token, outerFeeGrowth1Token } = await pool.ticks(-240);
expect(liquidityTotal).to.eq(0);
expect(outerFeeGrowth0Token).to.eq(0);
expect(outerFeeGrowth1Token).to.eq(0);
({ liquidityTotal, outerFeeGrowth0Token, outerFeeGrowth1Token } = await pool.ticks(-tickSpacing));
expect(liquidityTotal).to.eq(250);
expect(outerFeeGrowth0Token).to.eq(0);
expect(outerFeeGrowth1Token).to.eq(0);
});
});
describe('including current price', () => {
it('price within range: transfers current price of both tokens', async () => {
const poolAddress = await pool.getAddress();
await expect(mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 100))
.to.emit(token0, 'Transfer')
.withArgs(wallet.address, poolAddress, 317)
.to.emit(token1, 'Transfer')
.withArgs(wallet.address, poolAddress, 32);
expect(await token0.balanceOf(pool)).to.eq(9996 + 317);
expect(await token1.balanceOf(pool)).to.eq(1000 + 32);
});
it('initializes lower tick', async () => {
await mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 100);
const { liquidityTotal } = await pool.ticks(minTick + tickSpacing);
expect(liquidityTotal).to.eq(100);
});
it('initializes upper tick', async () => {
await mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 100);
const { liquidityTotal } = await pool.ticks(maxTick - tickSpacing);
expect(liquidityTotal).to.eq(100);
});
it('works for min/max tick', async () => {
const poolAddress = await pool.getAddress();
await expect(mint(wallet.address, minTick, maxTick, 10000))
.to.emit(token0, 'Transfer')
.withArgs(wallet.address, poolAddress, 31623)
.to.emit(token1, 'Transfer')
.withArgs(wallet.address, poolAddress, 3163);
expect(await token0.balanceOf(pool)).to.eq(9996 + 31623);
expect(await token1.balanceOf(pool)).to.eq(1000 + 3163);
});
it('removing works', async () => {
await mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 100);
await pool.burn(minTick + tickSpacing, maxTick - tickSpacing, 100, '0x');
const { amount0, amount1 } = await pool.collect.staticCall(
wallet.address,
minTick + tickSpacing,
maxTick - tickSpacing,
MaxUint128,
MaxUint128
);
expect(amount0, 'amount0').to.eq(316);
expect(amount1, 'amount1').to.eq(31);
});
});
describe('below current price', () => {
it('transfers token1 only', async () => {
await expect(mint(wallet.address, -46080, -23040, 10000))
.to.emit(token1, 'Transfer')
.withArgs(wallet.address, await pool.getAddress(), 2162)
.to.not.emit(token0, 'Transfer');
expect(await token0.balanceOf(pool)).to.eq(9996);
expect(await token1.balanceOf(pool)).to.eq(1000 + 2162);
});
it('min tick with max leverage', async () => {
await mint(wallet.address, minTick, minTick + tickSpacing, 2n ** 102n);
expect(await token0.balanceOf(pool)).to.eq(9996);
expect(await token1.balanceOf(pool)).to.eq(1000 + 828011520);
});
it('works for min tick', async () => {
await expect(mint(wallet.address, minTick, -23040, 10000))
.to.emit(token1, 'Transfer')
.withArgs(wallet.address, await pool.getAddress(), 3161);
expect(await token0.balanceOf(pool)).to.eq(9996);
expect(await token1.balanceOf(pool)).to.eq(1000 + 3161);
});
it('removing works', async () => {
await mint(wallet.address, -46080, -46020, 10000);
await pool.burn(-46080, -46020, 10000, '0x');
const { amount0, amount1 } = await pool.collect.staticCall(
wallet.address,
-46080,
-46020,
MaxUint128,
MaxUint128
);
expect(amount0, 'amount0').to.eq(0);
expect(amount1, 'amount1').to.eq(3);
});
});
});
it('community fees accumulate as expected during swap', async () => {
await pool.setCommunityFee(170);
await mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, expandTo18Decimals(1));
await swapExact0For1(expandTo18Decimals(1) / 10n, wallet.address);
await swapExact1For0(expandTo18Decimals(1) / 100n, wallet.address);
expect((await token0.balanceOf(vaultAddress)).toString()).to.eq('8500000000000');
const [, communityFeePending1] = await pool.getCommunityFeePending();
expect(communityFeePending1.toString()).to.eq('850000000000');
});
it('positions are protected before community fee is turned on', async () => {
await mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, expandTo18Decimals(1));
await swapExact0For1(expandTo18Decimals(1) / 10n, wallet.address);
await swapExact1For0(expandTo18Decimals(1) / 100n, wallet.address);
expect(Number((await token0.balanceOf(vaultAddress)).toString())).to.eq(0);
expect(Number((await token1.balanceOf(vaultAddress)).toString())).to.eq(0);
await pool.setCommunityFee(170);
expect(Number((await token0.balanceOf(vaultAddress)).toString())).to.eq(0);
expect(Number((await token1.balanceOf(vaultAddress)).toString())).to.eq(0);
});
it('poke is not happened on uninitialized position', async () => {
await mint(other.address, minTick + tickSpacing, maxTick - tickSpacing, expandTo18Decimals(1));
await swapExact0For1(expandTo18Decimals(1) / 10n, wallet.address);
await swapExact1For0(expandTo18Decimals(1) / 100n, wallet.address);
await expect(pool.burn(minTick + tickSpacing, maxTick - tickSpacing, 0, '0x')).to.be.not.reverted;
let {
liquidity: l0,
innerFeeGrowth0Token: ifg0,
innerFeeGrowth1Token: ifg1,
fees1: f1,
fees0: f0,
} = await pool.positions(
await pool.getKeyForPosition(wallet.address, minTick + tickSpacing, maxTick - tickSpacing)
);
expect(l0).to.eq(0);
expect(f0, 'tokens owed 0 before np').to.eq(0);
expect(f1, 'tokens owed 1 before np').to.eq(0);
expect(ifg0).to.eq('0');
expect(ifg1).to.eq('0');
await mint(wallet.address, minTick + tickSpacing, maxTick - tickSpacing, 1);
let { liquidity, innerFeeGrowth0Token, innerFeeGrowth1Token, fees1, fees0 } = await pool.positions(
await pool.getKeyForPosition(wallet.address, minTick + tickSpacing, maxTick - tickSpacing)
);
expect(liquidity).to.eq(1);
expect(fees0, 'tokens owed 0 before').to.eq(0);
expect(fees1, 'tokens owed 1 before').to.eq(0);
expect(innerFeeGrowth0Token).to.eq('17014118346046869391540638517434263');
expect(innerFeeGrowth1Token).to.eq('1701411834604686939154063851743426');
await pool.burn(minTick + tickSpacing, maxTick - tickSpacing, 1, '0x');
({ liquidity, innerFeeGrowth0Token, innerFeeGrowth1Token, fees1, fees0 } = await pool.positions(
await pool.getKeyForPosition(wallet.address, minTick + tickSpacing, maxTick - tickSpacing)
));
expect(liquidity).to.eq(0);
expect(innerFeeGrowth0Token).to.eq('17014118346046869391540638517434263');
expect(innerFeeGrowth1Token).to.eq('1701411834604686939154063851743426');
expect(fees0, 'tokens owed 0 after').to.eq(3);
expect(fees1, 'tokens owed 1 after').to.eq(0);
});
});
});
describe('#burn', () => {
beforeEach('initialize at zero tick', () => initializeAtZeroTick(pool));
async function checkTickIsClear(tick: number) {
const { liquidityTotal, outerFeeGrowth0Token, outerFeeGrowth1Token, liquidityDelta } = await pool.ticks(tick);
expect(liquidityTotal).to.eq(0);
expect(outerFeeGrowth0Token).to.eq(0);
expect(outerFeeGrowth1Token).to.eq(0);
expect(liquidityDelta).to.eq(0);
}
async function checkTickIsNotClear(tick: number) {
const { liquidityTotal } = await pool.ticks(tick);
expect(liquidityTotal).to.not.eq(0);
}
it('does not clear the position fee growth snapshot if no more liquidity', async () => {
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(other.address, minTick, maxTick, expandTo18Decimals(1));
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await swapExact1For0(expandTo18Decimals(1), wallet.address);
await pool.connect(other).burn(minTick, maxTick, expandTo18Decimals(1), '0x');
const { liquidity, fees0, fees1, innerFeeGrowth0Token, innerFeeGrowth1Token } = await pool.positions(
await pool.getKeyForPosition(other.address, minTick, maxTick)
);
expect(liquidity).to.eq(0);
expect(fees0).to.not.eq(0);
expect(fees1).to.not.eq(0);
expect(innerFeeGrowth0Token).to.eq('56713727820156410577229101238628035');
expect(innerFeeGrowth1Token).to.eq('56713727820156410577229101238628035');
});
it('clears the tick if its the last position using it', async () => {
const bottomTick = minTick + tickSpacing;
const topTick = maxTick - tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(wallet.address, bottomTick, topTick, 1);
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await pool.burn(bottomTick, topTick, 1, '0x');
await checkTickIsClear(bottomTick);
await checkTickIsClear(topTick);
});
it('clears the tick if its the last position using it after tickSpacing increase', async () => {
const bottomTick = minTick + tickSpacing;
const topTick = maxTick - tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(wallet.address, bottomTick, topTick, 1);
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await pool.setTickSpacing(200);
await pool.burn(bottomTick, topTick, 1, '0x');
await checkTickIsClear(bottomTick);
await checkTickIsClear(topTick);
});
it('clears only the lower tick if upper is still used', async () => {
const bottomTick = minTick + tickSpacing;
const topTick = maxTick - tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(wallet.address, bottomTick, topTick, 1);
await mint(wallet.address, bottomTick + tickSpacing, topTick, 1);
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await pool.burn(bottomTick, topTick, 1, '0x');
await checkTickIsClear(bottomTick);
await checkTickIsNotClear(topTick);
});
it('clears only the lower tick if upper is still used after tickSpacing decrease', async () => {
const bottomTick = minTick + tickSpacing;
const topTick = maxTick - tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(wallet.address, bottomTick, topTick, 1);
await mint(wallet.address, bottomTick + tickSpacing, topTick, 1);
await pool.setTickSpacing(5);
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await pool.burn(bottomTick, topTick, 1, '0x');
await checkTickIsClear(bottomTick);
await checkTickIsNotClear(topTick);
});
it('clears only the upper tick if lower is still used', async () => {
const bottomTick = minTick + tickSpacing;
const topTick = maxTick - tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(wallet.address, bottomTick, topTick, 1);
await mint(wallet.address, bottomTick, topTick - tickSpacing, 1);
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await pool.burn(bottomTick, topTick, 1, '0x');
await checkTickIsNotClear(bottomTick);
await checkTickIsClear(topTick);
});
it('clears only the upper tick if lower is still used after tickSpacing increase', async () => {
const bottomTick = minTick + tickSpacing;
const topTick = maxTick - tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(wallet.address, bottomTick, topTick, 1);
await mint(wallet.address, bottomTick, topTick - tickSpacing, 1);
await pool.setTickSpacing(100);
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await pool.burn(bottomTick, topTick, 1, '0x');
await checkTickIsNotClear(bottomTick);
await checkTickIsClear(topTick);
});
it('fails when try to burn with incorrect ticks', async () => {
const bottomTick = minTick + tickSpacing;
const topTick = maxTick - tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(wallet.address, bottomTick, topTick, 1);
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await expect(pool.burn(topTick, bottomTick, 1, '0x')).to.be.revertedWithCustomError(
pool,
'topTickLowerOrEqBottomTick'
);
});
it('fails when try to burn max uint128 value', async () => {
const bottomTick = minTick + tickSpacing;
const topTick = maxTick - tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(wallet.address, bottomTick, topTick, 1);
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await expect(pool.burn(bottomTick, topTick, 2n ** 128n - 1n, '0x')).to.be.revertedWithCustomError(
pool,
'arithmeticError'
);
});
it('fails when try to burn max int128 + 1 value', async () => {
const bottomTick = minTick + tickSpacing;
const topTick = maxTick - tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await mint(wallet.address, bottomTick, topTick, 1);
await swapExact0For1(expandTo18Decimals(1), wallet.address);
await expect(pool.burn(bottomTick, topTick, 2n ** 127n, '0x')).to.be.revertedWithCustomError(
pool,
'arithmeticError'
);
});
it('do not emit event after poke on empty position', async () => {
const bottomTick = minTick + 2 * tickSpacing;
const topTick = maxTick - 2 * tickSpacing;
// some activity that would make the ticks non-zero
await pool.advanceTime(10);
await expect(pool.burn(bottomTick, topTick, 0, '0x')).to.not.emit(pool, 'Burn');
});
});
// the combined amount of liquidity that the pool is initialized with (including the 1 minimum liquidity that is burned)
const initializeLiquidityAmount = expandTo18Decimals(2);
async function initializeAtZeroTick(pool: MockTimeAlgebraPool): Promise<void> {
await pool.initialize(encodePriceSqrt(1, 1));
const tickSpacing = Number(await pool.tickSpacing());
const [min, max] = [getMinTick(tickSpacing), getMaxTick(tickSpacing)];
await mint(wallet.address, min, max, initializeLiquidityAmount);
}
describe('miscellaneous mint tests', () => {
beforeEach('initialize at zero tick', async () => {
pool = await createPoolWrapped();
await initializeAtZeroTick(pool);
});
it('mint to the right of the current price', async () => {
const liquidityDelta = 1000;
const bottomTick = tickSpacing;
const topTick = tickSpacing * 2;
const liquidityBefore = await pool.liquidity();
const b0 = await token0.balanceOf(pool);
const b1 = await token1.balanceOf(pool);
await mint(wallet.address, bottomTick, topTick, liquidityDelta);
const liquidityAfter = await pool.liquidity();
expect(liquidityAfter).to.be.gte(liquidityBefore);
expect((await token0.balanceOf(pool)) - b0).to.eq(3);
expect((await token1.balanceOf(pool)) - b1).to.eq(0);
});
it('mint to the left of the current price', async () => {
const liquidityDelta = 1000;
const bottomTick = -tickSpacing * 2;
const topTick = -tickSpacing;
const liquidityBefore = await pool.liquidity();
const b0 = await token0.balanceOf(pool);
const b1 = await token1.balanceOf(pool);
await mint(wallet.address, bottomTick, topTick, liquidityDelta);
const liquidityAfter = await pool.liquidity();
expect(liquidityAfter).to.be.gte(liquidityBefore);
expect((await token0.balanceOf(pool)) - b0).to.eq(0);
expect((await token1.balanceOf(pool)) - b1).to.eq(3);
});
it('mint within the current price', async () => {
const liquidityDelta = 1000;
const bottomTick = -tickSpacing;
const topTick = tickSpacing;
const liquidityBefore = await pool.liquidity();
const b0 = await token0.balanceOf(pool);
const b1 = await token1.balanceOf(pool);
await mint(wallet.address, bottomTick, topTick, liquidityDelta);
const liquidityAfter = await pool.liquidity();
expect(liquidityAfter).to.be.gte(liquidityBefore);
expect((await token0.balanceOf(pool)) - b0).to.eq(3);
expect((await token1.balanceOf(pool)) - b1).to.eq(3);
});
it('cannot remove more than the entire position', async () => {
const bottomTick = -tickSpacing;
const topTick = tickSpacing;
await mint(wallet.address, bottomTick, topTick, expandTo18Decimals(1000));