forked from compound-finance/compound-protocol
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathCCollateralCapErc20.sol
693 lines (597 loc) · 31 KB
/
CCollateralCapErc20.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
pragma solidity ^0.5.16;
import "./CToken.sol";
import "./ComptrollerStorage.sol";
/**
* @title Cream's Comptroller interface extension
*/
interface ComptrollerInterfaceExtension {
function checkMembership(address account, CToken cToken) external view returns (bool);
function updateCTokenVersion(address cToken, ComptrollerV2Storage.Version version) external;
}
/**
* @title Cream's CCollateralCapErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying with collateral cap
* @author Cream
*/
contract CCollateralCapErc20 is CToken, CCollateralCapErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/**
* @notice Set the given collateral cap for the market.
* @param newCollateralCap New collateral cap for this market. A value of 0 corresponds to no cap.
*/
function _setCollateralCap(uint newCollateralCap) external {
require(msg.sender == admin, "only admin can set collateral cap");
collateralCap = newCollateralCap;
emit NewCollateralCap(address(this), newCollateralCap);
}
/**
* @notice Absorb excess cash into reserves.
*/
function gulp() external nonReentrant {
uint256 cashOnChain = getCashOnChain();
uint256 cashPrior = getCashPrior();
uint excessCash = sub_(cashOnChain, cashPrior);
totalReserves = add_(totalReserves, excessCash);
internalCash = cashOnChain;
}
/**
* @notice Flash loan funds to a given account.
* @param receiver The receiver address for the funds
* @param amount The amount of the funds to be loaned
* @param params The other parameters
*/
function flashLoan(address receiver, uint amount, bytes calldata params) external nonReentrant {
uint cashOnChainBefore = getCashOnChain();
uint cashBefore = getCashPrior();
require(cashBefore >= amount, "INSUFFICIENT_LIQUIDITY");
// 1. calculate fee, 1 bips = 1/10000
uint totalFee = div_(mul_(amount, flashFeeBips), 10000);
// 2. transfer fund to receiver
doTransferOut(address(uint160(receiver)), amount);
// 3. execute receiver's callback function
IFlashloanReceiver(receiver).executeOperation(msg.sender, underlying, amount, totalFee, params);
// 4. check balance
uint cashOnChainAfter = getCashOnChain();
require(cashOnChainAfter == add_(cashOnChainBefore, totalFee), "BALANCE_INCONSISTENT");
// 5. update reserves and internal cash
uint reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee);
totalReserves = add_(totalReserves, reservesFee);
internalCash = add_(cashBefore, totalFee);
emit Flashloan(receiver, amount, totalFee, reservesFee);
}
/**
* @notice Register account collateral tokens if there is space.
* @param account The account to register
* @dev This function could only be called by comptroller.
* @return The actual registered amount of collateral
*/
function registerCollateral(address account) external returns (uint) {
// Make sure accountCollateralTokens of `account` is initialized.
initializeAccountCollateralTokens(account);
require(msg.sender == address(comptroller), "only comptroller may register collateral for user");
uint amount = sub_(accountTokens[account], accountCollateralTokens[account]);
return increaseUserCollateralInternal(account, amount);
}
/**
* @notice Unregister account collateral tokens if the account still has enough collateral.
* @dev This function could only be called by comptroller.
* @param account The account to unregister
*/
function unregisterCollateral(address account) external {
// Make sure accountCollateralTokens of `account` is initialized.
initializeAccountCollateralTokens(account);
require(msg.sender == address(comptroller), "only comptroller may unregister collateral for user");
decreaseUserCollateralInternal(account, accountCollateralTokens[account]);
}
/*** Safe Token ***/
/**
* @notice Gets internal balance of this contract in terms of the underlying.
* It excludes balance from direct transfer.
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
return internalCash;
}
/**
* @notice Gets total balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashOnChain() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @notice Initialize the account's collateral tokens. This function should be called in the beginning of every function
* that accesses accountCollateralTokens or accountTokens.
* @param account The account of accountCollateralTokens that needs to be updated
*/
function initializeAccountCollateralTokens(address account) internal {
/**
* If isCollateralTokenInit is false, it means accountCollateralTokens was not initialized yet.
* This case will only happen once and must be the very beginning. accountCollateralTokens is a new structure and its
* initial value should be equal to accountTokens if user has entered the market. However, it's almost impossible to
* check every user's value when the implementation becomes active. Therefore, it must rely on every action which will
* access accountTokens to call this function to check if accountCollateralTokens needed to be initialized.
*/
if (!isCollateralTokenInit[account]) {
if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(account, CToken(this))) {
accountCollateralTokens[account] = accountTokens[account];
totalCollateralTokens = add_(totalCollateralTokens, accountTokens[account]);
emit UserCollateralChanged(account, accountCollateralTokens[account]);
}
isCollateralTokenInit[account] = true;
}
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
uint transferredIn = sub_(balanceAfter, balanceBefore);
internalCash = add_(internalCash, transferredIn);
return transferredIn;
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
internalCash = sub_(internalCash, amount);
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
// Make sure accountCollateralTokens of `src` and `dst` are initialized.
initializeAccountCollateralTokens(src);
initializeAccountCollateralTokens(dst);
/**
* For every user, accountTokens must be greater than or equal to accountCollateralTokens.
* The buffer between the two values will be transferred first.
* bufferTokens = accountTokens[src] - accountCollateralTokens[src]
* collateralTokens = tokens - bufferTokens
*/
uint bufferTokens = sub_(accountTokens[src], accountCollateralTokens[src]);
uint collateralTokens = 0;
if (tokens > bufferTokens) {
collateralTokens = sub_(tokens, bufferTokens);
}
/**
* Since bufferTokens are not collateralized and can be transferred freely, we only check with comptroller
* whether collateralized tokens can be transferred.
*/
uint allowed = comptroller.transferAllowed(address(this), src, dst, collateralTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
uint allowanceNew = sub_(startingAllowance, tokens);
accountTokens[src] = sub_(accountTokens[src], tokens);
accountTokens[dst] = add_(accountTokens[dst], tokens);
if (collateralTokens > 0) {
accountCollateralTokens[src] = sub_(accountCollateralTokens[src], collateralTokens);
accountCollateralTokens[dst] = add_(accountCollateralTokens[dst], collateralTokens);
emit UserCollateralChanged(src, accountCollateralTokens[src]);
emit UserCollateralChanged(dst, accountCollateralTokens[dst]);
}
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Get the account's cToken balances
* @param account The address of the account
*/
function getCTokenBalanceInternal(address account) internal view returns (uint) {
if (isCollateralTokenInit[account]) {
return accountCollateralTokens[account];
} else {
/**
* If the value of accountCollateralTokens was not initialized, we should return the value of accountTokens.
*/
return accountTokens[account];
}
}
/**
* @notice Increase user's collateral. Increase as much as we can.
* @param account The address of the account
* @param amount The amount of collateral user wants to increase
* @return The actual increased amount of collateral
*/
function increaseUserCollateralInternal(address account, uint amount) internal returns (uint) {
uint totalCollateralTokensNew = add_(totalCollateralTokens, amount);
if (collateralCap == 0 || (collateralCap != 0 && totalCollateralTokensNew <= collateralCap)) {
// 1. If collateral cap is not set,
// 2. If collateral cap is set but has enough space for this user,
// give all the user needs.
totalCollateralTokens = totalCollateralTokensNew;
accountCollateralTokens[account] = add_(accountCollateralTokens[account], amount);
emit UserCollateralChanged(account, accountCollateralTokens[account]);
return amount;
} else if (collateralCap > totalCollateralTokens) {
// If the collateral cap is set but the remaining cap is not enough for this user,
// give the remaining parts to the user.
uint gap = sub_(collateralCap, totalCollateralTokens);
totalCollateralTokens = add_(totalCollateralTokens, gap);
accountCollateralTokens[account] = add_(accountCollateralTokens[account], gap);
emit UserCollateralChanged(account, accountCollateralTokens[account]);
return gap;
}
return 0;
}
/**
* @notice Decrease user's collateral. Reject if the amount can't be fully decrease.
* @param account The address of the account
* @param amount The amount of collateral user wants to decrease
*/
function decreaseUserCollateralInternal(address account, uint amount) internal {
require(comptroller.redeemAllowed(address(this), account, amount) == 0, "comptroller rejection");
totalCollateralTokens = sub_(totalCollateralTokens, amount);
accountCollateralTokens[account] = sub_(accountCollateralTokens[account], amount);
emit UserCollateralChanged(account, accountCollateralTokens[account]);
}
struct MintLocalVars {
uint exchangeRateMantissa;
uint mintTokens;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
// Make sure accountCollateralTokens of `minter` is initialized.
initializeAccountCollateralTokens(minter);
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
vars.exchangeRateMantissa = exchangeRateStoredInternal();
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupply = totalSupply + mintTokens
* accountTokens[minter] = accountTokens[minter] + mintTokens
*/
totalSupply = add_(totalSupply, vars.mintTokens);
accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens);
/*
* We only allocate collateral tokens if the minter has entered the market.
*/
if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(minter, CToken(this))) {
increaseUserCollateralInternal(minter, vars.mintTokens);
}
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
// unused function
// comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
struct RedeemLocalVars {
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
// Make sure accountCollateralTokens of `redeemer` is initialized.
initializeAccountCollateralTokens(redeemer);
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
vars.exchangeRateMantissa = exchangeRateStoredInternal();
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
vars.redeemAmount = redeemAmountIn;
}
/**
* For every user, accountTokens must be greater than or equal to accountCollateralTokens.
* The buffer between the two values will be redeemed first.
* bufferTokens = accountTokens[redeemer] - accountCollateralTokens[redeemer]
* collateralTokens = redeemTokens - bufferTokens
*/
uint bufferTokens = sub_(accountTokens[redeemer], accountCollateralTokens[redeemer]);
uint collateralTokens = 0;
if (vars.redeemTokens > bufferTokens) {
collateralTokens = sub_(vars.redeemTokens, bufferTokens);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
totalSupply = sub_(totalSupply, vars.redeemTokens);
accountTokens[redeemer] = sub_(accountTokens[redeemer], vars.redeemTokens);
/*
* We only deallocate collateral tokens if the redeemer needs to redeem them.
*/
if (collateralTokens > 0) {
decreaseUserCollateralInternal(redeemer, collateralTokens);
}
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
// Make sure accountCollateralTokens of `liquidator` and `borrower` are initialized.
initializeAccountCollateralTokens(liquidator);
initializeAccountCollateralTokens(borrower);
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
/*
* We calculate the new borrower and liquidator token balances and token collateral balances, failing on underflow/overflow:
* accountTokens[borrower] = accountTokens[borrower] - seizeTokens
* accountTokens[liquidator] = accountTokens[liquidator] + seizeTokens
* accountCollateralTokens[borrower] = accountCollateralTokens[borrower] - seizeTokens
* accountCollateralTokens[liquidator] = accountCollateralTokens[liquidator] + seizeTokens
*/
accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens);
accountTokens[liquidator] = add_(accountTokens[liquidator], seizeTokens);
accountCollateralTokens[borrower] = sub_(accountCollateralTokens[borrower], seizeTokens);
accountCollateralTokens[liquidator] = add_(accountCollateralTokens[liquidator], seizeTokens);
/* Emit a Transfer, UserCollateralChanged events */
emit Transfer(borrower, liquidator, seizeTokens);
emit UserCollateralChanged(borrower, accountCollateralTokens[borrower]);
emit UserCollateralChanged(liquidator, accountCollateralTokens[liquidator]);
/* We call the defense hook */
// unused function
// comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
}