/
SmartYield.sol
658 lines (523 loc) · 19.1 KB
/
SmartYield.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
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./lib/math/MathUtils.sol";
import "./Governed.sol";
import "./IController.sol";
import "./oracle/IYieldOraclelizable.sol";
import "./ISmartYield.sol";
import "./IProvider.sol";
import "./model/IBondModel.sol";
import "./oracle/IYieldOracle.sol";
import "./IBond.sol";
import "./JuniorToken.sol";
contract SmartYield is
JuniorToken,
ISmartYield
{
using SafeMath for uint256;
// controller address
address public controller;
// address of IProviderPool
address public pool;
// senior BOND (NFT)
address public seniorBond; // IBond
// junior BOND (NFT)
address public juniorBond; // IBond
// underlying amount in matured and liquidated juniorBonds
uint256 public underlyingLiquidatedJuniors;
// tokens amount in unmatured juniorBonds or matured and unliquidated
uint256 public tokensInJuniorBonds;
// latest SeniorBond Id
uint256 public seniorBondId;
// latest JuniorBond Id
uint256 public juniorBondId;
// last index of juniorBondsMaturities that was liquidated
uint256 public juniorBondsMaturitiesPrev;
// list of junior bond maturities (timestamps)
uint256[] public juniorBondsMaturities;
// checkpoints for all JuniorBonds matureing at (timestamp) -> (JuniorBondsAt)
// timestamp -> JuniorBondsAt
mapping(uint256 => JuniorBondsAt) public juniorBondsMaturingAt;
// metadata for senior bonds
// bond id => bond (SeniorBond)
mapping(uint256 => SeniorBond) public seniorBonds;
// metadata for junior bonds
// bond id => bond (JuniorBond)
mapping(uint256 => JuniorBond) public juniorBonds;
// pool state / average bond
// holds rate of payment by juniors to seniors
SeniorBond public abond;
bool public _setup;
// emitted when user buys junior ERC20 tokens
event BuyTokens(address indexed buyer, uint256 underlyingIn, uint256 tokensOut, uint256 fee);
// emitted when user sells junior ERC20 tokens and forfeits their share of the debt
event SellTokens(address indexed seller, uint256 tokensIn, uint256 underlyingOut, uint256 forfeits);
event BuySeniorBond(address indexed buyer, uint256 indexed seniorBondId, uint256 underlyingIn, uint256 gain, uint256 forDays);
event RedeemSeniorBond(address indexed owner, uint256 indexed seniorBondId, uint256 fee);
event BuyJuniorBond(address indexed buyer, uint256 indexed juniorBondId, uint256 tokensIn, uint256 maturesAt);
event RedeemJuniorBond(address indexed owner, uint256 indexed juniorBondId, uint256 underlyingOut);
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
)
JuniorToken(name_, symbol_, decimals_)
{}
function setup(
address controller_,
address pool_,
address seniorBond_,
address juniorBond_
)
external
{
require(
false == _setup,
"SY: already setup"
);
controller = controller_;
pool = pool_;
seniorBond = seniorBond_;
juniorBond = juniorBond_;
_setup = true;
}
// externals
// buy at least _minTokens with _underlyingAmount, before _deadline passes
function buyTokens(
uint256 underlyingAmount_,
uint256 minTokens_,
uint256 deadline_
)
external override
{
_beforeProviderOp();
require(
false == IController(controller).PAUSED_BUY_JUNIOR_TOKEN(),
"SY: buyTokens paused"
);
require(
this.currentTime() <= deadline_,
"SY: buyTokens deadline"
);
uint256 fee = MathUtils.fractionOf(underlyingAmount_, IController(controller).FEE_BUY_JUNIOR_TOKEN());
uint256 getsTokens = (underlyingAmount_ - fee) * 1e18 / this.price();
require(
getsTokens >= minTokens_,
"SY: buyTokens minTokens"
);
// ---
address buyer = msg.sender;
IProvider(pool)._takeUnderlying(buyer, underlyingAmount_);
IProvider(pool)._depositProvider(underlyingAmount_, fee);
_mint(buyer, getsTokens);
emit BuyTokens(buyer, underlyingAmount_, getsTokens, fee);
}
// sell _tokens for at least _minUnderlying, before _deadline and forfeit potential future gains
function sellTokens(
uint256 tokenAmount_,
uint256 minUnderlying_,
uint256 deadline_
)
external override
{
_beforeProviderOp();
require(
this.currentTime() <= deadline_,
"SY: sellTokens deadline"
);
// share of these tokens in the debt
uint256 debtShare = tokenAmount_ * 1e18 / totalSupply();
uint256 forfeits = (this.abondDebt() * debtShare) / 1e18;
// debt share is forfeit, and only diff is returned to user
uint256 toPay = (tokenAmount_ * this.price()) / 1e18 - forfeits;
require(
toPay >= minUnderlying_,
"SY: sellTokens minUnderlying"
);
// ---
address seller = msg.sender;
_burn(seller, tokenAmount_);
IProvider(pool)._withdrawProvider(toPay, 0);
IProvider(pool)._sendUnderlying(seller, toPay);
emit SellTokens(seller, tokenAmount_, toPay, forfeits);
}
// Purchase a senior bond with principalAmount_ underlying for forDays_, buyer gets a bond with gain >= minGain_ or revert. deadline_ is timestamp before which tx is not rejected.
// returns gain
function buyBond(
uint256 principalAmount_,
uint256 minGain_,
uint256 deadline_,
uint16 forDays_
)
external override
returns (uint256)
{
_beforeProviderOp();
require(
false == IController(controller).PAUSED_BUY_SENIOR_BOND(),
"SY: buyBond paused"
);
require(
this.currentTime() <= deadline_,
"SY: buyBond deadline"
);
require(
0 < forDays_ && forDays_ <= IController(controller).BOND_LIFE_MAX(),
"SY: buyBond forDays"
);
uint256 issuedAt = this.currentTime();
// ---
address buyer = msg.sender;
IProvider(pool)._takeUnderlying(buyer, principalAmount_);
IProvider(pool)._depositProvider(principalAmount_, 0);
uint256 gain = this.bondGain(principalAmount_, forDays_);
require(
gain >= minGain_,
"SY: buyBond minGain"
);
require(
gain > 0,
"SY: buyBond gain 0"
);
require(
gain < this.underlyingLoanable(),
"SY: buyBond underlyingLoanable"
);
SeniorBond memory b =
SeniorBond(
principalAmount_,
gain,
issuedAt,
uint256(1 days) * uint256(forDays_) + issuedAt,
false
);
_mintBond(buyer, b);
emit BuySeniorBond(buyer, seniorBondId, principalAmount_, gain, forDays_);
return gain;
}
// buy an nft with tokenAmount_ jTokens, that matures at abond maturesAt
function buyJuniorBond(
uint256 tokenAmount_,
uint256 maxMaturesAt_,
uint256 deadline_
)
external override
{
uint256 maturesAt = 1 + abond.maturesAt / 1e18;
require(
this.currentTime() <= deadline_,
"SY: buyJuniorBond deadline"
);
require(
maturesAt <= maxMaturesAt_,
"SY: buyJuniorBond maxMaturesAt"
);
JuniorBond memory jb = JuniorBond(
tokenAmount_,
maturesAt
);
// ---
address buyer = msg.sender;
_takeTokens(buyer, tokenAmount_);
_mintJuniorBond(buyer, jb);
emit BuyJuniorBond(buyer, juniorBondId, tokenAmount_, maturesAt);
// if abond.maturesAt is past we can liquidate, but juniorBondsMaturingAt might have already been liquidated
if (this.currentTime() >= maturesAt) {
JuniorBondsAt memory jBondsAt = juniorBondsMaturingAt[jb.maturesAt];
if (jBondsAt.price == 0) {
_liquidateJuniorsAt(jb.maturesAt);
} else {
// juniorBondsMaturingAt was previously liquidated,
_burn(address(this), jb.tokens); // burns user's locked tokens reducing the jToken supply
underlyingLiquidatedJuniors += jb.tokens * jBondsAt.price / 1e18;
_unaccountJuniorBond(jb);
}
return this.redeemJuniorBond(juniorBondId);
}
}
// Redeem a senior bond by it's id. Anyone can redeem but owner gets principal + gain
function redeemBond(
uint256 bondId_
)
external override
{
_beforeProviderOp();
require(
this.currentTime() >= seniorBonds[bondId_].maturesAt,
"SY: redeemBond not matured"
);
// bondToken.ownerOf will revert for burned tokens
address payTo = IBond(seniorBond).ownerOf(bondId_);
uint256 payAmnt = seniorBonds[bondId_].gain + seniorBonds[bondId_].principal;
uint256 fee = MathUtils.fractionOf(seniorBonds[bondId_].gain, IController(controller).FEE_REDEEM_SENIOR_BOND());
payAmnt -= fee;
// ---
if (seniorBonds[bondId_].liquidated == false) {
seniorBonds[bondId_].liquidated = true;
_unaccountBond(seniorBonds[bondId_]);
}
// bondToken.burn will revert for already burned tokens
IBond(seniorBond).burn(bondId_);
IProvider(pool)._withdrawProvider(payAmnt, fee);
IProvider(pool)._sendUnderlying(payTo, payAmnt);
emit RedeemSeniorBond(payTo, bondId_, fee);
}
// once matured, redeem a jBond for underlying
function redeemJuniorBond(uint256 jBondId_)
external override
{
_beforeProviderOp();
JuniorBond memory jb = juniorBonds[jBondId_];
require(
jb.maturesAt <= this.currentTime(),
"SY: redeemJuniorBond maturesAt"
);
JuniorBondsAt memory jBondsAt = juniorBondsMaturingAt[jb.maturesAt];
// blows up if already burned
address payTo = IBond(juniorBond).ownerOf(jBondId_);
uint256 payAmnt = jBondsAt.price * jb.tokens / 1e18;
// ---
_burnJuniorBond(jBondId_);
IProvider(pool)._withdrawProvider(payAmnt, 0);
IProvider(pool)._sendUnderlying(payTo, payAmnt);
underlyingLiquidatedJuniors -= payAmnt;
emit RedeemJuniorBond(payTo, jBondId_, payAmnt);
}
// given a principal amount and a number of days, compute the guaranteed bond gain, excluding principal
function bondGain(uint256 principalAmount_, uint16 forDays_)
external override
returns (uint256)
{
return IBondModel(IController(controller).bondModel()).gain(
this.underlyingTotal(),
this.underlyingLoanable(),
IController(controller).providerRatePerDay(),
principalAmount_,
forDays_
);
}
// returns the maximum theoretically possible daily rate for senior bonds,
// in reality the actual rate given to a bond will always be lower due to slippage
function maxBondDailyRate()
external override
returns (uint256)
{
return IBondModel(IController(controller).bondModel()).maxDailyRate(
this.underlyingTotal(),
this.underlyingLoanable(),
IController(controller).providerRatePerDay()
);
}
// /externals
// publics
function currentTime()
public view virtual override
returns (uint256)
{
// mockable
return block.timestamp;
}
// jToken price * 1e18
function price()
public override
returns (uint256)
{
uint256 ts = totalSupply();
return (ts == 0) ? 1e18 : (this.underlyingJuniors() * 1e18) / ts;
}
function underlyingTotal()
public virtual override
returns(uint256)
{
return IProvider(pool).underlyingBalance() - IProvider(pool).underlyingFees() - underlyingLiquidatedJuniors;
}
function underlyingJuniors()
public virtual override
returns (uint256)
{
return this.underlyingTotal() - abond.principal - this.abondPaid();
}
function underlyingLoanable()
public virtual override
returns (uint256)
{
// underlyingTotal - abond.principal - abond.gain - queued withdrawls
return this.underlyingTotal() - abond.principal - abond.gain - (tokensInJuniorBonds * this.price() / 1e18);
}
function abondGain()
public view override
returns (uint256)
{
return abond.gain;
}
function abondPaid()
public view override
returns (uint256)
{
uint256 ts = this.currentTime() * 1e18;
if (ts <= abond.issuedAt || (abond.maturesAt <= abond.issuedAt)) {
return 0;
}
uint256 d = abond.maturesAt - abond.issuedAt;
return (this.abondGain() * MathUtils.min(ts - abond.issuedAt, d)) / d;
}
function abondDebt()
public view override
returns (uint256)
{
return this.abondGain() - this.abondPaid();
}
// /publics
// internals
function _beforeProviderOp() internal {
// this modifier will be added to the begginging of all (write) functions.
// The first tx after a queued liquidation's timestamp will trigger the liquidation
// reducing the jToken supply, and setting aside owed_dai for withdrawals
for (uint256 i = juniorBondsMaturitiesPrev; i < juniorBondsMaturities.length; i++) {
if (this.currentTime() >= juniorBondsMaturities[i]) {
_liquidateJuniorsAt(juniorBondsMaturities[i]);
juniorBondsMaturitiesPrev = i + 1;
} else {
break;
}
}
}
function _liquidateJuniorsAt(uint256 timestamp_)
internal
{
JuniorBondsAt storage jBondsAt = juniorBondsMaturingAt[timestamp_];
require(
jBondsAt.tokens > 0,
"SY: nothing to liquidate"
);
require(
jBondsAt.price == 0,
"SY: already liquidated"
);
jBondsAt.price = this.price();
// ---
underlyingLiquidatedJuniors += jBondsAt.tokens * jBondsAt.price / 1e18;
_burn(address(this), jBondsAt.tokens); // burns Junior locked tokens reducing the jToken supply
tokensInJuniorBonds -= jBondsAt.tokens;
}
// removes matured seniorBonds from being accounted in abond
function unaccountBonds(uint256[] memory bondIds_) public override {
for (uint256 f = 0; f < bondIds_.length; f++) {
if (
this.currentTime() > seniorBonds[bondIds_[f]].maturesAt &&
seniorBonds[bondIds_[f]].liquidated == false
) {
seniorBonds[bondIds_[f]].liquidated = true;
_unaccountBond(seniorBonds[bondIds_[f]]);
}
}
}
function _mintBond(address to_, SeniorBond memory bond_)
internal
{
require(
seniorBondId < uint256(-1),
"SY: _mintBond"
);
seniorBondId++;
seniorBonds[seniorBondId] = bond_;
_accountBond(bond_);
IBond(seniorBond).mint(to_, seniorBondId);
}
// when a new bond is added to the pool, we want:
// - to average abond.maturesAt (the earliest date at which juniors can fully exit), this shortens the junior exit date compared to the date of the last active bond
// - to keep the price for jTokens before a bond is bought ~equal with the price for jTokens after a bond is bought
function _accountBond(SeniorBond memory b_)
internal
{
uint256 _now = this.currentTime() * 1e18;
uint256 newDebt = this.abondDebt() + b_.gain;
// for the very first bond or the first bond after abond maturity: this.abondDebt() = 0 => newMaturesAt = b.maturesAt
uint256 newMaturesAt = (abond.maturesAt * this.abondDebt() + b_.maturesAt * 1e18 * b_.gain) / newDebt;
// timestamp = timestamp - tokens * d / tokens
uint256 newIssuedAt = newMaturesAt.sub(uint256(1) + ((abond.gain + b_.gain) * (newMaturesAt - _now)) / newDebt, "SY: liquidate some seniorBonds");
abond = SeniorBond(
abond.principal + b_.principal,
abond.gain + b_.gain,
newIssuedAt,
newMaturesAt,
false
);
}
// when a bond is redeemed from the pool, we want:
// - for abond.maturesAt (the earliest date at which juniors can fully exit) to remain the same as before the redeem
// - to keep the price for jTokens before a bond is bought ~equal with the price for jTokens after a bond is bought
function _unaccountBond(SeniorBond memory b_)
internal
{
uint256 now_ = this.currentTime() * 1e18;
if ((now_ >= abond.maturesAt)) {
// abond matured
// this.abondDebt() == 0
abond = SeniorBond(
abond.principal - b_.principal,
abond.gain - b_.gain,
now_ - (abond.maturesAt - abond.issuedAt),
now_,
false
);
return;
}
// timestamp = timestamp - tokens * d / tokens
uint256 newIssuedAt = abond.maturesAt.sub(uint256(1) + (abond.gain - b_.gain) * (abond.maturesAt - now_) / this.abondDebt(), "SY: liquidate some seniorBonds");
abond = SeniorBond(
abond.principal - b_.principal,
abond.gain - b_.gain,
newIssuedAt,
abond.maturesAt,
false
);
}
function _mintJuniorBond(address to_, JuniorBond memory jb_)
internal
{
require(
juniorBondId < uint256(-1),
"SY: _mintJuniorBond"
);
juniorBondId++;
juniorBonds[juniorBondId] = jb_;
_accountJuniorBond(jb_);
IBond(juniorBond).mint(to_, juniorBondId);
}
function _accountJuniorBond(JuniorBond memory jb_)
internal
{
tokensInJuniorBonds += jb_.tokens;
JuniorBondsAt storage jBondsAt = juniorBondsMaturingAt[jb_.maturesAt];
uint256 tmp;
if (jBondsAt.tokens == 0 && this.currentTime() < jb_.maturesAt) {
juniorBondsMaturities.push(jb_.maturesAt);
for (uint256 i = juniorBondsMaturities.length - 1; i >= MathUtils.max(1, juniorBondsMaturitiesPrev); i--) {
if (juniorBondsMaturities[i] > juniorBondsMaturities[i - 1]) {
break;
}
tmp = juniorBondsMaturities[i - 1];
juniorBondsMaturities[i - 1] = juniorBondsMaturities[i];
juniorBondsMaturities[i] = tmp;
}
}
jBondsAt.tokens += jb_.tokens;
}
function _burnJuniorBond(uint256 bondId_) internal {
// blows up if already burned
IBond(juniorBond).burn(bondId_);
}
function _unaccountJuniorBond(JuniorBond memory jb_) internal {
tokensInJuniorBonds -= jb_.tokens;
JuniorBondsAt storage jBondsAt = juniorBondsMaturingAt[jb_.maturesAt];
jBondsAt.tokens -= jb_.tokens;
}
function _takeTokens(address from_, uint256 amount_) internal {
_transfer(from_, address(this), amount_);
}
// /internals
}