/
OriginationController.sol
873 lines (761 loc) · 37.1 KB
/
OriginationController.sol
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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/interfaces/IERC1271.sol";
import "./interfaces/IOriginationController.sol";
import "./interfaces/ILoanCore.sol";
import "./interfaces/IERC721Permit.sol";
import "./interfaces/IAssetVault.sol";
import "./interfaces/IVaultFactory.sol";
import "./interfaces/ISignatureVerifier.sol";
import "./InstallmentsCalc.sol";
import "./verifiers/ItemsVerifier.sol";
import {
OC_ZeroAddress,
OC_InvalidState,
OC_InvalidVerifier,
OC_BatchLengthMismatch,
OC_PredicateFailed,
OC_PredicatesArrayEmpty,
OC_SelfApprove,
OC_ApprovedOwnLoan,
OC_InvalidSignature,
OC_CallerNotParticipant,
OC_PrincipalTooLow,
OC_LoanDuration,
OC_InterestRate,
OC_NumberInstallments,
OC_SignatureIsExpired,
OC_RolloverCurrencyMismatch,
OC_RolloverCollateralMismatch
} from "./errors/Lending.sol";
/**
* @title OriginationController
* @author Non-Fungible Technologies, Inc.
*
* The Origination Controller is the entry point for all new loans
* in the Arcade.xyz lending protocol. This contract has the exclusive
* responsibility of creating new loans in LoanCore. All permissioning,
* signature verification, and collateral verification takes place in
* this contract. To originate a loan, the controller also takes custody
* of both the collateral and loan principal.
*/
contract OriginationController is
Initializable,
InstallmentsCalc,
ContextUpgradeable,
IOriginationController,
EIP712Upgradeable,
ReentrancyGuardUpgradeable,
AccessControlEnumerableUpgradeable,
UUPSUpgradeable
{
using SafeERC20Upgradeable for IERC20Upgradeable;
// ============================================ STATE ==============================================
// =================== Constants =====================
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/// @notice EIP712 type hash for bundle-based signatures.
bytes32 private constant _TOKEN_ID_TYPEHASH =
keccak256(
// solhint-disable-next-line max-line-length
"LoanTerms(uint32 durationSecs,uint32 deadline,uint24 numInstallments,uint160 interestRate,uint256 principal,address collateralAddress,uint256 collateralId,address payableCurrency,uint160 nonce,uint8 side)"
);
/// @notice EIP712 type hash for item-based signatures.
bytes32 private constant _ITEMS_TYPEHASH =
keccak256(
// solhint-disable max-line-length
"LoanTermsWithItems(uint32 durationSecs,uint32 deadline,uint24 numInstallments,uint160 interestRate,uint256 principal,address collateralAddress,bytes32 itemsHash,address payableCurrency,uint160 nonce,uint8 side)"
);
// =============== Contract References ===============
address public loanCore;
// ================= Approval State ==================
/// @notice Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _signerApprovals;
/// @notice Mapping from address to whether that verifier contract has been whitelisted
mapping(address => bool) public allowedVerifiers;
// ========================================== CONSTRUCTOR ===========================================
/**
* @notice Runs the initializer function in an upgradeable contract.
*
* @dev Add Unsafe-allow comment to notify upgrades plugin to accept the constructor.
*/
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
// ========================================== INITIALIZER ===========================================
/**
* @notice Creates a new origination controller contract, also initializing
* the parent signature verifier.
*
* @dev For this controller to work, it needs to be granted the ORIGINATOR_ROLE
* in loan core after deployment.
*
* @param _loanCore The address of the loan core logic of the protocol.
*/
function initialize(address _loanCore) public initializer {
__EIP712_init("OriginationController", "2");
__AccessControlEnumerable_init_unchained();
__UUPSUpgradeable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(ADMIN_ROLE, _msgSender());
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
if (_loanCore == address(0)) revert OC_ZeroAddress();
loanCore = _loanCore;
}
// ======================================= UPGRADE AUTHORIZATION ========================================
/**
* @notice Authorization function to define who should be allowed to upgrade the contract
*
* @param newImplementation The address of the upgraded verion of this contract
*/
function _authorizeUpgrade(address newImplementation) internal override onlyRole(ADMIN_ROLE) {}
// ==================================== ORIGINATION OPERATIONS ======================================
/**
* @notice Initializes a loan with Loan Core.
* @notice Works with either wrapped bundles with an ID, or specific ERC721 unwrapped NFTs.
* In that case, collateralAddress should be the token contract.
*
* @dev The caller must be a borrower or lender, or approved by a borrower or lender.
* @dev The external signer must be a borrower or lender, or approved by a borrower or lender.
* @dev The external signer must come from the opposite side of the loan as the caller.
*
* @param loanTerms The terms agreed by the lender and borrower.
* @param borrower Address of the borrower.
* @param lender Address of the lender.
* @param sig The loan terms signature, with v, r, s fields, and a nonce.
* @param nonce The signature nonce.
*
* @return loanId The unique ID of the new loan.
*/
function initializeLoan(
LoanLibrary.LoanTerms calldata loanTerms,
address borrower,
address lender,
Signature calldata sig,
uint160 nonce
) public override returns (uint256 loanId) {
_validateLoanTerms(loanTerms);
// Determine if signature needs to be on the borrow or lend side
Side neededSide = isSelfOrApproved(borrower, _msgSender()) ? Side.LEND : Side.BORROW;
(bytes32 sighash, address externalSigner) = recoverTokenSignature(loanTerms, sig, nonce, neededSide);
_validateCounterparties(borrower, lender, msg.sender, externalSigner, sig, sighash, neededSide);
ILoanCore(loanCore).consumeNonce(externalSigner, nonce);
loanId = _initialize(loanTerms, borrower, lender);
}
/**
* @notice Initializes a loan with Loan Core.
* @notice Compared to initializeLoan, this verifies the specific items in a bundle.
* @notice Only works with bundles implementing the IVaultFactory interface.
*
* @dev The caller must be a borrower or lender, or approved by a borrower or lender.
* @dev The external signer must be a borrower or lender, or approved by a borrower or lender.
* @dev The external signer must come from the opposite side of the loan as the caller.
*
* @param loanTerms The terms agreed by the lender and borrower.
* @param borrower Address of the borrower.
* @param lender Address of the lender.
* @param sig The loan terms signature, with v, r, s fields, and a nonce.
* @param nonce The signature nonce.
* @param itemPredicates The predicate rules for the items in the bundle.
*
* @return loanId The unique ID of the new loan.
*/
function initializeLoanWithItems(
LoanLibrary.LoanTerms calldata loanTerms,
address borrower,
address lender,
Signature calldata sig,
uint160 nonce,
LoanLibrary.Predicate[] calldata itemPredicates
) public override returns (uint256 loanId) {
_validateLoanTerms(loanTerms);
// Determine if signature needs to be on the borrow or lend side
Side neededSide = isSelfOrApproved(borrower, _msgSender()) ? Side.LEND : Side.BORROW;
address vault = IVaultFactory(loanTerms.collateralAddress).instanceAt(loanTerms.collateralId);
(bytes32 sighash, address externalSigner) = recoverItemsSignature(
loanTerms,
sig,
nonce,
neededSide,
keccak256(abi.encode(itemPredicates))
);
_validateCounterparties(borrower, lender, msg.sender, externalSigner, sig, sighash, neededSide);
if (itemPredicates.length == 0) {
revert OC_PredicatesArrayEmpty();
}
for (uint256 i = 0; i < itemPredicates.length; i++) {
// Verify items are held in the wrapper
address verifier = itemPredicates[i].verifier;
if (!isAllowedVerifier(verifier)) revert OC_InvalidVerifier(verifier);
if (!ISignatureVerifier(verifier).verifyPredicates(itemPredicates[i].data, vault)) {
revert OC_PredicateFailed(verifier, itemPredicates[i].data, vault);
}
}
ILoanCore(loanCore).consumeNonce(externalSigner, nonce);
loanId = _initialize(loanTerms, borrower, lender);
}
/**
* @notice Initializes a loan with Loan Core, with a permit signature instead of pre-approved collateral.
*
* @dev The caller must be a borrower or lender, or approved by a borrower or lender.
* @dev The external signer must be a borrower or lender, or approved by a borrower or lender.
* @dev The external signer must come from the opposite side of the loan as the caller.
*
* @param loanTerms The terms agreed by the lender and borrower.
* @param borrower Address of the borrower.
* @param lender Address of the lender.
* @param sig The loan terms signature, with v, r, s fields.
* @param nonce The signature nonce for the loan terms signature.
* @param collateralSig The collateral permit signature, with v, r, s fields.
* @param permitDeadline The last timestamp for which the signature is valid.
*
* @return loanId The unique ID of the new loan.
*/
function initializeLoanWithCollateralPermit(
LoanLibrary.LoanTerms calldata loanTerms,
address borrower,
address lender,
Signature calldata sig,
uint160 nonce,
Signature calldata collateralSig,
uint256 permitDeadline
) external override returns (uint256 loanId) {
IERC721Permit(loanTerms.collateralAddress).permit(
borrower,
address(this),
loanTerms.collateralId,
permitDeadline,
collateralSig.v,
collateralSig.r,
collateralSig.s
);
loanId = initializeLoan(loanTerms, borrower, lender, sig, nonce);
}
/**
* @notice Initializes a loan with Loan Core, with a permit signature instead of pre-approved collateral.
* @notice Compared to initializeLoanWithCollateralPermit, this verifies the specific items in a bundle.
*
* @dev The caller must be a borrower or lender, or approved by a borrower or lender.
* @dev The external signer must be a borrower or lender, or approved by a borrower or lender.
* @dev The external signer must come from the opposite side of the loan as the caller.
*
* @param loanTerms The terms agreed by the lender and borrower.
* @param borrower Address of the borrower.
* @param lender Address of the lender.
* @param sig The loan terms signature, with v, r, s fields.
* @param nonce The signature nonce for the loan terms signature.
* @param collateralSig The collateral permit signature, with v, r, s fields.
* @param permitDeadline The last timestamp for which the signature is valid.
* @param itemPredicates The predicate rules for the items in the bundle.
*
* @return loanId The unique ID of the new loan.
*/
function initializeLoanWithCollateralPermitAndItems(
LoanLibrary.LoanTerms calldata loanTerms,
address borrower,
address lender,
Signature calldata sig,
uint160 nonce,
Signature calldata collateralSig,
uint256 permitDeadline,
LoanLibrary.Predicate[] calldata itemPredicates
) external override returns (uint256 loanId) {
IERC721Permit(loanTerms.collateralAddress).permit(
borrower,
address(this),
loanTerms.collateralId,
permitDeadline,
collateralSig.v,
collateralSig.r,
collateralSig.s
);
loanId = initializeLoanWithItems(loanTerms, borrower, lender, sig, nonce, itemPredicates);
}
/**
* @notice Rolls over an existing loan via Loan Core, using a signature for
* a new loan to be created. The lender can be the same lender as the
* loan to be rolled over, or a new lender. The net funding between the
* old and new loan is calculated, with funds withdrawn from relevant
* parties.
*
* @param oldLoanId The ID of the old loan.
* @param loanTerms The terms agreed by the lender and borrower.
* @param lender Address of the lender.
* @param sig The loan terms signature, with v, r, s fields.
* @param nonce The signature nonce for the loan terms signature.
*
* @return newLoanId The unique ID of the new loan.
*/
function rolloverLoan(
uint256 oldLoanId,
LoanLibrary.LoanTerms calldata loanTerms,
address lender,
Signature calldata sig,
uint160 nonce
) public override returns (uint256 newLoanId) {
_validateLoanTerms(loanTerms);
LoanLibrary.LoanData memory data = ILoanCore(loanCore).getLoan(oldLoanId);
if (data.state != LoanLibrary.LoanState.Active) revert OC_InvalidState(data.state);
address borrower = IERC721(ILoanCore(loanCore).borrowerNote()).ownerOf(oldLoanId);
// Determine if signature needs to be on the borrow or lend side
Side neededSide = isSelfOrApproved(borrower, _msgSender()) ? Side.LEND : Side.BORROW;
_validateRollover(data.terms, loanTerms);
(bytes32 sighash, address externalSigner) = recoverTokenSignature(loanTerms, sig, nonce, neededSide);
_validateCounterparties(borrower, lender, msg.sender, externalSigner, sig, sighash, neededSide);
ILoanCore(loanCore).consumeNonce(externalSigner, nonce);
newLoanId = _rollover(oldLoanId, loanTerms, borrower, lender);
}
/**
* @notice Rolls over an existing loan via Loan Core, using a signature
* for a new loan to create (of items type). The lender can be the same lender
* in the loan to be rolled over, or a new lender. The net funding between
* the old and new loan is calculated, with funds withdrawn from relevant
* parties.
*
* @param oldLoanId The ID of the old loan.
* @param loanTerms The terms agreed by the lender and borrower.
* @param lender Address of the lender.
* @param sig The loan terms signature, with v, r, s fields.
* @param nonce The signature nonce for the loan terms signature.
* @param itemPredicates The predicate rules for the items in the bundle.
*
* @return newLoanId The unique ID of the new loan.
*/
function rolloverLoanWithItems(
uint256 oldLoanId,
LoanLibrary.LoanTerms calldata loanTerms,
address lender,
Signature calldata sig,
uint160 nonce,
LoanLibrary.Predicate[] calldata itemPredicates
) public override returns (uint256 newLoanId) {
_validateLoanTerms(loanTerms);
LoanLibrary.LoanData memory data = ILoanCore(loanCore).getLoan(oldLoanId);
_validateRollover(data.terms, loanTerms);
address borrower = IERC721(ILoanCore(loanCore).borrowerNote()).ownerOf(oldLoanId);
// Determine if signature needs to be on the borrow or lend side
Side neededSide = isSelfOrApproved(borrower, _msgSender()) ? Side.LEND : Side.BORROW;
address vault = IVaultFactory(loanTerms.collateralAddress).instanceAt(loanTerms.collateralId);
(bytes32 sighash, address externalSigner) = recoverItemsSignature(
loanTerms,
sig,
nonce,
neededSide,
keccak256(abi.encode(itemPredicates))
);
_validateCounterparties(borrower, lender, msg.sender, externalSigner, sig, sighash, neededSide);
if (itemPredicates.length == 0) {
revert OC_PredicatesArrayEmpty();
}
for (uint256 i = 0; i < itemPredicates.length; i++) {
// Verify items are held in the wrapper
address verifier = itemPredicates[i].verifier;
if (!isAllowedVerifier(verifier)) revert OC_InvalidVerifier(verifier);
if (!ISignatureVerifier(verifier).verifyPredicates(itemPredicates[i].data, vault)) {
revert OC_PredicateFailed(verifier, itemPredicates[i].data, vault);
}
}
ILoanCore(loanCore).consumeNonce(externalSigner, nonce);
newLoanId = _rollover(oldLoanId, loanTerms, borrower, lender);
}
// ==================================== PERMISSION MANAGEMENT =======================================
/**
* @notice Approve a third party to sign or initialize loans on a counterparty's behalf.
* @notice Useful to multisig counterparties (who cannot sign themselves) or third-party integrations.
*
* @param signer The party to set approval for.
* @param approved Whether the party should be approved.
*/
function approve(address signer, bool approved) public override {
if (signer == msg.sender) revert OC_SelfApprove(msg.sender);
_signerApprovals[msg.sender][signer] = approved;
emit Approval(msg.sender, signer, approved);
}
/**
* @notice Reports whether a party is approved to act on a counterparty's behalf.
*
* @param owner The grantor of permission.
* @param signer The grantee of permission.
*
* @return isApproved Whether the grantee has been approved by the grantor.
*/
function isApproved(address owner, address signer) public view virtual override returns (bool) {
return _signerApprovals[owner][signer];
}
/**
* @notice Reports whether the signer matches the target or is approved by the target.
*
* @param target The grantor of permission - should be a smart contract.
* @param sig A struct containing the signature data (for checking EIP-1271).
* @param sighash The hash of the signature payload (used for EIP-1271 check).
*
* @return isApprovedForContract Whether the signer is either the grantor themselves, or approved.
*/
function isApprovedForContract(
address target,
Signature calldata sig,
bytes32 sighash
) public view override returns (bool) {
bytes memory signature = new bytes(65);
// Construct byte array directly in assembly for efficiency
uint8 v = sig.v;
bytes32 r = sig.r;
bytes32 s = sig.s;
assembly {
mstore(add(signature, 32), r)
mstore(add(signature, 64), s)
mstore(add(signature, 96), v)
}
// Convert sig struct to bytes
(bool success, bytes memory result) = target.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, sighash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
/**
* @notice Reports whether the signer matches the target or is approved by the target.
*
* @param target The grantor of permission.
* @param signer The grantee of permission.
*
* @return isSelfOrApproved Whether the signer is either the grantor themselves, or approved.
*/
function isSelfOrApproved(address target, address signer) public view override returns (bool) {
return target == signer || isApproved(target, signer);
}
// ==================================== SIGNATURE VERIFICATION ======================================
/**
* @notice Determine the external signer for a signature specifying only a collateral address and ID.
*
* @param loanTerms The terms of the loan.
* @param sig The signature, with v, r, s fields.
* @param nonce The signature nonce.
* @param side The side of the loan being signed.
*
* @return sighash The hash that was signed.
* @return signer The address of the recovered signer.
*/
function recoverTokenSignature(
LoanLibrary.LoanTerms calldata loanTerms,
Signature calldata sig,
uint160 nonce,
Side side
) public view override returns (bytes32 sighash, address signer) {
bytes32 loanHash = keccak256(
abi.encode(
_TOKEN_ID_TYPEHASH,
loanTerms.durationSecs,
loanTerms.deadline,
loanTerms.numInstallments,
loanTerms.interestRate,
loanTerms.principal,
loanTerms.collateralAddress,
loanTerms.collateralId,
loanTerms.payableCurrency,
nonce,
uint8(side)
)
);
sighash = _hashTypedDataV4(loanHash);
signer = ECDSA.recover(sighash, sig.v, sig.r, sig.s);
}
/**
* @notice Determine the external signer for a signature specifying specific items.
* @dev Bundle ID should _not_ be included in this signature, because the loan
* can be initiated with any arbitrary bundle - as long as the bundle contains the items.
*
* @param loanTerms The terms of the loan.
* @param sig The loan terms signature, with v, r, s fields.
* @param nonce The signature nonce.
* @param side The side of the loan being signed.
* @param itemsHash The required items in the specified bundle.
*
* @return sighash The hash that was signed.
* @return signer The address of the recovered signer.
*/
function recoverItemsSignature(
LoanLibrary.LoanTerms calldata loanTerms,
Signature calldata sig,
uint160 nonce,
Side side,
bytes32 itemsHash
) public view override returns (bytes32 sighash, address signer) {
bytes32 loanHash = keccak256(
abi.encode(
_ITEMS_TYPEHASH,
loanTerms.durationSecs,
loanTerms.deadline,
loanTerms.numInstallments,
loanTerms.interestRate,
loanTerms.principal,
loanTerms.collateralAddress,
itemsHash,
loanTerms.payableCurrency,
nonce,
uint8(side)
)
);
sighash = _hashTypedDataV4(loanHash);
signer = ECDSA.recover(sighash, sig.v, sig.r, sig.s);
}
// ==================================== VERIFICATION WHITELIST ======================================
/**
* @notice Manage whitelist for contracts that are allowed to act as a predicate verifier.
* Prevents counterparties from abusing misleading/obscure verification logic.
* The contract owner should take extra care in whitelisting third-party verification contracts:
* for instance, an upgradeable third-party verifier controlled by a borrower could be maliciously
* upgraded to approve an empty bundle.
*
* @param verifier The specified verifier contract, should implement ISignatureVerifier.
* @param isAllowed Whether the specified contract should be allowed.
*/
function setAllowedVerifier(address verifier, bool isAllowed) public override onlyRole(ADMIN_ROLE) {
if (verifier == address(0)) revert OC_ZeroAddress();
allowedVerifiers[verifier] = isAllowed;
emit SetAllowedVerifier(verifier, isAllowed);
}
/**
* @notice Batch update for verification whitelist, in case of multiple verifiers
* active in production.
*
* @param verifiers The list of specified verifier contracts, should implement ISignatureVerifier.
* @param isAllowed Whether the specified contracts should be allowed, respectively.
*/
function setAllowedVerifierBatch(address[] calldata verifiers, bool[] calldata isAllowed) external override {
if (verifiers.length != isAllowed.length) revert OC_BatchLengthMismatch();
for (uint256 i = 0; i < verifiers.length; i++) {
setAllowedVerifier(verifiers[i], isAllowed[i]);
}
}
/**
* @notice Return whether the address can be used as a verifier.
*
* @param verifier The verifier contract to query.
*
* @return isVerified Whether the contract is verified.
*/
function isAllowedVerifier(address verifier) public view override returns (bool) {
return allowedVerifiers[verifier];
}
// =========================================== HELPERS ==============================================
/**
* @dev Validates argument bounds for the loan terms.
*
* @param terms The terms of the loan.
*/
function _validateLoanTerms(LoanLibrary.LoanTerms memory terms) internal view {
// principal must be greater than or equal to 10000 wei
if (terms.principal < 10_000) revert OC_PrincipalTooLow(terms.principal);
// loan duration must be greater than 1 hr and less than 3 years
if (terms.durationSecs < 3600 || terms.durationSecs > 94_608_000) revert OC_LoanDuration(terms.durationSecs);
// interest rate must be greater than or equal to 0.01%
// and less than 10,000% (1e6 basis points)
if (terms.interestRate < 1e18 || terms.interestRate > 1e24) revert OC_InterestRate(terms.interestRate);
// number of installments must be either 0, or between 2 and 1000.
if (terms.numInstallments == 1 || terms.numInstallments > 1_000)
revert OC_NumberInstallments(terms.numInstallments);
// signature must not have already expired
if (terms.deadline < block.timestamp) revert OC_SignatureIsExpired(terms.deadline);
}
/**
* @dev Validate the rules for rolling over a loan - must be using the same
* currency and collateral.
*
* @param oldTerms The terms of the old loan, fetched from LoanCore.
* @param newTerms The terms of the new loan, provided by the caller.
*/
function _validateRollover(LoanLibrary.LoanTerms memory oldTerms, LoanLibrary.LoanTerms memory newTerms)
internal
pure
{
if (newTerms.payableCurrency != oldTerms.payableCurrency)
revert OC_RolloverCurrencyMismatch(oldTerms.payableCurrency, newTerms.payableCurrency);
if (newTerms.collateralAddress != oldTerms.collateralAddress || newTerms.collateralId != oldTerms.collateralId)
revert OC_RolloverCollateralMismatch(
oldTerms.collateralAddress,
oldTerms.collateralId,
newTerms.collateralAddress,
newTerms.collateralId
);
}
/**
* @dev Ensure that one counterparty has signed the loan terms, and the other
* has initiated the transaction.
*
* @param borrower The specified borrower for the loan.
* @param lender The specified lender for the loan.
* @param caller The address initiating the transaction.
* @param signer The address recovered from the loan terms signature.
* @param sig A struct containing the signature data (for checking EIP-1271).
* @param sighash The hash of the signature payload (used for EIP-1271 check).
* @param neededSide The side of the loan the signature will take (lend or borrow).
*/
function _validateCounterparties(
address borrower,
address lender,
address caller,
address signer,
Signature calldata sig,
bytes32 sighash,
Side neededSide
) internal view {
if (caller == signer) revert OC_ApprovedOwnLoan(caller);
address shouldBeSigner = neededSide == Side.LEND ? lender : borrower;
address shouldBeCaller = shouldBeSigner == lender ? borrower : lender;
if (!isSelfOrApproved(shouldBeCaller, caller) && !isApprovedForContract(shouldBeCaller, sig, sighash)) {
revert OC_CallerNotParticipant(msg.sender);
}
if (!isSelfOrApproved(shouldBeSigner, signer) && !isApprovedForContract(shouldBeSigner, sig, sighash)) {
revert OC_InvalidSignature(shouldBeSigner, signer);
}
}
/**
* @dev Perform loan initialization. Take custody of both principal and
* collateral, and tell LoanCore to create and start a loan.
*
* @param loanTerms The terms agreed by the lender and borrower.
* @param borrower Address of the borrower.
* @param lender Address of the lender.
*
* @return loanId The unique ID of the new loan.
*/
function _initialize(
LoanLibrary.LoanTerms calldata loanTerms,
address borrower,
address lender
) internal nonReentrant returns (uint256 loanId) {
// Take custody of funds
IERC20Upgradeable(loanTerms.payableCurrency).safeTransferFrom(lender, address(this), loanTerms.principal);
IERC20Upgradeable(loanTerms.payableCurrency).approve(loanCore, loanTerms.principal);
IERC721(loanTerms.collateralAddress).transferFrom(borrower, address(this), loanTerms.collateralId);
IERC721(loanTerms.collateralAddress).approve(loanCore, loanTerms.collateralId);
// Start loan
loanId = ILoanCore(loanCore).startLoan(lender, borrower, loanTerms);
}
/**
* @dev Perform loan rollover. Take custody of both principal and
* collateral, and tell LoanCore to roll over the existing loan.
*
* @param oldLoanId The ID of the loan to be rolled over.
* @param newTerms The terms agreed by the lender and borrower.
* @param borrower Address of the borrower.
* @param lender Address of the lender.
*
* @return loanId The unique ID of the new loan.
*/
function _rollover(
uint256 oldLoanId,
LoanLibrary.LoanTerms calldata newTerms,
address borrower,
address lender
) internal nonReentrant returns (uint256 loanId) {
LoanLibrary.LoanData memory oldLoanData = ILoanCore(loanCore).getLoan(oldLoanId);
LoanLibrary.LoanTerms memory oldTerms = oldLoanData.terms;
address oldLender = ILoanCore(loanCore).lenderNote().ownerOf(oldLoanId);
IERC20Upgradeable payableCurrency = IERC20Upgradeable(oldTerms.payableCurrency);
uint256 rolloverFee = ILoanCore(loanCore).feeController().getRolloverFee();
// Settle amounts
RolloverAmounts memory amounts = _calculateRolloverAmounts(
oldLoanData,
newTerms,
lender,
oldLender,
rolloverFee
);
// Collect funds
uint256 settledAmount;
if (lender != oldLender) {
// Take new principal from lender
// OriginationController should have collected
payableCurrency.safeTransferFrom(lender, address(this), newTerms.principal);
settledAmount += newTerms.principal;
}
if (amounts.needFromBorrower > 0) {
// Borrower must pay difference
// OriginationController should have collected
payableCurrency.safeTransferFrom(borrower, address(this), amounts.needFromBorrower);
settledAmount += amounts.needFromBorrower;
} else if (amounts.leftoverPrincipal > 0 && lender == oldLender) {
// Lender must pay difference
// OriginationController should have collected
// Make sure to collect fee
payableCurrency.safeTransferFrom(lender, address(this), amounts.leftoverPrincipal);
settledAmount += amounts.leftoverPrincipal;
}
{
payableCurrency.approve(loanCore, settledAmount);
loanId = ILoanCore(loanCore).rollover(
oldLoanId,
borrower,
lender,
newTerms,
settledAmount,
amounts.amountToOldLender,
amounts.amountToLender,
amounts.amountToBorrower
);
}
}
/**
* @dev Calculate the net amounts needed for the rollover from each party - the
* borrower, the new lender, and the old lender (can be same as new lender).
* Determine the amount to either pay or withdraw from the borrower, and
* any payments to be sent to the old lender.
*
* @param oldLoanData The LoanData struct for the old loan.
* @param newTerms The terms struct for the new loan.
* @param lender The lender for the new loan.
* @param oldLender The lender for the existing loan.
* @param rolloverFee The protocol fee for rollovers.
*
* @return amounts The net amounts owed to each party.
*/
function _calculateRolloverAmounts(
LoanLibrary.LoanData memory oldLoanData,
LoanLibrary.LoanTerms calldata newTerms,
address lender,
address oldLender,
uint256 rolloverFee
) internal view returns (RolloverAmounts memory amounts) {
LoanLibrary.LoanTerms memory oldTerms = oldLoanData.terms;
uint256 repayAmount;
if (oldTerms.numInstallments == 0) {
repayAmount = getFullInterestAmount(oldTerms.principal, oldTerms.interestRate);
} else {
(uint256 interestDue, uint256 lateFees, ) = _calcAmountsDue(
oldLoanData.balance,
oldLoanData.startDate,
oldTerms.durationSecs,
oldTerms.numInstallments,
oldLoanData.numInstallmentsPaid,
oldTerms.interestRate
);
repayAmount = oldLoanData.balance + interestDue + lateFees;
}
amounts.fee = (newTerms.principal * rolloverFee) / BASIS_POINTS_DENOMINATOR;
uint256 borrowerWillGet = newTerms.principal - amounts.fee;
// Settle amounts
if (repayAmount > borrowerWillGet) {
amounts.needFromBorrower = repayAmount - borrowerWillGet;
} else {
amounts.leftoverPrincipal = newTerms.principal - repayAmount;
amounts.amountToBorrower = amounts.leftoverPrincipal - amounts.fee;
}
// Collect funds
if (lender != oldLender) {
amounts.amountToOldLender = repayAmount;
amounts.amountToLender = 0;
} else {
amounts.amountToOldLender = 0;
if (amounts.needFromBorrower > 0 && repayAmount > newTerms.principal) {
amounts.amountToLender = repayAmount - newTerms.principal;
}
}
}
}