-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathPool.bundle.spec.ts
1167 lines (992 loc) · 45.5 KB
/
Pool.bundle.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 { expect } from "chai";
import { ethers, network } from "hardhat";
import * as helpers from "@nomicfoundation/hardhat-network-helpers";
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/dist/src/signer-with-address";
import {
TestERC20,
TestERC721,
TestProxy,
TestLoanReceipt,
TestDelegateRegistryV1,
TestDelegateRegistryV2,
ExternalCollateralLiquidator,
Pool,
BundleCollateralWrapper,
ERC20DepositTokenImplementation,
} from "../typechain";
import { getContractFactoryWithLibraries } from "./helpers/Deploy";
import { extractEvent, expectEvent } from "./helpers/EventUtilities";
import { FixedPoint } from "./helpers/FixedPoint";
import { Tick } from "./helpers/Tick";
describe("Pool Bundle", function () {
let accounts: SignerWithAddress[];
let tok1: TestERC20;
let nft1: TestERC721;
let loanReceiptLib: TestLoanReceipt;
let collateralLiquidator: ExternalCollateralLiquidator;
let poolImpl: Pool;
let pool: Pool;
let snapshotId: string;
let accountDepositors: SignerWithAddress[3];
let accountBorrower: SignerWithAddress;
let accountLender: SignerWithAddress;
let accountLiquidator: SignerWithAddress;
let delegateRegistryV1: TestDelegateRegistryV1;
let delegateRegistryV2: TestDelegateRegistryV2;
let bundleCollateralWrapper: BundleCollateralWrapper;
let erc20DepositTokenImpl: ERC20DepositTokenImplementation;
before("deploy fixture", async () => {
accounts = await ethers.getSigners();
const testERC20Factory = await ethers.getContractFactory("TestERC20");
const testERC721Factory = await ethers.getContractFactory("TestERC721");
const testLoanReceiptFactory = await ethers.getContractFactory("TestLoanReceipt");
const testProxyFactory = await ethers.getContractFactory("TestProxy");
const externalCollateralLiquidatorFactory = await ethers.getContractFactory("ExternalCollateralLiquidator");
const delegateRegistryV1Factory = await ethers.getContractFactory("TestDelegateRegistryV1");
const delegateRegistryV2Factory = await ethers.getContractFactory("TestDelegateRegistryV2");
const bundleCollateralWrapperFactory = await ethers.getContractFactory("BundleCollateralWrapper");
const erc20DepositTokenImplFactory = await ethers.getContractFactory("ERC20DepositTokenImplementation");
const poolImplFactory = await getContractFactoryWithLibraries("WeightedRateCollectionPool", [
"LiquidityLogic",
"DepositLogic",
"BorrowLogic",
"ERC20DepositTokenFactory",
]);
/* Deploy test currency token */
tok1 = (await testERC20Factory.deploy("Token 1", "TOK1", 18, ethers.parseEther("10000"))) as TestERC20;
await tok1.waitForDeployment();
/* Deploy test NFT */
nft1 = (await testERC721Factory.deploy("NFT 1", "NFT1", "https://nft1.com/token/")) as TestERC721;
await nft1.waitForDeployment();
/* Deploy loan receipt library */
loanReceiptLib = await testLoanReceiptFactory.deploy();
await loanReceiptLib.waitForDeployment();
/* Deploy external collateral liquidator implementation */
const collateralLiquidatorImpl = await externalCollateralLiquidatorFactory.deploy();
await collateralLiquidatorImpl.waitForDeployment();
/* Deploy collateral liquidator */
let proxy = await testProxyFactory.deploy(
await collateralLiquidatorImpl.getAddress(),
collateralLiquidatorImpl.interface.encodeFunctionData("initialize")
);
await proxy.waitForDeployment();
collateralLiquidator = (await ethers.getContractAt(
"ExternalCollateralLiquidator",
await proxy.getAddress()
)) as ExternalCollateralLiquidator;
/* Deploy test delegation registry v1 */
delegateRegistryV1 = await delegateRegistryV1Factory.deploy();
await delegateRegistryV1.waitForDeployment();
/* Deploy test delegation registry v2 */
delegateRegistryV2 = await delegateRegistryV2Factory.deploy();
await delegateRegistryV2.waitForDeployment();
/* Deploy bundle collateral wrapper */
bundleCollateralWrapper = await bundleCollateralWrapperFactory.deploy();
await bundleCollateralWrapper.waitForDeployment();
/* Deploy erc20 deposit token implementation */
erc20DepositTokenImpl = (await erc20DepositTokenImplFactory.deploy()) as ERC20DepositTokenImplementation;
await erc20DepositTokenImpl.waitForDeployment();
/* Deploy pool implementation */
poolImpl = (await poolImplFactory.deploy(
await collateralLiquidator.getAddress(),
await delegateRegistryV1.getAddress(),
await delegateRegistryV2.getAddress(),
await erc20DepositTokenImpl.getAddress(),
[await bundleCollateralWrapper.getAddress()]
)) as Pool;
await poolImpl.waitForDeployment();
/* Deploy pool */
proxy = await testProxyFactory.deploy(
await poolImpl.getAddress(),
poolImpl.interface.encodeFunctionData("initialize", [
ethers.AbiCoder.defaultAbiCoder().encode(
["address[]", "address", "address", "uint64[]", "uint64[]"],
[
[await nft1.getAddress()],
await tok1.getAddress(),
ethers.ZeroAddress,
[30 * 86400, 14 * 86400, 7 * 86400],
[FixedPoint.normalizeRate("0.10"), FixedPoint.normalizeRate("0.30"), FixedPoint.normalizeRate("0.50")],
]
),
])
);
await proxy.waitForDeployment();
pool = (await ethers.getContractAt("Pool", await proxy.getAddress())) as Pool;
/* Arrange accounts */
accountDepositors = accounts.slice(1, 4);
accountBorrower = accounts[4];
accountLender = accounts[5];
accountLiquidator = accounts[6];
/* Grant liquidator role to liquidator account */
await collateralLiquidator.grantRole(
await collateralLiquidator.COLLATERAL_LIQUIDATOR_ROLE(),
await accountLiquidator.getAddress()
);
/* Transfer TOK1 to depositors and approve Pool */
for (const depositor of accountDepositors) {
await tok1.transfer(await depositor.getAddress(), ethers.parseEther("1000"));
await tok1.connect(depositor).approve(await pool.getAddress(), ethers.MaxUint256);
}
/* Transfer TOK1 to liquidator and approve collateral liquidator */
await tok1.transfer(await accountLiquidator.getAddress(), ethers.parseEther("100"));
await tok1.connect(accountLiquidator).approve(await collateralLiquidator.getAddress(), ethers.MaxUint256);
/* Mint NFT to borrower */
await nft1.mint(await accountBorrower.getAddress(), 123);
await nft1.mint(await accountBorrower.getAddress(), 124);
await nft1.mint(await accountBorrower.getAddress(), 125);
/* Mint token to borrower */
await tok1.transfer(await accountBorrower.getAddress(), ethers.parseEther("100"));
/* Mint token to lender */
await tok1.transfer(await accountLender.getAddress(), ethers.parseEther("1000"));
/* Approve pool to transfer NFT */
await nft1.connect(accountBorrower).setApprovalForAll(await pool.getAddress(), true);
/* Approve pool to transfer token (for repayment) */
await tok1.connect(accountBorrower).approve(await pool.getAddress(), ethers.MaxUint256);
/* Approve bundle to transfer NFT */
await nft1.connect(accountBorrower).setApprovalForAll(await bundleCollateralWrapper.getAddress(), true);
/* Approve pool to transfer bundle NFT */
await bundleCollateralWrapper.connect(accountBorrower).setApprovalForAll(await pool.getAddress(), true);
});
beforeEach("snapshot blockchain", async () => {
snapshotId = await network.provider.send("evm_snapshot", []);
});
afterEach("restore blockchain snapshot", async () => {
await network.provider.send("evm_revert", [snapshotId]);
});
/****************************************************************************/
/* Constants */
/****************************************************************************/
describe("constants", async function () {
it("matches expected implementation name", async function () {
expect(await pool.IMPLEMENTATION_NAME()).to.equal("WeightedRateCollectionPool");
});
});
/****************************************************************************/
/* Getters */
/****************************************************************************/
describe("getters", async function () {
it("returns expected currency token", async function () {
expect(await pool.currencyToken()).to.equal(await tok1.getAddress());
});
it("returns expected admin fee rate", async function () {
expect(await pool.adminFeeRate()).to.equal(0);
});
it("returns expected collateral wrappers", async function () {
const collateralWrappers = await pool.collateralWrappers();
expect(collateralWrappers[0]).to.equal(await bundleCollateralWrapper.getAddress());
expect(collateralWrappers[1]).to.equal(ethers.ZeroAddress);
expect(collateralWrappers[2]).to.equal(ethers.ZeroAddress);
});
it("returns expected collateral liquidator", async function () {
expect(await pool.collateralLiquidator()).to.equal(await collateralLiquidator.getAddress());
});
it("returns expected delegation registry v1", async function () {
expect(await pool.delegationRegistry()).to.equal(await delegateRegistryV1.getAddress());
});
it("returns expected delegation registry v2", async function () {
expect(await pool.delegationRegistryV2()).to.equal(await delegateRegistryV2.getAddress());
});
});
/****************************************************************************/
/* Liquidity and Loan Helper functions */
/****************************************************************************/
const MaxUint128 = BigInt("0xffffffffffffffffffffffffffffffff");
const minBN = (a: bigint, b: bigint) => (a < b ? a : b);
const maxBN = (a: bigint, b: bigint) => (a > b ? a : b);
async function setupLiquidity(): Promise<void> {
const NUM_LIMITS = 20;
const TICK_LIMIT_SPACING_BASIS_POINTS = await pool.ABSOLUTE_TICK_LIMIT_SPACING_BASIS_POINTS();
let limit = FixedPoint.from("6.5");
for (let i = 0; i < NUM_LIMITS; i++) {
await pool.connect(accountDepositors[0]).deposit(Tick.encode(limit), FixedPoint.from("25"), 0);
limit = (limit * (TICK_LIMIT_SPACING_BASIS_POINTS + 10000n)) / 10000n;
}
}
async function sourceLiquidity(
amount: bigint,
multiplier?: bigint = 1n,
duration?: number = 0,
rate?: number = 0
): Promise<bigint[]> {
const nodes = await pool.liquidityNodes(0, MaxUint128);
const ticks = [];
let taken = 0n;
for (const node of nodes) {
const limit = Tick.decode(node.tick).limit;
if (limit === 0n) continue;
const take = minBN(minBN(limit * multiplier - taken, node.available), amount - taken);
if (take === 0n) break;
ticks.push(node.tick);
taken = taken + take;
}
if (taken !== amount) throw new Error(`Insufficient liquidity for amount ${amount.toString()}`);
return ticks;
}
async function createActiveLoan(principal: bigint, duration?: number = 30 * 86400): Promise<[string, string]> {
const tokenId =
(await nft1.ownerOf(123)) === (await accountBorrower.getAddress())
? 123
: (await nft1.ownerOf(124)) === (await accountBorrower.getAddress())
? 124
: 125;
const ticks = await sourceLiquidity(principal);
const repayment = await pool.quote(principal, duration, await nft1.getAddress(), tokenId, ticks, "0x");
const borrowTx = await pool
.connect(accountBorrower)
.borrow(principal, duration, await nft1.getAddress(), tokenId, repayment, ticks, "0x");
const loanReceipt = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceipt;
const loanReceiptHash = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceiptHash;
return [loanReceipt, loanReceiptHash];
}
async function createActiveBundleLoan(
principal: bigint,
duration?: number = 30 * 86400
): Promise<[string, string, bigint, string]> {
/* Mint bundle */
const mintTx = await bundleCollateralWrapper
.connect(accountBorrower)
.mint(await nft1.getAddress(), [123, 124, 125]);
const bundleTokenId = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.tokenId;
const bundleData = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.encodedBundle;
/* Borrow */
const borrowTx = await pool
.connect(accountBorrower)
.borrow(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("26"),
await sourceLiquidity(FixedPoint.from("25"), 3n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
/* Extract loan receipt */
const loanReceiptHash = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceiptHash;
const loanReceipt = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceipt;
return [loanReceipt, loanReceiptHash, bundleTokenId, bundleData];
}
/****************************************************************************/
/* Lend API */
/****************************************************************************/
describe("#quote", async function () {
beforeEach("setup liquidity", async function () {
await setupLiquidity();
});
it("correctly quotes repayment for bundle", async function () {
/* Mint bundle */
const mintTx = await bundleCollateralWrapper
.connect(accountBorrower)
.mint(await nft1.getAddress(), [123, 124, 125]);
const bundleTokenId = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.tokenId;
const bundleData = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.encodedBundle;
expect(
await pool.quote(
FixedPoint.from("10"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
await sourceLiquidity(FixedPoint.from("10")),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
)
).to.equal(FixedPoint.from("10.082191780812160000"));
expect(
await pool.quote(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
await sourceLiquidity(FixedPoint.from("25")),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
)
).to.equal(FixedPoint.from("25.205479452030400000"));
});
it("fails on insufficient liquidity for bundle", async function () {
/* Mint bundle */
const mintTx = await bundleCollateralWrapper
.connect(accountBorrower)
.mint(await nft1.getAddress(), [123, 124, 125]);
const bundleTokenId = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.tokenId;
const bundleData = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.encodedBundle;
await expect(
pool.quote(
FixedPoint.from("1000"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
await sourceLiquidity(FixedPoint.from("25")),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
)
).to.be.revertedWithCustomError(pool, "InsufficientLiquidity");
});
});
describe("#borrow", async function () {
beforeEach("setup liquidity", async function () {
await setupLiquidity();
});
it("originates bundle loan", async function () {
/* Mint bundle */
const mintTx = await bundleCollateralWrapper
.connect(accountBorrower)
.mint(await nft1.getAddress(), [123, 124, 125]);
const bundleTokenId = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.tokenId;
const bundleData = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.encodedBundle;
/* Quote repayment */
const repayment = await pool.quote(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
await sourceLiquidity(FixedPoint.from("25")),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
/* Simulate borrow */
const simulatedRepayment = await pool
.connect(accountBorrower)
.borrow.staticCall(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("26"),
await sourceLiquidity(FixedPoint.from("25"), 3n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
/* Borrow */
const borrowTx = await pool
.connect(accountBorrower)
.borrow(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("26"),
await sourceLiquidity(FixedPoint.from("25"), 3n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
/* Validate return value from borrow() */
expect(simulatedRepayment).to.equal(repayment);
/* Validate events */
await expectEvent(mintTx, bundleCollateralWrapper, "Transfer", {
from: ethers.ZeroAddress,
to: await accountBorrower.getAddress(),
tokenId: bundleTokenId,
});
await expectEvent(borrowTx, bundleCollateralWrapper, "Transfer", {
from: await accountBorrower.getAddress(),
to: await pool.getAddress(),
tokenId: bundleTokenId,
});
await expectEvent(borrowTx, tok1, "Transfer", {
from: await pool.getAddress(),
to: await accountBorrower.getAddress(),
value: FixedPoint.from("25"),
});
await expect(borrowTx).to.emit(pool, "LoanOriginated");
/* Extract loan receipt */
const loanReceiptHash = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceiptHash;
const loanReceipt = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceipt;
/* Validate hash */
expect(loanReceiptHash).to.equal(await loanReceiptLib.hash(loanReceipt));
/* Validate loan receipt */
const decodedLoanReceipt = await loanReceiptLib.decode(loanReceipt);
expect(decodedLoanReceipt.version).to.equal(2);
expect(decodedLoanReceipt.borrower).to.equal(await accountBorrower.getAddress());
expect(decodedLoanReceipt.maturity).to.equal(
BigInt((await ethers.provider.getBlock(borrowTx.blockHash!)).timestamp) + 30n * 86400n
);
expect(decodedLoanReceipt.duration).to.equal(30 * 86400);
expect(decodedLoanReceipt.collateralToken).to.equal(await bundleCollateralWrapper.getAddress());
expect(decodedLoanReceipt.collateralTokenId).to.equal(bundleTokenId);
expect(decodedLoanReceipt.collateralWrapperContextLen).to.equal(ethers.dataLength(bundleData));
expect(decodedLoanReceipt.collateralWrapperContext).to.equal(bundleData);
expect(decodedLoanReceipt.nodeReceipts.length).to.equal(4);
/* Sum used and pending totals from node receipts */
let totalUsed = 0n;
let totalPending = 0n;
for (const nodeReceipt of decodedLoanReceipt.nodeReceipts) {
totalUsed = totalUsed + nodeReceipt.used;
totalPending = totalPending + nodeReceipt.pending;
}
/* Validate used and pending totals */
expect(totalUsed).to.equal(FixedPoint.from("25"));
expect(totalPending).to.equal(repayment);
/* Validate loan state */
expect(await pool.loans(loanReceiptHash)).to.equal(1);
});
it("originates bundle loan with delegation", async function () {
/* Mint bundle */
const mintTx = await bundleCollateralWrapper
.connect(accountBorrower)
.mint(await nft1.getAddress(), [123, 124, 125]);
const bundleTokenId = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.tokenId;
const bundleData = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.encodedBundle;
/* Quote repayment */
const repayment = await pool.quote(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
await sourceLiquidity(FixedPoint.from("25")),
ethers.solidityPacked(
["uint16", "uint16", "bytes", "uint16", "uint16", "bytes20"],
[1, ethers.dataLength(bundleData), bundleData, 3, 20, await accountBorrower.getAddress()]
)
);
/* Simulate borrow */
const simulatedRepayment = await pool
.connect(accountBorrower)
.borrow.staticCall(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("26"),
await sourceLiquidity(FixedPoint.from("25"), 3n),
ethers.solidityPacked(
["uint16", "uint16", "bytes", "uint16", "uint16", "bytes20"],
[1, ethers.dataLength(bundleData), bundleData, 3, 20, await accountBorrower.getAddress()]
)
);
/* Borrow */
const borrowTx = await pool
.connect(accountBorrower)
.borrow(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("26"),
await sourceLiquidity(FixedPoint.from("25"), 3n),
ethers.solidityPacked(
["uint16", "uint16", "bytes", "uint16", "uint16", "bytes20"],
[1, ethers.dataLength(bundleData), bundleData, 3, 20, await accountBorrower.getAddress()]
)
);
/* Validate return value from borrow() */
expect(simulatedRepayment).to.equal(repayment);
/* Validate events */
await expectEvent(mintTx, bundleCollateralWrapper, "Transfer", {
from: ethers.ZeroAddress,
to: await accountBorrower.getAddress(),
tokenId: bundleTokenId,
});
await expectEvent(borrowTx, bundleCollateralWrapper, "Transfer", {
from: await accountBorrower.getAddress(),
to: await pool.getAddress(),
tokenId: bundleTokenId,
});
await expectEvent(borrowTx, tok1, "Transfer", {
from: await pool.getAddress(),
to: await accountBorrower.getAddress(),
value: FixedPoint.from("25"),
});
await expectEvent(borrowTx, delegateRegistryV1, "DelegateForToken", {
vault: await pool.getAddress(),
delegate: await accountBorrower.getAddress(),
contract_: await bundleCollateralWrapper.getAddress(),
tokenId: bundleTokenId,
value: true,
});
await expect(borrowTx).to.emit(pool, "LoanOriginated");
/* Extract loan receipt */
const loanReceiptHash = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceiptHash;
const loanReceipt = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceipt;
/* Validate hash */
expect(loanReceiptHash).to.equal(await loanReceiptLib.hash(loanReceipt));
/* Validate loan receipt */
const decodedLoanReceipt = await loanReceiptLib.decode(loanReceipt);
expect(decodedLoanReceipt.version).to.equal(2);
expect(decodedLoanReceipt.borrower).to.equal(await accountBorrower.getAddress());
expect(decodedLoanReceipt.maturity).to.equal(
BigInt((await ethers.provider.getBlock(borrowTx.blockHash!)).timestamp) + 30n * 86400n
);
expect(decodedLoanReceipt.duration).to.equal(30 * 86400);
expect(decodedLoanReceipt.collateralToken).to.equal(await bundleCollateralWrapper.getAddress());
expect(decodedLoanReceipt.collateralTokenId).to.equal(bundleTokenId);
expect(decodedLoanReceipt.collateralWrapperContextLen).to.equal(ethers.dataLength(bundleData));
expect(decodedLoanReceipt.collateralWrapperContext).to.equal(bundleData);
expect(decodedLoanReceipt.nodeReceipts.length).to.equal(4);
/* Sum used and pending totals from node receipts */
let totalUsed = 0n;
let totalPending = 0n;
for (const nodeReceipt of decodedLoanReceipt.nodeReceipts) {
totalUsed = totalUsed + nodeReceipt.used;
totalPending = totalPending + nodeReceipt.pending;
}
/* Validate used and pending totals */
expect(totalUsed).to.equal(FixedPoint.from("25"));
expect(totalPending).to.equal(repayment);
/* Validate loan state */
expect(await pool.loans(loanReceiptHash)).to.equal(1);
});
it("originates bundle loan for a 85 ETH principal", async function () {
/* Mint bundle */
const mintTx = await bundleCollateralWrapper
.connect(accountBorrower)
.mint(await nft1.getAddress(), [123, 124, 125]);
const bundleTokenId = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.tokenId;
const bundleData = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.encodedBundle;
/* Quote repayment */
const repayment = await pool.quote(
FixedPoint.from("85"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
await sourceLiquidity(FixedPoint.from("85"), 3n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
/* Simulate borrow */
const simulatedRepayment = await pool
.connect(accountBorrower)
.borrow.staticCall(
FixedPoint.from("85"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("88"),
await sourceLiquidity(FixedPoint.from("85"), 3n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
/* Validate return value from borrow() */
expect(simulatedRepayment).to.equal(repayment);
/* Borrow */
const borrowTx = await pool
.connect(accountBorrower)
.borrow(
FixedPoint.from("85"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("88"),
await sourceLiquidity(FixedPoint.from("85"), 3n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
/* Validate events */
await expectEvent(mintTx, bundleCollateralWrapper, "Transfer", {
from: ethers.ZeroAddress,
to: await accountBorrower.getAddress(),
tokenId: bundleTokenId,
});
await expectEvent(borrowTx, bundleCollateralWrapper, "Transfer", {
from: await accountBorrower.getAddress(),
to: await pool.getAddress(),
tokenId: bundleTokenId,
});
await expectEvent(borrowTx, tok1, "Transfer", {
from: await pool.getAddress(),
to: await accountBorrower.getAddress(),
value: FixedPoint.from("85"),
});
await expect(borrowTx).to.emit(pool, "LoanOriginated");
/* Extract loan receipt */
const loanReceiptHash = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceiptHash;
const loanReceipt = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceipt;
/* Validate hash */
expect(loanReceiptHash).to.equal(await loanReceiptLib.hash(loanReceipt));
/* Validate loan receipt */
const decodedLoanReceipt = await loanReceiptLib.decode(loanReceipt);
expect(decodedLoanReceipt.version).to.equal(2);
expect(decodedLoanReceipt.borrower).to.equal(await accountBorrower.getAddress());
expect(decodedLoanReceipt.maturity).to.equal(
BigInt((await ethers.provider.getBlock(borrowTx.blockHash!)).timestamp) + 30n * 86400n
);
expect(decodedLoanReceipt.duration).to.equal(30 * 86400);
expect(decodedLoanReceipt.collateralToken).to.equal(await bundleCollateralWrapper.getAddress());
expect(decodedLoanReceipt.collateralTokenId).to.equal(bundleTokenId);
expect(decodedLoanReceipt.collateralWrapperContextLen).to.equal(ethers.dataLength(bundleData));
expect(decodedLoanReceipt.collateralWrapperContext).to.equal(bundleData);
expect(decodedLoanReceipt.nodeReceipts.length).to.equal(17);
/* Sum used and pending totals from node receipts */
let totalUsed = 0n;
let totalPending = 0n;
for (const nodeReceipt of decodedLoanReceipt.nodeReceipts) {
totalUsed = totalUsed + nodeReceipt.used;
totalPending = totalPending + nodeReceipt.pending;
}
/* Validate used and pending totals */
expect(totalUsed).to.equal(FixedPoint.from("85"));
expect(totalPending).to.equal(repayment);
/* Validate loan state */
expect(await pool.loans(loanReceiptHash)).to.equal(1);
});
it("fails on bundle with invalid option encoding", async function () {
/* Mint bundle */
const mintTx = await bundleCollateralWrapper
.connect(accountBorrower)
.mint(await nft1.getAddress(), [123, 124, 125]);
const bundleTokenId = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.tokenId;
const bundleData = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.encodedBundle;
/* Set length of tokenId to 31 instead of 32 */
await expect(
pool
.connect(accountBorrower)
.borrow(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("26"),
await sourceLiquidity(FixedPoint.from("25"), 3n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, 20 + 31 * 3, bundleData])
)
).to.be.reverted;
});
it("fails on insufficient liquidity with bundle", async function () {
const mintTx = await bundleCollateralWrapper
.connect(accountBorrower)
.mint(await nft1.getAddress(), [123, 124, 125]);
const bundleTokenId = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.tokenId;
const bundleData = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.encodedBundle;
await expect(
pool
.connect(accountBorrower)
.borrow(
FixedPoint.from("120"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("122"),
await sourceLiquidity(FixedPoint.from("85"), 3n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
)
).to.be.revertedWithCustomError(pool, "InsufficientLiquidity");
});
});
describe("#repay", async function () {
beforeEach("setup liquidity and borrow", async function () {
await setupLiquidity();
});
it("repays bundle loan at maturity", async function () {
const mintTx = await bundleCollateralWrapper.connect(accountBorrower).mint(await nft1.getAddress(), [124, 125]);
const bundleTokenId = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.tokenId;
const bundleData = (await extractEvent(mintTx, bundleCollateralWrapper, "BundleMinted")).args.encodedBundle;
expect(await bundleCollateralWrapper.ownerOf(bundleTokenId)).to.equal(await accountBorrower.getAddress());
/* Quote repayment */
const repayment = await pool.quote(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
await sourceLiquidity(FixedPoint.from("25")),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
const borrowTx = await pool
.connect(accountBorrower)
.borrow(
FixedPoint.from("25"),
30 * 86400,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
repayment,
await sourceLiquidity(FixedPoint.from("25"), 2n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
expect(await bundleCollateralWrapper.ownerOf(bundleTokenId)).to.equal(await pool.getAddress());
const bundleLoanReceipt = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceipt;
const bundleLoanReceiptHash = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceiptHash;
/* Get decoded receipt */
const decodedLoanReceipt = await loanReceiptLib.decode(bundleLoanReceipt);
/* Repay */
await helpers.time.setNextBlockTimestamp(decodedLoanReceipt.maturity);
const repayTx = await pool.connect(accountBorrower).repay(bundleLoanReceipt);
/* Validate events */
await expectEvent(repayTx, tok1, "Transfer", {
from: await accountBorrower.getAddress(),
to: await pool.getAddress(),
value: decodedLoanReceipt.repayment,
});
await expectEvent(repayTx, bundleCollateralWrapper, "Transfer", {
from: await pool.getAddress(),
to: await accountBorrower.getAddress(),
tokenId: bundleTokenId,
});
await expectEvent(repayTx, pool, "LoanRepaid", {
loanReceiptHash: bundleLoanReceiptHash,
repayment: decodedLoanReceipt.repayment,
});
/* Validate state */
expect(await pool.loans(bundleLoanReceiptHash)).to.equal(2);
/* Validate ticks */
let totalDelta = 0n;
for (const nodeReceipt of decodedLoanReceipt.nodeReceipts) {
const delta = nodeReceipt.pending - nodeReceipt.used;
const node = await pool.liquidityNode(nodeReceipt.tick);
expect(node.value).to.equal(FixedPoint.from("25") + delta);
expect(node.available).to.equal(FixedPoint.from("25") + delta);
expect(node.pending).to.equal(0n);
totalDelta = totalDelta + delta;
}
expect(await bundleCollateralWrapper.ownerOf(bundleTokenId)).to.equal(await accountBorrower.getAddress());
});
});
describe("#refinance", async function () {
let loanReceipt: string;
let loanReceiptHash: string;
let bundleTokenId: bigint;
let bundleData: string;
beforeEach("setup liquidity", async function () {
await setupLiquidity();
});
it("refinance bundle loan at maturity with admin fee and same principal", async function () {
/* Set Admin Fee */
await pool.setAdminFee(500, accounts[2].address, 500);
/* Create Loan */
[loanReceipt, loanReceiptHash, bundleTokenId] = await createActiveBundleLoan(FixedPoint.from("25"));
/* Get decoded receipt */
const decodedLoanReceipt = await loanReceiptLib.decode(loanReceipt);
/* Refinance */
await helpers.time.setNextBlockTimestamp(decodedLoanReceipt.maturity);
const refinanceTx = await pool
.connect(accountBorrower)
.refinance(
loanReceipt,
decodedLoanReceipt.principal,
15 * 86400,
FixedPoint.from("26"),
await sourceLiquidity(FixedPoint.from("25")),
"0x"
);
const newLoanReceipt = (await extractEvent(refinanceTx, pool, "LoanOriginated")).args.loanReceipt;
const newLoanReceiptHash = (await extractEvent(refinanceTx, pool, "LoanOriginated")).args.loanReceiptHash;
/* Calculate admin fee */
const adminFee =
(BigInt(await pool.adminFeeRate()) * (decodedLoanReceipt.repayment - FixedPoint.from("25"))) / 10000n;
/* Validate hash */
expect(loanReceiptHash).to.equal(await loanReceiptLib.hash(loanReceipt));
/* Validate loan receipt */
const decodedNewLoanReceipt = await loanReceiptLib.decode(newLoanReceipt);
expect(decodedNewLoanReceipt.version).to.equal(2);
expect(decodedNewLoanReceipt.borrower).to.equal(await accountBorrower.getAddress());
expect(decodedNewLoanReceipt.maturity).to.equal(
BigInt((await ethers.provider.getBlock(refinanceTx.blockHash!)).timestamp) + 15n * 86400n
);
expect(decodedNewLoanReceipt.duration).to.equal(15 * 86400);
expect(decodedNewLoanReceipt.collateralToken).to.equal(await bundleCollateralWrapper.getAddress());
expect(decodedNewLoanReceipt.collateralTokenId).to.equal(bundleTokenId);
expect(decodedNewLoanReceipt.nodeReceipts.length).to.equal(4);
/* Validate events */
await expectEvent(refinanceTx, tok1, "Transfer", {
from: await accountBorrower.getAddress(),
to: await pool.getAddress(),
value: decodedLoanReceipt.repayment - decodedLoanReceipt.principal,
});
await expectEvent(refinanceTx, pool, "LoanRepaid", {
loanReceiptHash,
repayment: decodedLoanReceipt.repayment,
});
await expect(refinanceTx).to.emit(pool, "LoanOriginated");
/* Validate state */
expect(await pool.loans(loanReceiptHash)).to.equal(2);
expect(await pool.loans(newLoanReceiptHash)).to.equal(1);
expect(await pool.adminFeeBalance()).to.closeTo((adminFee * 9500n) / 10000n, "1");
});
it("bundle loan fails on refinance and refinance in same block with same loan receipt fields", async function () {
/* Set Admin Fee */
await pool.setAdminFee(500, accounts[2].address, 500);
/* Create Loan */
[loanReceipt, loanReceiptHash, bundleTokenId] = await createActiveBundleLoan(FixedPoint.from("25"));
/* Validate inability to do both refinance() and refinance() with the same loan receipt fields */
await expect(
pool
.connect(accountBorrower)
.multicall([
pool.interface.encodeFunctionData("refinance", [
loanReceipt,
FixedPoint.from("25"),
1,
FixedPoint.from("26"),
await sourceLiquidity(FixedPoint.from("25")),
"0x",
]),
pool.interface.encodeFunctionData("refinance", [
loanReceipt,
FixedPoint.from("25"),
1,
FixedPoint.from("26"),
await sourceLiquidity(FixedPoint.from("25")),
"0x",
]),
])
).to.be.revertedWithCustomError(pool, "InvalidLoanReceipt");
});
it("bundle loan fails on borrow and refinance in same block with same loan receipt fields", async function () {
/* setup liquidity and borrow */
await setupLiquidity();
[loanReceipt, loanReceiptHash, bundleTokenId, bundleData] = await createActiveBundleLoan(FixedPoint.from("25"));
/* Workaround to skip borrow() in beforeEach */
await pool.connect(accountBorrower).repay(loanReceipt);
/* Borrow to get loan receipt object */
const borrowTx = await pool
.connect(accountBorrower)
.borrow(
FixedPoint.from("1"),
1,
await bundleCollateralWrapper.getAddress(),
bundleTokenId,
FixedPoint.from("2"),
await sourceLiquidity(FixedPoint.from("1"), 3n),
ethers.solidityPacked(["uint16", "uint16", "bytes"], [1, ethers.dataLength(bundleData), bundleData])
);
let encodedLoanReceipt = (await extractEvent(borrowTx, pool, "LoanOriginated")).args.loanReceipt;
await pool.connect(accountBorrower).repay(encodedLoanReceipt);
/* Use existing loan receipt with the parameters we want */
const decodedExistingLoanReceipt = await loanReceiptLib.decode(encodedLoanReceipt);
/* Mutate NFT address in loan receipt and encode it */
const nodeReceipt = {
version: decodedExistingLoanReceipt.version,
principal: decodedExistingLoanReceipt.principal,
repayment: decodedExistingLoanReceipt.repayment,
adminFee: decodedExistingLoanReceipt.adminFee,
borrower: decodedExistingLoanReceipt.borrower,
maturity: BigInt("10000000001"),
duration: decodedExistingLoanReceipt.duration,
collateralToken: decodedExistingLoanReceipt.collateralToken,
collateralTokenId: decodedExistingLoanReceipt.collateralTokenId,
collateralWrapperContextLen: decodedExistingLoanReceipt.collateralWrapperContextLen,
collateralWrapperContext: decodedExistingLoanReceipt.collateralWrapperContext,