This repository has been archived by the owner on Sep 27, 2022. It is now read-only.
/
SharedLoan.sol
487 lines (413 loc) · 13.8 KB
/
SharedLoan.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
/*
Copyright 2018 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { Margin } from "../Margin.sol";
import { MathHelpers } from "../../lib/MathHelpers.sol";
import { ReentrancyGuard } from "../../lib/ReentrancyGuard.sol";
import { TokenInteract } from "../../lib/TokenInteract.sol";
import { MarginCommon } from "../impl/MarginCommon.sol";
import { OnlyMargin } from "../interfaces/OnlyMargin.sol";
/* solium-disable-next-line max-len*/
import { ForceRecoverCollateralDelegator } from "../interfaces/lender/ForceRecoverCollateralDelegator.sol";
import { IncreaseLoanDelegator } from "../interfaces/lender/IncreaseLoanDelegator.sol";
import { LoanOwner } from "../interfaces/lender/LoanOwner.sol";
import { MarginCallDelegator } from "../interfaces/lender/MarginCallDelegator.sol";
import { MarginHelper } from "./lib/MarginHelper.sol";
/**
* @title SharedLoan
* @author dYdX
*
* This contract is used to share loan positions. Multiple participants can share in a loan
* position, and will all be paid out proportional to ownership when the loan is repaid. Ownership
* is non-transferrable
*/
contract SharedLoan is
ReentrancyGuard,
OnlyMargin,
LoanOwner,
IncreaseLoanDelegator,
MarginCallDelegator,
ForceRecoverCollateralDelegator
{
using SafeMath for uint256;
// ============ Enums ============
enum State {
UNINITIALIZED,
OPEN,
CLOSED
}
// ============ Events ============
/**
* This SharedLoan was successfully initialized
*/
event Initialized(
bytes32 positionId,
uint256 initialAmount
);
/**
* Balance was added to the loan position
*/
event BalanceAdded(
address indexed who,
uint256 amount
);
/**
* Funds were withdrawn by a lender after the loan was partially or completely repaid
*/
event TokensWithdrawn(
address indexed who,
uint256 owedTokenAmount,
uint256 heldTokenAmount,
bool completelyRepaid
);
// ============ State Variables ============
// Initial lender of the position
address public INITIAL_LENDER;
// Unique ID of the position this contract is lending for
bytes32 public POSITION_ID;
// Addresses that can margin-call the position
mapping (address => bool) public TRUSTED_MARGIN_CALLERS;
// Current State of this contract. See State enum
State public state;
// Address of the position's owedToken. Cached for convenience and lower-cost withdrawals
address public owedToken;
// Address of the position's heldToken. Cached for convenience and lower-cost withdrawals
address public heldToken;
// Total principal
uint256 public totalPrincipal;
// Amount that has been fully repaid and withdrawn
uint256 public totalPrincipalFullyWithdrawn;
// Total amount of owedToken that has been withdrawn
uint256 public totalOwedTokenWithdrawn;
// Principal attributed to each lender
mapping (address => uint256) public balances;
// Amount of owedToken each lender has withdrawn before the loan was fully repaid
mapping (address => uint256) public owedTokenWithdrawnEarly;
// ============ Modifiers ============
modifier onlyPosition(bytes32 positionId) {
require(
POSITION_ID == positionId,
"SharedLoan#onlyPosition: Incorrect position"
);
_;
}
modifier onlyState(State specificState) {
require(
state == specificState,
"SharedLoan#onlyState: Incorrect State"
);
_;
}
// ============ Constructor ============
constructor(
bytes32 positionId,
address margin,
address initialLender,
address[] trustedMarginCallers
)
public
OnlyMargin(margin)
{
POSITION_ID = positionId;
state = State.UNINITIALIZED;
INITIAL_LENDER = initialLender;
for (uint256 i = 0; i < trustedMarginCallers.length; i++) {
TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true;
}
}
// ============ Margin-Only Functions ============
/**
* Called by the Margin contract when anyone transfers ownership of a loan to this contract.
* This function initializes this contract and returns this address to indicate to Margin
* that it is willing to take ownership of the loan.
*
* param from (unused)
* @param positionId Unique ID of the position
* @return This address on success, throw otherwise
*/
function receiveLoanOwnership(
address /* from */,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyState(State.UNINITIALIZED)
onlyPosition(positionId)
returns (address)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID);
assert(position.principal > 0);
// set relevant constants
state = State.OPEN;
totalPrincipal = position.principal;
balances[INITIAL_LENDER] = position.principal;
owedToken = position.owedToken;
heldToken = position.heldToken;
emit Initialized(POSITION_ID, position.principal);
emit BalanceAdded(
INITIAL_LENDER,
position.principal
);
return address(this); // returning own address retains ownership of loan
}
/**
* Called by Margin when additional value is added onto the position this contract
* is lending for. Balance is added to the address that loaned the additional tokens.
*
* @param payer Address that loaned the additional tokens
* @param positionId Unique ID of the position
* @param principalAdded Amount that was added to the position
* param lentAmount (unused)
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 /* lentAmount */
)
external
onlyMargin
nonReentrant
onlyState(State.OPEN)
onlyPosition(positionId)
returns (address)
{
balances[payer] = balances[payer].add(principalAdded);
totalPrincipal = totalPrincipal.add(principalAdded);
emit BalanceAdded(
payer,
principalAdded
);
return address(this);
}
/**
* Called by Margin when another address attempts to margin call the loan this contract owns
*
* @param caller Address attempting to initiate the loan call
* @param positionId Unique ID of the position
* param (unused)
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 /* depositAmount */
)
external
onlyMargin
nonReentrant
onlyState(State.OPEN)
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[caller],
"SharedLoan#marginCallOnBehalfOf: margin caller must be trusted"
);
return address(this);
}
/**
* Called by Margin when another address attempts to cancel a margin call for the loan
* this contract owns
*
* @param canceler Address attempting to initiate the loan call cancel
* @param positionId Unique ID of the position
* @return True to consent to the loan call being canceled if the initiator is a
* trusted loan caller, false otherwise
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyState(State.OPEN)
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[canceler],
"SharedLoan#marginCallOnBehalfOf: margin call canceler must be trusted"
);
return address(this);
}
/**
* Called by Margin when another address attempts to force recover the loan
* this contract owns. This contract will receive funds on a force recover. This contract
* always consents to anyone initiating a force recover
*
* param recoverer (unused)
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address /* recoverer */,
bytes32 positionId,
address recipient
)
external
onlyMargin
nonReentrant
onlyState(State.OPEN)
onlyPosition(positionId)
returns (address)
{
require(
recipient == address(this),
"SharedLoan#forceRecoverCollateralOnBehalfOf: Invalid collateral recipient"
);
state = State.CLOSED;
return address(this);
}
// ============ Public State Changing Functions ============
/**
* Helper to allow withdrawal for multiple lenders in one call
*
* @param who Array of addresses to withdraw for
*/
function withdrawMultiple(
address[] who
)
external
nonReentrant
{
require(
state == State.OPEN || state == State.CLOSED,
"SharedLoan#withdrawMultiple: Invalid state"
);
updateStateOnClosed();
for (uint256 i = 0; i < who.length; i++) {
withdrawImpl(who[i]);
}
}
/**
* Withdraw tokens that were repaid for this loan. Callable by anyone for a specific lender.
* Tokens will be sent directly to the lender. Tokens could include owedToken and/or
* heldToken (if the loan was force recovered). Callable at any time
*
* @param who Lender to withdraw for
* @return Values corresponding to:
* 1) Amount of owedToken paid out
* 2) Amount of heldToken paid out
*/
function withdraw(
address who
)
external
nonReentrant
returns (uint256, uint256)
{
require(
state == State.OPEN || state == State.CLOSED,
"SharedLoan#withdraw: Invalid state"
);
updateStateOnClosed();
return withdrawImpl(who);
}
// ============ Private Functions ============
function updateStateOnClosed()
private
{
if (state != State.CLOSED) {
if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) {
state = State.CLOSED;
}
}
}
function withdrawImpl(
address who
)
private
returns (uint256, uint256)
{
uint256 balance = balances[who];
if (balance == 0) {
return (0, 0);
}
uint256 owedTokenWithdrawn = withdrawOwedTokens(who, balance);
uint256 heldTokenWithdrawn = 0;
bool completelyRepaid = false;
if (state == State.CLOSED) {
heldTokenWithdrawn = withdrawHeldTokens(who, balance);
totalPrincipalFullyWithdrawn = totalPrincipalFullyWithdrawn.add(balance);
balances[who] = 0;
completelyRepaid = true;
}
emit TokensWithdrawn(
who,
owedTokenWithdrawn,
heldTokenWithdrawn,
completelyRepaid
);
return (
owedTokenWithdrawn,
heldTokenWithdrawn
);
}
function withdrawOwedTokens(
address who,
uint256 balance
)
private
returns (uint256)
{
uint256 currentOwedTokenBalance = TokenInteract.balanceOf(
owedToken,
address(this));
uint256 totalOwedTokenEverHeld = currentOwedTokenBalance.add(
totalOwedTokenWithdrawn);
uint256 allowedAmount = MathHelpers.getPartialAmount(
balance,
totalPrincipal,
totalOwedTokenEverHeld
).sub(owedTokenWithdrawnEarly[who]);
if (allowedAmount == 0) {
return 0;
}
totalOwedTokenWithdrawn =
totalOwedTokenWithdrawn.add(allowedAmount);
if (state == State.OPEN) {
owedTokenWithdrawnEarly[who] =
owedTokenWithdrawnEarly[who].add(allowedAmount);
}
TokenInteract.transfer(owedToken, who, allowedAmount);
return allowedAmount;
}
function withdrawHeldTokens(
address who,
uint256 balance
)
private
returns (uint256)
{
uint256 currentHeldTokenBalance = TokenInteract.balanceOf(
heldToken,
address(this));
uint256 allowedAmount = MathHelpers.getPartialAmount(
balance,
totalPrincipal.sub(totalPrincipalFullyWithdrawn),
currentHeldTokenBalance
);
if (allowedAmount == 0) {
return 0;
}
TokenInteract.transfer(heldToken, who, allowedAmount);
return allowedAmount;
}
}