-
Notifications
You must be signed in to change notification settings - Fork 2
/
rToken.sol
1412 lines (1222 loc) · 49.4 KB
/
rToken.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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*Submitted for verification at Etherscan.io on 2019-08-24
*/
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/IAllocationStrategy.sol
pragma solidity ^0.5.8;
/**
* @notice Allocation strategy for assets.
* - It invests the underlying assets into some yield generating contracts,
* usually lending contracts, in return it gets new assets aka. saving assets.
* - Sainv assets can be redeemed back to the underlying assets plus interest any time.
*/
interface IAllocationStrategy {
/**
* @notice Underlying asset for the strategy
* @return address Underlying asset address
*/
function underlying() external view returns (address);
/**
* @notice Calculates the exchange rate from the underlying to the saving assets
* @return uint256 Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Applies accrued interest to all savings
* @dev This should calculates interest accrued from the last checkpointed
* block up to the current block and writes new checkpoint to storage.
* @return bool success(true) or failure(false)
*/
function accrueInterest() external returns (bool);
/**
* @notice Sender supplies underlying assets into the market and receives saving assets in exchange
* @dev Interst shall be accrued
* @param investAmount The amount of the underlying asset to supply
* @return uint256 Amount of saving assets created
*/
function investUnderlying(uint256 investAmount) external returns (uint256);
/**
* @notice Sender redeems saving assets in exchange for a specified amount of underlying asset
* @dev Interst shall be accrued
* @param redeemAmount The amount of underlying to redeem
* @return uint256 Amount of saving assets burned
*/
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
}
// File: contracts/IRToken.sol
pragma solidity ^0.5.8;
pragma experimental ABIEncoderV2;
/**
* @notice RToken interface a ERC20 interface and one can mint new tokens by
* trasfering underlying token into the contract, configure _hats_ for
* addresses and pay earned interest in new _rTokens_.
*/
contract IRToken is IERC20 {
/**
* @notice Global stats
*/
struct GlobalStats {
/// @notice Total redeemable tokens supply
uint256 totalSupply;
/// @notice Total saving assets in redeemable amount
uint256 totalSavingsAmount;
}
/**
* @notice Stats for accounts
*/
struct AccountStats {
/// @notice Cumulative interests paid
uint256 cumulativeInterest;
}
////////////////////////////////////////////////////////////////////////////
// For external transactions
////////////////////////////////////////////////////////////////////////////
/**
* @notice Sender supplies assets into the market and receives rTokens in exchange
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure
*/
function mint(uint256 mintAmount) external returns (bool);
/**
* @notice Sender supplies assets into the market and receives rTokens in exchange
* Also setting the a selected hat for the account.
* @param hatID The id of the selected Hat
* @return uint 0=success, otherwise a failure
*/
function mintWithSelectedHat(uint256 mintAmount, uint256 hatID) external returns (bool);
/**
* @notice Sender supplies assets into the market and receives rTokens in exchange
* Also setting the a new hat for the account.
* @param mintAmount The amount of the underlying asset to supply
* @param proportions Relative proportions of benefits received by the recipients
* @return uint 0=success, otherwise a failure
*/
function mintWithNewHat(uint256 mintAmount,
address[] calldata recipients,
uint32[] calldata proportions) external returns (bool);
/**
* @notice Moves all tokens from the caller's account to `dst`.
*/
function transferAll(address dst) external returns (bool);
/**
* @notice Moves all tokens from `src` account to `dst`.
*/
function transferAllFrom(address src, address dst) external returns (bool);
/**
* @notice Sender redeems rTokens in exchange for the underlying asset
* @param redeemTokens The number of rTokens to redeem into underlying
* @return uint 0=success, otherwise a failure
*/
function redeem(uint256 redeemTokens) external returns (bool);
/**
* @notice Sender redeems all rTokens in exchange for the underlying asset
* @return uint 0=success, otherwise a failure
*/
function redeemAll() external returns (bool);
/**
* @notice Sender redeems rTokens in exchange for the underlying asset then immediately transfer them to a differen user
* @param redeemTo Destination address to send the redeemed tokens to
* @param redeemTokens The number of rTokens to redeem into underlying
* @return uint 0=success, otherwise a failure
*/
function redeemAndTransfer(address redeemTo, uint256 redeemTokens) external returns (bool);
/**
* @notice Sender redeems all rTokens in exchange for the underlying asset then immediately transfer them to a differen user
* @param redeemTo Destination address to send the redeemed tokens to
* @return uint 0=success, otherwise a failure
*/
function redeemAndTransferAll(address redeemTo) external returns (bool);
/**
* @notice Create a new Hat
* @param recipients List of beneficial recipients
* @param proportions Relative proportions of benefits received by the recipients
* @param doChangeHat Should the hat of the `msg.sender` be switched to the new one
*/
function createHat(
address[] calldata recipients,
uint32[] calldata proportions,
bool doChangeHat) external returns (uint256 hatID);
/**
* @notice Change the hat for `msg.sender`
* @param hatID The id of the Hat
*/
function changeHat(uint256 hatID) external;
/**
* @notice pay interest to the owner
* @param owner Account owner address
*
* Anyone can trigger the interest distribution on behalf of the recipient,
* due to the fact that the recipient can be a contract code that has not
* implemented the interaction with the rToken contract internally`.
*
* A interest lock-up period may apply, in order to mitigate the "hat
* inheritance scam".
*/
function payInterest(address owner) external returns (bool);
////////////////////////////////////////////////////////////////////////////
// Essential info views
////////////////////////////////////////////////////////////////////////////
/**
* @notice Get the maximum hatID in the system
*/
function getMaximumHatID() external view returns (uint256 hatID);
/**
* @notice Get the hatID of the owner and the hat structure
* @param owner Account owner address
* @return hatID Hat ID
* @return recipients Hat recipients
* @return proportions Hat recipient's relative proportions
*/
function getHatByAddress(address owner) external view
returns (
uint256 hatID,
address[] memory recipients,
uint32[] memory proportions);
/**
* @notice Get the hat structure
* @param hatID Hat ID
* @return recipients Hat recipients
* @return proportions Hat recipient's relative proportions
*/
function getHatByID(uint256 hatID) external view
returns (
address[] memory recipients,
uint32[] memory proportions);
/**
* @notice Amount of saving assets given to the recipient along with the
* loans.
* @param owner Account owner address
*/
function receivedSavingsOf(address owner) external view returns (uint256 amount);
/**
* @notice Amount of token loaned to the recipient along with the savings
* assets.
* @param owner Account owner address
* @return amount
*/
function receivedLoanOf(address owner) external view returns (uint256 amount);
/**
* @notice Get the current interest balance of the owner.
It is equivalent of: receivedSavings - receivedLoan - freeBalance
* @param owner Account owner address
* @return amount
*/
function interestPayableOf(address owner) external view returns (uint256 amount);
////////////////////////////////////////////////////////////////////////////
// statistics views
////////////////////////////////////////////////////////////////////////////
/**
* @notice Get the current saving strategy contract
* @return Saving strategy address
*/
function getCurrentSavingStrategy() external view returns (address);
/**
* @notice Get saving asset balance for specific saving strategy
* @return rAmount Balance in redeemable amount
* @return sAmount Balance in native amount of the strategy
*/
function getSavingAssetBalance() external view returns (uint256 nAmount, uint256 sAmount);
/**
* @notice Get global stats
* @return global stats
*/
function getGlobalStats() external view returns (GlobalStats memory);
/**
* @notice Get account stats
* @param owner Account owner address
* @return account stats
*/
function getAccountStats(address owner) external view returns (AccountStats memory);
////////////////////////////////////////////////////////////////////////////
// admin functions
////////////////////////////////////////////////////////////////////////////
/**
* @notice Change allocation strategy for the contract instance
* @param allocationStrategy Allocation strategy instance
*/
function changeAllocationStrategy(IAllocationStrategy allocationStrategy) external;
////////////////////////////////////////////////////////////////////////////
// Events
////////////////////////////////////////////////////////////////////////////
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address indexed minter, uint256 mintAmount);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address indexed redeemer, address indexed redeemTo, uint256 redeemAmount);
/**
* @notice Event emitted when interest paid
*/
event InterestPaid(address indexed recipient, uint256 interestAmount);
/**
* @notice A new hat is created
*/
event HatCreated(uint256 indexed hatID);
/**
* @notice Hat is changed for the account
*/
event HatChanged(address indexed account, uint256 indexed hatID);
}
// File: contracts/RToken.sol
pragma solidity ^0.5.8;
/**
* @notice RToken an ERC20 token that is 1:1 redeemable to its underlying ERC20 token.
*/
contract RToken is IRToken, Ownable, ReentrancyGuard {
using SafeMath for uint256;
uint256 public constant SELF_HAT_ID = uint256(int256(-1));
uint32 constant PROPORTION_BASE = 0xFFFFFFFF;
//
// public structures
//
/**
* @notice Hat structure describes who are the recipients of the interest
*
* To be a valid hat structure:
* - at least one recipient
* - recipients.length == proportions.length
* - each value in proportions should be greater than 0
*/
struct Hat {
address[] recipients;
uint32[] proportions;
}
/**
* @notice Create rToken linked with cToken at `cToken_`
*/
constructor(IAllocationStrategy allocationStrategy) public {
ias = allocationStrategy;
token = IERC20(ias.underlying());
// special hat aka. zero hat : hatID = 0
hats.push(Hat(new address[](0), new uint32[](0)));
}
//
// ERC20 Interface
//
/**
* @notice EIP-20 token name for this token
*/
string public name = "Redeemable DAI (rDAI ethberlin)";
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol = "rDAItest";
/**
* @notice EIP-20 token decimals for this token
*/
uint256 public decimals = 18;
/**
* @notice Total number of tokens in circulation
*/
uint256 public totalSupply;
/**
* @notice Returns the amount of tokens owned by `account`.
*/
function balanceOf(address owner) external view returns (uint256) {
return accounts[owner].rAmount;
}
/**
* @notice Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Moves `amount` tokens from the caller's account to `dst`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
* May also emit `InterestPaid` event.
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferInternal(msg.sender, msg.sender, dst, amount);
}
/// @dev IRToken.transferAll implementation
function transferAll(address dst) external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
return transferInternal(src, src, dst, accounts[src].rAmount);
}
/// @dev IRToken.transferAllFrom implementation
function transferAllFrom(address src, address dst) external nonReentrant returns (bool) {
payInterestInternal(src);
payInterestInternal(dst);
return transferInternal(msg.sender, src, dst, accounts[src].rAmount);
}
/**
* @notice Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferInternal(msg.sender, src, dst, amount);
}
//
// rToken interface
//
/// @dev IRToken.mint implementation
function mint(uint256 mintAmount) external nonReentrant returns (bool) {
mintInternal(mintAmount);
return true;
}
/// @dev IRToken.mintWithSelectedHat implementation
function mintWithSelectedHat(uint256 mintAmount, uint256 hatID) external nonReentrant returns (bool) {
require(hatID == SELF_HAT_ID || hatID < hats.length, "Invalid hat ID");
changeHatInternal(msg.sender, hatID);
mintInternal(mintAmount);
return true;
}
/**
* @dev IRToken.mintWithNewHat implementation
*/
function mintWithNewHat(uint256 mintAmount,
address[] calldata recipients,
uint32[] calldata proportions) external nonReentrant returns (bool) {
uint256 hatID = createHatInternal(recipients, proportions);
changeHatInternal(msg.sender, hatID);
mintInternal(mintAmount);
return true;
}
/**
* @dev IRToken.redeem implementation
* It withdraws equal amount of initially supplied underlying assets
*/
function redeem(uint256 redeemTokens) external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
redeemInternal(src, redeemTokens);
return true;
}
/// @dev IRToken.redeemAll implementation
function redeemAll() external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
redeemInternal(src, accounts[src].rAmount);
return true;
}
/// @dev IRToken.redeemAndTransfer implementation
function redeemAndTransfer(address redeemTo, uint256 redeemTokens) external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
redeemInternal(redeemTo, redeemTokens);
return true;
}
/// @dev IRToken.redeemAndTransferAll implementation
function redeemAndTransferAll(address redeemTo) external nonReentrant returns (bool) {
address src = msg.sender;
payInterestInternal(src);
redeemInternal(redeemTo, accounts[src].rAmount);
return true;
}
/// @dev IRToken.createHat implementation
function createHat(
address[] calldata recipients,
uint32[] calldata proportions,
bool doChangeHat) external nonReentrant returns (uint256 hatID) {
hatID = createHatInternal(recipients, proportions);
if (doChangeHat) {
changeHatInternal(msg.sender, hatID);
}
}
/// @dev IRToken.changeHat implementation
function changeHat(uint256 hatID) external nonReentrant {
changeHatInternal(msg.sender, hatID);
}
/// @dev IRToken.getMaximumHatID implementation
function getMaximumHatID() external view returns (uint256 hatID) {
return hats.length - 1;
}
/// @dev IRToken.getHatByAddress implementation
function getHatByAddress(address owner) external view returns (
uint256 hatID,
address[] memory recipients,
uint32[] memory proportions) {
hatID = accounts[owner].hatID;
if (hatID != 0 && hatID != SELF_HAT_ID) {
Hat memory hat = hats[hatID];
recipients = hat.recipients;
proportions = hat.proportions;
} else {
recipients = new address[](0);
proportions = new uint32[](0);
}
}
/// @dev IRToken.getHatByID implementation
function getHatByID(uint256 hatID) external view returns (
address[] memory recipients,
uint32[] memory proportions) {
if (hatID != 0 && hatID != SELF_HAT_ID) {
Hat memory hat = hats[hatID];
recipients = hat.recipients;
proportions = hat.proportions;
} else {
recipients = new address[](0);
proportions = new uint32[](0);
}
}
/// @dev IRToken.receivedSavingsOf implementation
function receivedSavingsOf(address owner) external view returns (uint256 amount) {
Account storage account = accounts[owner];
uint256 rGross =
account.sInternalAmount
.mul(ias.exchangeRateStored())
.div(savingAssetConversionRate); // the 1e18 decimals should be cancelled out
return rGross;
}
/// @dev IRToken.receivedLoanOf implementation
function receivedLoanOf(address owner) external view returns (uint256 amount) {
Account storage account = accounts[owner];
return account.lDebt;
}
/// @dev IRToken.interestPayableOf implementation
function interestPayableOf(address owner) external view returns (uint256 amount) {
Account storage account = accounts[owner];
return getInterestPayableOf(account);
}
/// @dev IRToken.payInterest implementation
function payInterest(address owner) external nonReentrant returns (bool) {
payInterestInternal(owner);
return true;
}
/// @dev IRToken.getAccountStats implementation!1
function getGlobalStats() external view returns (GlobalStats memory) {
uint256 totalSavingsAmount;
totalSavingsAmount +=
savingAssetOrignalAmount
.mul(ias.exchangeRateStored())
.div(10 ** 18);
return GlobalStats({
totalSupply: totalSupply,
totalSavingsAmount: totalSavingsAmount
});
}
/// @dev IRToken.getAccountStats implementation
function getAccountStats(address owner) external view returns (AccountStats memory) {
Account storage account = accounts[owner];
return account.stats;
}
/// @dev IRToken.getCurrentSavingStrategy implementation
function getCurrentSavingStrategy() external view returns (address) {
return address(ias);
}
/// @dev IRToken.getSavingAssetBalance implementation
function getSavingAssetBalance() external view
returns (uint256 nAmount, uint256 sAmount) {
sAmount = savingAssetOrignalAmount;
nAmount = sAmount
.mul(ias.exchangeRateStored())
.div(10 ** 18);
}
/// @dev IRToken.changeAllocationStrategy implementation
function changeAllocationStrategy(IAllocationStrategy allocationStrategy) external nonReentrant onlyOwner {
require(allocationStrategy.underlying() == address(token), "New strategy should have the same underlying asset");
IAllocationStrategy oldIas = ias;
ias = allocationStrategy;
// redeem everything from the old strategy
uint256 sOriginalBurned = oldIas.redeemUnderlying(totalSupply);
// invest everything into the new strategy
token.transferFrom(msg.sender, address(this), totalSupply);
token.approve(address(ias), totalSupply);
uint256 sOriginalCreated = ias.investUnderlying(totalSupply);
// calculate new saving asset conversion rate
// if new original saving asset is 2x in amount
// then the conversion of internal amount should be also 2x
savingAssetConversionRate =
sOriginalCreated
.mul(10 ** 18)
.div(sOriginalBurned);
}
//
// internal
//
/// @dev Current saving strategy
IAllocationStrategy private ias;
/// @dev Underlying token
IERC20 private token;
/// @dev Saving assets original amount
uint256 private savingAssetOrignalAmount;
/// @dev Saving asset original to internal amount conversion rate.
/// - It has 18 decimals
/// - It starts with value 1.
/// - Each strategy switching results a new conversion rate
uint256 private savingAssetConversionRate = 10 ** 18;
/// @dev Saving assets exchange rate with
/// @dev Approved token transfer amounts on behalf of others
mapping(address => mapping(address => uint256)) private transferAllowances;
/// @dev Hat list
Hat[] private hats;
/// @dev Account structure
struct Account {
//
// Essential info
//
/// @dev ID of the hat selected for the account
uint256 hatID;
/// @dev Redeemable token balance for the account
uint256 rAmount;
/// @dev Redeemable token balance portion that is from interest payment