This repository has been archived by the owner on Oct 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCollateralManager.sol
552 lines (513 loc) · 19.3 KB
/
CollateralManager.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
pragma solidity >=0.8.0 <0.9.0;
// SPDX-License-Identifier: MIT
// Contracts
import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
// Libraries
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
// Interfaces
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "./interfaces/ICollateralManager.sol";
import { Collateral, CollateralType, ICollateralEscrowV1 } from "./interfaces/escrow/ICollateralEscrowV1.sol";
import "./interfaces/ITellerV2.sol";
contract CollateralManager is OwnableUpgradeable, ICollateralManager {
/* Storage */
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
ITellerV2 public tellerV2;
address private collateralEscrowBeacon; // The address of the escrow contract beacon
mapping(uint256 => address) public _escrows; // bidIds -> collateralEscrow
// bidIds -> validated collateral info
mapping(uint256 => CollateralInfo) internal _bidCollaterals;
/**
* Since collateralInfo is mapped (address assetAddress => Collateral) that means
* that only a single tokenId per nft per loan can be collateralized.
* Ex. Two bored apes cannot be used as collateral for a single loan.
*/
struct CollateralInfo {
EnumerableSetUpgradeable.AddressSet collateralAddresses;
mapping(address => Collateral) collateralInfo;
}
/* Events */
event CollateralEscrowDeployed(uint256 _bidId, address _collateralEscrow);
event CollateralCommitted(
uint256 _bidId,
CollateralType _type,
address _collateralAddress,
uint256 _amount,
uint256 _tokenId
);
event CollateralClaimed(uint256 _bidId);
event CollateralDeposited(
uint256 _bidId,
CollateralType _type,
address _collateralAddress,
uint256 _amount,
uint256 _tokenId
);
event CollateralWithdrawn(
uint256 _bidId,
CollateralType _type,
address _collateralAddress,
uint256 _amount,
uint256 _tokenId,
address _recipient
);
/* Modifiers */
modifier onlyTellerV2() {
require(_msgSender() == address(tellerV2), "Sender not authorized");
_;
}
/* External Functions */
/**
* @notice Initializes the collateral manager.
* @param _collateralEscrowBeacon The address of the escrow implementation.
* @param _tellerV2 The address of the protocol.
*/
function initialize(address _collateralEscrowBeacon, address _tellerV2)
external
initializer
{
collateralEscrowBeacon = _collateralEscrowBeacon;
tellerV2 = ITellerV2(_tellerV2);
__Ownable_init_unchained();
}
/**
* @notice Sets the address of the Beacon contract used for the collateral escrow contracts.
* @param _collateralEscrowBeacon The address of the Beacon contract.
*/
function setCollateralEscrowBeacon(address _collateralEscrowBeacon)
external
reinitializer(2)
{
collateralEscrowBeacon = _collateralEscrowBeacon;
}
/**
* @notice Checks to see if a bid is backed by collateral.
* @param _bidId The id of the bid to check.
*/
function isBidCollateralBacked(uint256 _bidId)
public
virtual
returns (bool)
{
return _bidCollaterals[_bidId].collateralAddresses.length() > 0;
}
/**
* @notice Checks the validity of a borrower's multiple collateral balances and commits it to a bid.
* @param _bidId The id of the associated bid.
* @param _collateralInfo Additional information about the collateral assets.
* @return validation_ Boolean indicating if the collateral balances were validated.
*/
function commitCollateral(
uint256 _bidId,
Collateral[] calldata _collateralInfo
) public returns (bool validation_) {
address borrower = tellerV2.getLoanBorrower(_bidId);
(validation_, ) = checkBalances(borrower, _collateralInfo);
if (validation_) {
for (uint256 i; i < _collateralInfo.length; i++) {
Collateral memory info = _collateralInfo[i];
_commitCollateral(_bidId, info);
}
}
}
/**
* @notice Checks the validity of a borrower's collateral balance and commits it to a bid.
* @param _bidId The id of the associated bid.
* @param _collateralInfo Additional information about the collateral asset.
* @return validation_ Boolean indicating if the collateral balance was validated.
*/
function commitCollateral(
uint256 _bidId,
Collateral calldata _collateralInfo
) public returns (bool validation_) {
address borrower = tellerV2.getLoanBorrower(_bidId);
validation_ = _checkBalance(borrower, _collateralInfo);
if (validation_) {
_commitCollateral(_bidId, _collateralInfo);
}
}
/**
* @notice Re-checks the validity of a borrower's collateral balance committed to a bid.
* @param _bidId The id of the associated bid.
* @return validation_ Boolean indicating if the collateral balance was validated.
*/
function revalidateCollateral(uint256 _bidId)
external
returns (bool validation_)
{
Collateral[] memory collateralInfos = getCollateralInfo(_bidId);
address borrower = tellerV2.getLoanBorrower(_bidId);
(validation_, ) = _checkBalances(borrower, collateralInfos, true);
}
/**
* @notice Checks the validity of a borrower's multiple collateral balances.
* @param _borrowerAddress The address of the borrower holding the collateral.
* @param _collateralInfo Additional information about the collateral assets.
*/
function checkBalances(
address _borrowerAddress,
Collateral[] calldata _collateralInfo
) public returns (bool validated_, bool[] memory checks_) {
return _checkBalances(_borrowerAddress, _collateralInfo, false);
}
/**
* @notice Deploys a new collateral escrow and deposits collateral.
* @param _bidId The associated bidId of the collateral escrow.
*/
function deployAndDeposit(uint256 _bidId) external onlyTellerV2 {
if (isBidCollateralBacked(_bidId)) {
(address proxyAddress, ) = _deployEscrow(_bidId);
_escrows[_bidId] = proxyAddress;
for (
uint256 i;
i < _bidCollaterals[_bidId].collateralAddresses.length();
i++
) {
_deposit(
_bidId,
_bidCollaterals[_bidId].collateralInfo[
_bidCollaterals[_bidId].collateralAddresses.at(i)
]
);
}
emit CollateralEscrowDeployed(_bidId, proxyAddress);
}
}
/**
* @notice Gets the address of a deployed escrow.
* @notice _bidId The bidId to return the escrow for.
* @return The address of the escrow.
*/
function getEscrow(uint256 _bidId) external view returns (address) {
return _escrows[_bidId];
}
/**
* @notice Gets the collateral info for a given bid id.
* @param _bidId The bidId to return the collateral info for.
* @return infos_ The stored collateral info.
*/
function getCollateralInfo(uint256 _bidId)
public
view
returns (Collateral[] memory infos_)
{
CollateralInfo storage collateral = _bidCollaterals[_bidId];
address[] memory collateralAddresses = collateral
.collateralAddresses
.values();
infos_ = new Collateral[](collateralAddresses.length);
for (uint256 i; i < collateralAddresses.length; i++) {
infos_[i] = collateral.collateralInfo[collateralAddresses[i]];
}
}
/**
* @notice Gets the collateral asset amount for a given bid id on the TellerV2 contract.
* @param _bidId The ID of a bid on TellerV2.
* @param _collateralAddress An address used as collateral.
* @return amount_ The amount of collateral of type _collateralAddress.
*/
function getCollateralAmount(uint256 _bidId, address _collateralAddress)
public
view
returns (uint256 amount_)
{
amount_ = _bidCollaterals[_bidId]
.collateralInfo[_collateralAddress]
._amount;
}
/**
* @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.
* @param _bidId The id of the bid to withdraw collateral for.
*/
function withdraw(uint256 _bidId) external {
BidState bidState = tellerV2.getBidState(_bidId);
if (bidState == BidState.PAID) {
_withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));
} else if (tellerV2.isLoanDefaulted(_bidId)) {
_withdraw(_bidId, tellerV2.getLoanLender(_bidId));
emit CollateralClaimed(_bidId);
} else {
revert("collateral cannot be withdrawn");
}
}
/**
* @notice Sends the deposited collateral to a liquidator of a bid.
* @notice Can only be called by the protocol.
* @param _bidId The id of the liquidated bid.
* @param _liquidatorAddress The address of the liquidator to send the collateral to.
*/
function liquidateCollateral(uint256 _bidId, address _liquidatorAddress)
external
onlyTellerV2
{
if (isBidCollateralBacked(_bidId)) {
BidState bidState = tellerV2.getBidState(_bidId);
require(
bidState == BidState.LIQUIDATED,
"Loan has not been liquidated"
);
_withdraw(_bidId, _liquidatorAddress);
}
}
/* Internal Functions */
/**
* @notice Deploys a new collateral escrow.
* @param _bidId The associated bidId of the collateral escrow.
*/
function _deployEscrow(uint256 _bidId)
internal
virtual
returns (address proxyAddress_, address borrower_)
{
proxyAddress_ = _escrows[_bidId];
// Get bid info
borrower_ = tellerV2.getLoanBorrower(_bidId);
if (proxyAddress_ == address(0)) {
require(borrower_ != address(0), "Bid does not exist");
BeaconProxy proxy = new BeaconProxy(
collateralEscrowBeacon,
abi.encodeWithSelector(
ICollateralEscrowV1.initialize.selector,
_bidId
)
);
proxyAddress_ = address(proxy);
}
}
/*
* @notice Deploys a new collateral escrow contract. Deposits collateral into a collateral escrow.
* @param _bidId The associated bidId of the collateral escrow.
* @param collateralInfo The collateral info to deposit.
*/
function _deposit(uint256 _bidId, Collateral memory collateralInfo)
internal
virtual
{
require(collateralInfo._amount > 0, "Collateral not validated");
(address escrowAddress, address borrower) = _deployEscrow(_bidId);
ICollateralEscrowV1 collateralEscrow = ICollateralEscrowV1(
escrowAddress
);
// Pull collateral from borrower & deposit into escrow
if (collateralInfo._collateralType == CollateralType.ERC20) {
IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom(
borrower,
address(this),
collateralInfo._amount
);
IERC20Upgradeable(collateralInfo._collateralAddress).approve(
escrowAddress,
collateralInfo._amount
);
collateralEscrow.depositAsset(
CollateralType.ERC20,
collateralInfo._collateralAddress,
collateralInfo._amount,
0
);
} else if (collateralInfo._collateralType == CollateralType.ERC721) {
IERC721Upgradeable(collateralInfo._collateralAddress).transferFrom(
borrower,
address(this),
collateralInfo._tokenId
);
IERC721Upgradeable(collateralInfo._collateralAddress).approve(
escrowAddress,
collateralInfo._tokenId
);
collateralEscrow.depositAsset(
CollateralType.ERC721,
collateralInfo._collateralAddress,
collateralInfo._amount,
collateralInfo._tokenId
);
} else if (collateralInfo._collateralType == CollateralType.ERC1155) {
bytes memory data;
IERC1155Upgradeable(collateralInfo._collateralAddress)
.safeTransferFrom(
borrower,
address(this),
collateralInfo._tokenId,
collateralInfo._amount,
data
);
IERC1155Upgradeable(collateralInfo._collateralAddress)
.setApprovalForAll(escrowAddress, true);
collateralEscrow.depositAsset(
CollateralType.ERC1155,
collateralInfo._collateralAddress,
collateralInfo._amount,
collateralInfo._tokenId
);
} else {
revert("Unexpected collateral type");
}
emit CollateralDeposited(
_bidId,
collateralInfo._collateralType,
collateralInfo._collateralAddress,
collateralInfo._amount,
collateralInfo._tokenId
);
}
/**
* @notice Withdraws collateral to a given receiver's address.
* @param _bidId The id of the bid to withdraw collateral for.
* @param _receiver The address to withdraw the collateral to.
*/
function _withdraw(uint256 _bidId, address _receiver) internal virtual {
for (
uint256 i;
i < _bidCollaterals[_bidId].collateralAddresses.length();
i++
) {
// Get collateral info
Collateral storage collateralInfo = _bidCollaterals[_bidId]
.collateralInfo[
_bidCollaterals[_bidId].collateralAddresses.at(i)
];
// Withdraw collateral from escrow and send it to bid lender
ICollateralEscrowV1(_escrows[_bidId]).withdraw(
collateralInfo._collateralAddress,
collateralInfo._amount,
_receiver
);
emit CollateralWithdrawn(
_bidId,
collateralInfo._collateralType,
collateralInfo._collateralAddress,
collateralInfo._amount,
collateralInfo._tokenId,
_receiver
);
}
}
/**
* @notice Checks the validity of a borrower's collateral balance and commits it to a bid.
* @param _bidId The id of the associated bid.
* @param _collateralInfo Additional information about the collateral asset.
*/
function _commitCollateral(
uint256 _bidId,
Collateral memory _collateralInfo
) internal virtual {
CollateralInfo storage collateral = _bidCollaterals[_bidId];
collateral.collateralAddresses.add(_collateralInfo._collateralAddress);
collateral.collateralInfo[
_collateralInfo._collateralAddress
] = _collateralInfo;
emit CollateralCommitted(
_bidId,
_collateralInfo._collateralType,
_collateralInfo._collateralAddress,
_collateralInfo._amount,
_collateralInfo._tokenId
);
}
/**
* @notice Checks the validity of a borrower's multiple collateral balances.
* @param _borrowerAddress The address of the borrower holding the collateral.
* @param _collateralInfo Additional information about the collateral assets.
* @param _shortCircut if true, will return immediately until an invalid balance
*/
function _checkBalances(
address _borrowerAddress,
Collateral[] memory _collateralInfo,
bool _shortCircut
) internal virtual returns (bool validated_, bool[] memory checks_) {
checks_ = new bool[](_collateralInfo.length);
validated_ = true;
for (uint256 i; i < _collateralInfo.length; i++) {
bool isValidated = _checkBalance(
_borrowerAddress,
_collateralInfo[i]
);
checks_[i] = isValidated;
if (!isValidated) {
validated_ = false;
if (_shortCircut) {
return (validated_, checks_);
}
}
}
}
/**
* @notice Checks the validity of a borrower's single collateral balance.
* @param _borrowerAddress The address of the borrower holding the collateral.
* @param _collateralInfo Additional information about the collateral asset.
* @return validation_ Boolean indicating if the collateral balances were validated.
*/
function _checkBalance(
address _borrowerAddress,
Collateral memory _collateralInfo
) internal virtual returns (bool) {
CollateralType collateralType = _collateralInfo._collateralType;
if (collateralType == CollateralType.ERC20) {
return
_collateralInfo._amount <=
IERC20Upgradeable(_collateralInfo._collateralAddress).balanceOf(
_borrowerAddress
);
} else if (collateralType == CollateralType.ERC721) {
return
_borrowerAddress ==
IERC721Upgradeable(_collateralInfo._collateralAddress).ownerOf(
_collateralInfo._tokenId
);
} else if (collateralType == CollateralType.ERC1155) {
return
_collateralInfo._amount <=
IERC1155Upgradeable(_collateralInfo._collateralAddress)
.balanceOf(_borrowerAddress, _collateralInfo._tokenId);
} else {
return false;
}
}
// On NFT Received handlers
function onERC721Received(address, address, uint256, bytes calldata)
external
pure
returns (bytes4)
{
return
bytes4(
keccak256("onERC721Received(address,address,uint256,bytes)")
);
}
function onERC1155Received(
address,
address,
uint256 id,
uint256 value,
bytes calldata
) external returns (bytes4) {
return
bytes4(
keccak256(
"onERC1155Received(address,address,uint256,uint256,bytes)"
)
);
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata
) external returns (bytes4) {
require(
_ids.length == 1,
"Only allowed one asset batch transfer per transaction."
);
return
bytes4(
keccak256(
"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"
)
);
}
}