-
Notifications
You must be signed in to change notification settings - Fork 0
/
NAVCalculator.sol
534 lines (376 loc) · 14.7 KB
/
NAVCalculator.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
/**
The software and documentation available in this repository (the "Software") is
protected by copyright law and accessible pursuant to the license set forth below.
Copyright © 2019 Staked Securely, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person or organization
obtaining the Software (the “Licensee”) to privately study, review, and analyze
the Software. Licensee shall not use the Software for any other purpose. Licensee
shall not modify, transfer, assign, share, or sub-license the Software or any
derivative works of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT
HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT,
OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE.
*/
pragma solidity 0.4.25;
// external dependency
import "./openzeppelin/math/SafeMath.sol";
// internal dependencies
import "../interfaces/IRAYToken.sol";
import "../interfaces/Opportunity.sol";
import "../interfaces/Upgradeable.sol";
import "./Storage.sol";
import "./wrappers/StorageWrapper.sol";
/// @notice NAVCalculator generally holds functions to calculate the NAV and
/// calculate the value or portfolio [RAY] and opportunity tokens.
/// However, it does contain functions not semantically correct
/// but I've put them here for now to avoid PortfolioManager being
/// to large (reduce bytecode) and also avoid creating more contracts.
///
/// Author: Devan Purhar
/// Version: 1.0.0
contract NAVCalculator is Upgradeable {
using SafeMath
for uint256;
/*************** STORAGE VARIABLE DECLARATIONS **************/
// contracts used
bytes32 internal constant ADMIN_CONTRACT = keccak256("AdminContract");
bytes32 internal constant RAY_TOKEN_CONTRACT = keccak256("RAYTokenContract");
bytes32 internal constant PAYER_CONTRACT = keccak256("PayerContract");
bytes32 internal constant OPPORTUNITY_MANAGER_CONTRACT = keccak256("OpportunityManagerContract");
bytes32 internal constant OPPORTUNITY_TOKEN_CONTRACT = keccak256("OpportunityTokenContract");
bytes32 internal constant STORAGE_WRAPPER_CONTRACT = keccak256("StorageWrapperContract");
uint internal constant ON_CHAIN_PRECISION = 1e18;
uint internal constant BASE_PRICE_IN_WEI = 1 wei;
Storage public _storage;
bool public deprecated;
/*************** MODIFIER DECLARATIONS **************/
/// @notice Checks the caller is our Admin contract
modifier onlyAdmin()
{
require(
msg.sender == _storage.getContractAddress(ADMIN_CONTRACT),
"#NavCalculator onlyAdmin Modifier: Only the Admin contract can call this"
);
_;
}
/// @notice Requires the sender be OpportunityManager or one of our PortfolioManager's
modifier onlyPortfolioOrOpportunityManager(bytes32 contractId)
{
require(
msg.sender == _storage.getVerifier(contractId) ||
msg.sender == _storage.getContractAddress(OPPORTUNITY_MANAGER_CONTRACT),
"#NAVCalculator onlyPortfolioOrOpportunityManager Modifier: This is not a valid contract calling"
);
_;
}
/// @notice Checks if the contract has been set to deprecated
modifier notDeprecated()
{
require(
deprecated == false,
"#NavCalculator notDeprecated Modifier: In deprecated mode - this contract has been deprecated"
);
_;
}
/////////////////////// FUNCTION DECLARATIONS BEGIN ///////////////////////
/******************* PUBLIC FUNCTIONS *******************/
/// @notice Sets the Storage contract instance
///
/// @param __storage - The Storage contracts address
constructor(address __storage) public {
_storage = Storage(__storage);
}
/// @notice Update the yield after withdrawing it
///
/// @dev Yield is always greater than zero when this is called
///
/// @param portfolioId - The portfolio id
/// @param yield - The yield withdrawn in
function updateYield(
bytes32 portfolioId,
uint yield
)
external
notDeprecated
onlyPortfolioOrOpportunityManager(portfolioId)
{
uint withdrawnYield = _storage.getWithdrawnYield(portfolioId);
if (withdrawnYield < yield) {
uint difference = yield - withdrawnYield; // can't underflow due to the if()
StorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_CONTRACT)).setWithdrawnYield(portfolioId, 0);
// realizedYield += difference;
StorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_CONTRACT)).setRealizedYield(portfolioId, _storage.getRealizedYield(portfolioId) + difference);
} else {
// withdrawnYield -= yield;
// can't underflow due to the if()
StorageWrapper(_storage.getContractAddress(STORAGE_WRAPPER_CONTRACT)).setWithdrawnYield(portfolioId, withdrawnYield - yield);
}
}
/** ----------------- ONLY ADMIN MUTATORS ----------------- **/
/// @notice Sets the deprecated flag of the contract
///
/// @dev Used when upgrading a contract
///
/// @param value - true to deprecate, false to un-deprecate
function setDeprecated(bool value) external onlyAdmin {
deprecated = value;
}
/** ----------------- VIEW ACCESSORS ----------------- **/
/// @notice Calculates the current price per share
///
/// @param portfolioId - The portfolio id
///
/// @return The price per share scaled by ON_CHAIN_PRECISION
function getPricePerShare(
bytes32 portfolioId,
uint unrealizedYield
)
public
notDeprecated
view
returns (uint)
{
uint yield = getTotalYieldPerShare(portfolioId, unrealizedYield);
uint scaledPrice = BASE_PRICE_IN_WEI * ON_CHAIN_PRECISION;
return yield + scaledPrice;
}
/// @notice Calculates the current yield per share
///
/// @param portfolioId - The portfolio id
///
/// @return The yield per share scaled by ON_CHAIN_PRECISION
function getTotalYieldPerShare(
bytes32 portfolioId,
uint unrealizedYield
)
public
view
notDeprecated
returns (uint)
{
uint shareSupply = _storage.getShareSupply(portfolioId);
if (shareSupply > 0) {
uint realizedYield = _storage.getRealizedYield(portfolioId);
uint withdrawnYield = _storage.getWithdrawnYield(portfolioId);
uint totalYield = getTotalYield(unrealizedYield, realizedYield, withdrawnYield);
uint raised = _storage.getRaised(_storage.getPrincipalAddress(portfolioId));
return (totalYield * raised) / shareSupply;
} else {
return 0;
}
}
/// @notice Calculates the total yield when considering all factors
///
/// @param unrealizedYield - The unrealized yield of the portfolio
/// @param realizedYield - The realized yield of this portfolio
/// @param withdrawnYield - The withdrawn yield of this portfolio
///
/// @return The total yield
function getTotalYield(
uint unrealizedYield,
uint realizedYield,
uint withdrawnYield
)
public
pure
returns (uint)
{
// withdrawnYield can't be bigger than unrealizedYield + realizedYield since it's the
// unrealized yield we already added to realizedYield, it's there to make sure we
// don't double count it, but check underflow anyway for now (audit suggestion)
// unrealizedYield + realizedYield - withdrawnYield
uint totalYield = SafeMath.sub((unrealizedYield + realizedYield), withdrawnYield);
return totalYield;
}
/// @notice Sums the unrealized yield from all the opportunities in this portfolio
///
/// @param portfolioId - The portfolio id
///
/// @return The total unrealized yield
function getPortfolioUnrealizedYield(bytes32 portfolioId) public notDeprecated view returns (uint) {
uint unrealizedYield;
bytes32[] memory opportunities;
opportunities = _storage.getOpportunities(portfolioId);
for (uint i = 0; i < opportunities.length; i++) {
bytes32 opportunityId = opportunities[i];
uint balance = getOpportunityBalance(portfolioId, opportunityId);
if (balance != 0) {
unrealizedYield += getOpportunityYield(portfolioId, opportunityId, balance);
}
}
return unrealizedYield;
}
/// @notice Gets the amount of yield earnt based on an amount being withdrawn
/// for an Opportunity.
///
/// @param portfolioId - The portfolio id
/// @param amountToWithdraw - The amount being withdraw
///
/// @return The total unrealized yield
function getOpportunityUnrealizedYield(
bytes32 portfolioId,
uint amountToWithdraw
)
public
view
returns (uint)
{
uint principalAmount = _storage.getPrincipal(portfolioId);
if (principalAmount >= amountToWithdraw) {
return 0; // we aren't withdrawing any yield, we prioritize taking principal out first
}
uint yield = amountToWithdraw - principalAmount; // can't underflow due to if() ^
return yield;
}
/// @notice Calculate how much yield a generic Opportunity has made
///
/// @param portfolioId - The portfolio id
/// @param opportunityId - The opportunity id
/// @param amountToWithdraw - The amount we're trying to check if we have yield on if we withdrew
///
/// @return The amount of yield this opportunity has if we withdraw a certain value
function getOpportunityYield(
bytes32 portfolioId,
bytes32 opportunityId,
uint amountToWithdraw
)
public
notDeprecated
view
returns (uint)
{
bytes32 tokenId = _storage.getOpportunityToken(portfolioId, opportunityId);
uint principalAmount = _storage.getTokenCapital(opportunityId, tokenId);
if (principalAmount >= amountToWithdraw) {
return 0;
}
uint yield = amountToWithdraw - principalAmount; // can't underflow due to if() ^
return yield;
}
/// @notice Get the total value of a generic Opportunity
///
/// @param portfolioId - The portfolio id
/// @param opportunityId - The opportunity id
///
/// @return The total value of the Opportunity (capital + yield)
function getOpportunityBalance(
bytes32 portfolioId,
bytes32 opportunityId
)
public
notDeprecated
view
returns(uint)
{
bytes32 tokenId = _storage.getOpportunityToken(portfolioId, opportunityId);
uint tokenValue;
uint pricePerShare;
if (tokenId != bytes32(0)) { // if we've lent to this opporunity
(tokenValue, pricePerShare) = getTokenValue(opportunityId, tokenId);
}
return tokenValue;
}
/// @notice Decides how much value we need to send to our OpportunityManager function
/// that accepts ETH and ERC20's. It does this by checking if the
/// coin in question is an ERC20 or not.
///
/// @param principalToken - The coin we're checking for
/// @param value - The amount of value in the coin we need to send
function calculatePayableAmount(
address principalToken,
uint value
)
external
notDeprecated
view
returns(bool, uint)
{
bool isERC20 = _storage.getIsERC20(principalToken);
uint payableValue;
if (isERC20) {
payableValue = 0;
} else {
payableValue = value;
}
return (isERC20, payableValue);
}
/// @notice Checks that if the msg.sender == our Payer contract and then the
/// original caller == the true owner. We can do this since we trust
/// Payer (ours). Else, msg.sender must be the true owner of the token.
///
/// @dev This function exists so we can support paying for user transactions.
///
/// @param tokenId - The unique id of the position in question
/// @param origCaller - The address that signed the transaction that went through Payer
/// @param msgSender - The msg.sender to the function in PortfolioManager
function onlyTokenOwner(
bytes32 tokenId,
address origCaller,
address msgSender
)
external
notDeprecated
view
returns (address)
{
if (msgSender == _storage.getContractAddress(PAYER_CONTRACT)) {
require(IRAYToken(_storage.getContractAddress(RAY_TOKEN_CONTRACT)).ownerOf(uint(tokenId)) == origCaller,
"#RAY onlyTokenOwner modifier: The original caller is not the owner of the token");
return origCaller;
} else {
require(IRAYToken(_storage.getContractAddress(RAY_TOKEN_CONTRACT)).ownerOf(uint(tokenId)) == msgSender,
"#RAY onlyTokenOwner modifier: The caller is not the owner of the token");
return msgSender;
}
}
/// @notice Calculates the current token value
///
/// @dev (price per share * shares)
///
/// @param typeId - The portfolio / opportunity id
/// @param tokenId - The unique token id
///
/// @return Value of the token and price per share used to calculate it
function getTokenValue(
bytes32 typeId,
bytes32 tokenId
)
public
view
returns(uint, uint)
{
uint pricePerShare;
if (IRAYToken(_storage.getContractAddress(RAY_TOKEN_CONTRACT)).tokenExists(tokenId)) {
pricePerShare = getPortfolioPricePerShare(typeId);
} else if (IRAYToken(_storage.getContractAddress(OPPORTUNITY_TOKEN_CONTRACT)).tokenExists(tokenId)) {
pricePerShare = getOpportunityPricePerShare(typeId);
} else {
require(1 == 0, "#NAVCalculator getTokenValue(): Invalid tokenId");
}
uint raised = _storage.getRaised(_storage.getPrincipalAddress(typeId));
uint tokenValue = pricePerShare * _storage.getTokenShares(typeId, tokenId) / raised;
return (tokenValue, pricePerShare);
}
/// @notice Helper to get a portfolios price per share
///
/// @param portfolioId - The portfolio id
///
/// @return The price per share of the portfolio
function getPortfolioPricePerShare(bytes32 portfolioId) public view returns (uint) {
uint unrealizedYield = getPortfolioUnrealizedYield(portfolioId);
return getPricePerShare(portfolioId, unrealizedYield);
}
/// @notice Helper to get an opportunities price per share
///
/// @param opportunityId - The opportunity id
///
/// @return The price per share of the opportunity
function getOpportunityPricePerShare(bytes32 opportunityId) public view returns (uint) {
address opportunity = _storage.getVerifier(opportunityId);
address principalAddress = _storage.getPrincipalAddress(opportunityId);
uint unrealizedYield = getOpportunityUnrealizedYield(opportunityId, Opportunity(opportunity).getBalance(principalAddress));
return getPricePerShare(opportunityId, unrealizedYield);
}
}