-
Notifications
You must be signed in to change notification settings - Fork 29
/
PushCoreV2.sol
1149 lines (1035 loc) · 43.8 KB
/
PushCoreV2.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
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
/**
* EPNS Core is the main protocol that deals with the imperative
* features and functionalities like Channel Creation, pushChannelAdmin etc.
*
* This protocol will be specifically deployed on Ethereum Blockchain while the Communicator
* protocols can be deployed on Multiple Chains.
* The EPNS Core is more inclined towards the storing and handling the Channel related
* Functionalties.
**/
import "./EPNSCoreStorageV1_5.sol";
import "./EPNSCoreStorageV2.sol";
import "../interfaces/IPUSH.sol";
import "../interfaces/IUniswapV2Router.sol";
import "../interfaces/IEPNSCommV1.sol";
import "../interfaces/ITokenBridge.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract PushCoreV2 is
Initializable,
EPNSCoreStorageV1_5,
PausableUpgradeable,
EPNSCoreStorageV2
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ***************
EVENTS
*************** */
event UpdateChannel(address indexed channel, bytes identity);
event RewardsClaimed(address indexed user, uint256 rewardAmount);
event ChannelVerified(address indexed channel, address indexed verifier);
event ChannelVerificationRevoked(
address indexed channel,
address indexed revoker
);
event DeactivateChannel(
address indexed channel,
uint256 indexed amountRefunded
);
event ReactivateChannel(
address indexed channel,
uint256 indexed amountDeposited
);
event ChannelBlocked(address indexed channel);
event AddChannel(
address indexed channel,
ChannelType indexed channelType,
bytes identity
);
event ChannelNotifcationSettingsAdded(
address _channel,
uint256 totalNotifOptions,
string _notifSettings,
string _notifDescription
);
event AddSubGraph(address indexed channel, bytes _subGraphData);
event TimeBoundChannelDestroyed(
address indexed channel,
uint256 indexed amountRefunded
);
event ChannelOwnershipTransfer(
address indexed channel,
address indexed newOwner
);
event Staked(address indexed user, uint256 indexed amountStaked);
event Unstaked(address indexed user, uint256 indexed amountUnstaked);
event RewardsHarvested(
address indexed user,
uint256 indexed rewardAmount,
uint256 fromEpoch,
uint256 tillEpoch
);
event RelayerAddressUpdated(
address indexed oldRelayer,
address indexed newRelayer
);
event BridgeAddressUpdated(
address indexed oldBridge,
address indexed newBridge
);
event IncentivizeChatReqReceived(
address requestSender,
address requestReceiver,
uint256 amountForReqReceiver,
uint256 feePoolAmount,
uint256 timestamp
);
event ChatIncentiveClaimed(
address indexed user,
uint256 indexed amountClaimed
);
/* ***************
INITIALIZER
*************** */
function initialize(
address _pushChannelAdmin,
address _pushTokenAddress,
address _wethAddress,
address _uniswapRouterAddress,
address _lendingPoolProviderAddress,
address _daiAddress,
address _aDaiAddress,
uint256 _referralCode
) public initializer returns (bool success) {
// setup addresses
pushChannelAdmin = _pushChannelAdmin;
governance = _pushChannelAdmin; // Will be changed on-Chain governance Address later
daiAddress = _daiAddress;
aDaiAddress = _aDaiAddress;
WETH_ADDRESS = _wethAddress;
REFERRAL_CODE = _referralCode;
PUSH_TOKEN_ADDRESS = _pushTokenAddress;
UNISWAP_V2_ROUTER = _uniswapRouterAddress;
lendingPoolProviderAddress = _lendingPoolProviderAddress;
FEE_AMOUNT = 10 ether; // PUSH Amount that will be charged as Protocol Pool Fees
MIN_POOL_CONTRIBUTION = 50 ether; // Channel's poolContribution should never go below MIN_POOL_CONTRIBUTION
ADD_CHANNEL_MIN_FEES = 50 ether; // can never be below MIN_POOL_CONTRIBUTION
ADJUST_FOR_FLOAT = 10**7;
groupLastUpdate = block.number;
groupNormalizedWeight = ADJUST_FOR_FLOAT; // Always Starts with 1 * ADJUST FOR FLOAT
// Create Channel
success = true;
}
/* ***************
SETTER & HELPER FUNCTIONS
*************** */
function onlyPushChannelAdmin() private {
require(
msg.sender == pushChannelAdmin,
"PushCoreV2::onlyPushChannelAdmin: Invalid Caller"
);
}
function onlyGovernance() private {
require(
msg.sender == governance,
"PushCoreV2::onlyGovernance: Invalid Caller"
);
}
function onlyActivatedChannels(address _channel) private {
require(
channels[_channel].channelState == 1,
"PushCoreV2::onlyActivatedChannels: Invalid Channel"
);
}
function onlyChannelOwner(address _channel) private {
require(
((channels[_channel].channelState == 1 && msg.sender == _channel) ||
(msg.sender == pushChannelAdmin && _channel == address(0x0))),
"PushCoreV2::onlyChannelOwner: Invalid Channel Owner"
);
}
function addSubGraph(bytes calldata _subGraphData) external {
onlyActivatedChannels(msg.sender);
emit AddSubGraph(msg.sender, _subGraphData);
}
function setEpnsCommunicatorAddress(address _commAddress) external {
onlyPushChannelAdmin();
epnsCommunicator = _commAddress;
}
function setGovernanceAddress(address _governanceAddress) external {
onlyPushChannelAdmin();
governance = _governanceAddress;
}
function setFeeAmount(uint256 _newFees) external {
onlyGovernance();
require(
_newFees > 0 && _newFees < ADD_CHANNEL_MIN_FEES,
"PushCoreV2::setFeeAmount: Invalid Fee"
);
FEE_AMOUNT = _newFees;
}
function setMinPoolContribution(uint256 _newAmount) external {
onlyGovernance();
require(
_newAmount > 0,
"PushCoreV2::setMinPoolContribution: Invalid Amount"
);
MIN_POOL_CONTRIBUTION = _newAmount;
}
function pauseContract() external {
onlyGovernance();
_pause();
}
function unPauseContract() external {
onlyGovernance();
_unpause();
}
/**
* @notice Allows to set the Minimum amount threshold for Creating Channels
*
* @dev Minimum required amount can never be below MIN_POOL_CONTRIBUTION
*
* @param _newFees new minimum fees required for Channel Creation
**/
function setMinChannelCreationFees(uint256 _newFees) external {
onlyGovernance();
require(
_newFees >= MIN_POOL_CONTRIBUTION,
"PushCoreV2::setMinChannelCreationFees: Invalid Fees"
);
ADD_CHANNEL_MIN_FEES = _newFees;
}
function transferPushChannelAdminControl(address _newAdmin) external {
onlyPushChannelAdmin();
require(
_newAdmin != address(0),
"PushCoreV2::transferPushChannelAdminControl: Invalid Address"
);
require(
_newAdmin != pushChannelAdmin,
"PushCoreV2::transferPushChannelAdminControl: Similar Admnin Address"
);
pushChannelAdmin = _newAdmin;
}
/* ***********************************
CHANNEL RELATED FUNCTIONALTIES
**************************************/
/**
* @notice Allows Channel Owner to update their Channel's Details like Description, Name, Logo, etc by passing in a new identity bytes hash
*
* @dev Only accessible when contract is NOT Paused
* Only accessible when Caller is the Channel Owner itself
* If Channel Owner is updating the Channel Meta for the first time:
* Required Fees => 50 PUSH tokens
*
* If Channel Owner is updating the Channel Meta for the N time:
* Required Fees => (50 * N) PUSH Tokens
*
* Total fees goes to PROTOCOL_POOL_FEES
* Updates the channelUpdateCounter
* Updates the channelUpdateBlock
* Records the Block Number of the Block at which the Channel is being updated
* Emits an event with the new identity for the respective Channel Address
*
* @param _channel address of the Channel
* @param _newIdentity bytes Value for the New Identity of the Channel
* @param _amount amount of PUSH Token required for updating channel details.
**/
function updateChannelMeta(
address _channel,
bytes calldata _newIdentity,
uint256 _amount
) external whenNotPaused {
onlyChannelOwner(_channel);
uint256 updateCounter = channelUpdateCounter[_channel].add(1);
uint256 requiredFees = ADD_CHANNEL_MIN_FEES.mul(updateCounter);
require(
_amount >= requiredFees,
"PushCoreV2::updateChannelMeta: Insufficient Deposit Amount"
);
PROTOCOL_POOL_FEES = PROTOCOL_POOL_FEES.add(_amount);
channelUpdateCounter[_channel] = updateCounter;
channels[_channel].channelUpdateBlock = block.number;
IERC20(PUSH_TOKEN_ADDRESS).safeTransferFrom(
_channel,
address(this),
_amount
);
emit UpdateChannel(_channel, _newIdentity);
}
/**
* @notice An external function that allows users to Create their Own Channels by depositing a valid amount of PUSH
* @dev Only allows users to Create One Channel for a specific address.
* Only allows a Valid Channel Type to be assigned for the Channel Being created.
* Validates and Transfers the amount of PUSH from the Channel Creator to the EPNS Core Contract
*
* @param _channelType the type of the Channel Being created
* @param _identity the bytes value of the identity of the Channel
* @param _amount Amount of PUSH to be deposited before Creating the Channel
* @param _channelExpiryTime the expiry time for time bound channels
**/
function createChannelWithPUSH(
ChannelType _channelType,
bytes calldata _identity,
uint256 _amount,
uint256 _channelExpiryTime
) external whenNotPaused {
require(
_amount >= ADD_CHANNEL_MIN_FEES,
"PushCoreV2::_createChannelWithPUSH: Insufficient Deposit Amount"
);
require(
channels[msg.sender].channelState == 0,
"PushCoreV2::onlyInactiveChannels: Channel already Activated"
);
require(
(_channelType == ChannelType.InterestBearingOpen ||
_channelType == ChannelType.InterestBearingMutual ||
_channelType == ChannelType.TimeBound ||
_channelType == ChannelType.TokenGaited),
"PushCoreV2::onlyUserAllowedChannelType: Invalid Channel Type"
);
emit AddChannel(msg.sender, _channelType, _identity);
IERC20(PUSH_TOKEN_ADDRESS).safeTransferFrom(
msg.sender,
address(this),
_amount
);
_createChannel(msg.sender, _channelType, _amount, _channelExpiryTime);
}
/**
* @notice Base Channel Creation Function that allows users to Create Their own Channels and Stores crucial details about the Channel being created
* @dev -Initializes the Channel Struct
* -Subscribes the Channel's Owner to Imperative EPNS Channels as well as their Own Channels
* - Updates the CHANNEL_POOL_FUNDS and PROTOCOL_POOL_FEES in the contract.
*
* @param _channel address of the channel being Created
* @param _channelType The type of the Channel
* @param _amountDeposited The total amount being deposited while Channel Creation
* @param _channelExpiryTime the expiry time for time bound channels
**/
function _createChannel(
address _channel,
ChannelType _channelType,
uint256 _amountDeposited,
uint256 _channelExpiryTime
) private {
uint256 poolFeeAmount = FEE_AMOUNT;
uint256 poolFundAmount = _amountDeposited.sub(poolFeeAmount);
//store funds in pool_funds & pool_fees
CHANNEL_POOL_FUNDS = CHANNEL_POOL_FUNDS.add(poolFundAmount);
PROTOCOL_POOL_FEES = PROTOCOL_POOL_FEES.add(poolFeeAmount);
// Calculate channel weight
uint256 _channelWeight = poolFundAmount.mul(ADJUST_FOR_FLOAT).div(
MIN_POOL_CONTRIBUTION
);
// Next create the channel and mark user as channellized
channels[_channel].channelState = 1;
channels[_channel].poolContribution = poolFundAmount;
channels[_channel].channelType = _channelType;
channels[_channel].channelStartBlock = block.number;
channels[_channel].channelUpdateBlock = block.number;
channels[_channel].channelWeight = _channelWeight;
// Add to map of addresses and increment channel count
uint256 _channelsCount = channelsCount;
channelById[_channelsCount] = _channel;
channelsCount = _channelsCount.add(1);
if (_channelType == ChannelType.TimeBound) {
require(
_channelExpiryTime > block.timestamp,
"PushCoreV2::createChannel: Invalid channelExpiryTime"
);
channels[_channel].expiryTime = _channelExpiryTime;
}
// Subscribe them to their own channel as well
address _epnsCommunicator = epnsCommunicator;
if (_channel != pushChannelAdmin) {
IEPNSCommV1(_epnsCommunicator).subscribeViaCore(_channel, _channel);
}
// All Channels are subscribed to EPNS Alerter as well, unless it's the EPNS Alerter channel iteself
if (_channel != address(0x0)) {
IEPNSCommV1(_epnsCommunicator).subscribeViaCore(
address(0x0),
_channel
);
IEPNSCommV1(_epnsCommunicator).subscribeViaCore(
_channel,
pushChannelAdmin
);
}
}
/**
* @notice Function that allows Channel Owners to Destroy their Time-Bound Channels
* @dev - Can only be called the owner of the Channel or by the EPNS Governance/Admin.
* - EPNS Governance/Admin can only destory a channel after 14 Days of its expriation timestamp.
* - Can only be called if the Channel is of type - TimeBound
* - Can only be called after the Channel Expiry time is up.
* - If Channel Owner destroys the channel after expiration, he/she recieves back refundable amount & CHANNEL_POOL_FUNDS decreases.
* - If Channel is destroyed by EPNS Governance/Admin, No refunds for channel owner. Refundable Push tokens are added to PROTOCOL_POOL_FEES.
* - Deletes the Channel completely
* - It transfers back refundable tokenAmount back to the USER.
**/
function destroyTimeBoundChannel(address _channelAddress)
external
whenNotPaused
{
onlyActivatedChannels(_channelAddress);
Channel memory channelData = channels[_channelAddress];
require(
channelData.channelType == ChannelType.TimeBound,
"PushCoreV2::destroyTimeBoundChannel: Channel not TIME BOUND"
);
require(
(msg.sender == _channelAddress &&
channelData.expiryTime < block.timestamp) ||
(msg.sender == pushChannelAdmin &&
channelData.expiryTime.add(14 days) < block.timestamp),
"PushCoreV2::destroyTimeBoundChannel: Invalid Caller or Channel Not Expired"
);
uint256 totalRefundableAmount = channelData.poolContribution;
if (msg.sender != pushChannelAdmin) {
CHANNEL_POOL_FUNDS = CHANNEL_POOL_FUNDS.sub(totalRefundableAmount);
IERC20(PUSH_TOKEN_ADDRESS).safeTransfer(
msg.sender,
totalRefundableAmount
);
} else {
CHANNEL_POOL_FUNDS = CHANNEL_POOL_FUNDS.sub(totalRefundableAmount);
PROTOCOL_POOL_FEES = PROTOCOL_POOL_FEES.add(totalRefundableAmount);
}
// Unsubscribing from imperative Channels
address _epnsCommunicator = epnsCommunicator;
IEPNSCommV1(_epnsCommunicator).unSubscribeViaCore(
address(0x0),
_channelAddress
);
IEPNSCommV1(_epnsCommunicator).unSubscribeViaCore(
_channelAddress,
_channelAddress
);
IEPNSCommV1(_epnsCommunicator).unSubscribeViaCore(
_channelAddress,
pushChannelAdmin
);
// Decrement Channel Count and Delete Channel Completely
channelsCount = channelsCount.sub(1);
delete channels[_channelAddress];
emit TimeBoundChannelDestroyed(msg.sender, totalRefundableAmount);
}
/** @notice - Deliminated Notification Settings string contains -> Total Notif Options + Notification Settings
* For instance: 5+1-0+2-50-20-100+1-1+2-78-10-150
* 5 -> Total Notification Options provided by a Channel owner
*
* For Boolean Type Notif Options
* 1-0 -> 1 stands for BOOLEAN type - 0 stands for Default Boolean Type for that Notifcation(set by Channel Owner), In this case FALSE.
* 1-1 stands for BOOLEAN type - 1 stands for Default Boolean Type for that Notifcation(set by Channel Owner), In this case TRUE.
*
* For SLIDER TYPE Notif Options
* 2-50-20-100 -> 2 stands for SLIDER TYPE - 50 stands for Default Value for that Option - 20 is the Start Range of that SLIDER - 100 is the END Range of that SLIDER Option
* 2-78-10-150 -> 2 stands for SLIDER TYPE - 78 stands for Default Value for that Option - 10 is the Start Range of that SLIDER - 150 is the END Range of that SLIDER Option
*
* @param _notifOptions - Total Notification options provided by the Channel Owner
* @param _notifSettings- Deliminated String of Notification Settings
* @param _notifDescription - Description of each Notification that depicts the Purpose of that Notification
* @param _amountDeposited - Fees required for setting up channel notification settings
**/
function createChannelSettings(
uint256 _notifOptions,
string calldata _notifSettings,
string calldata _notifDescription,
uint256 _amountDeposited
) external {
onlyActivatedChannels(msg.sender);
require(
_amountDeposited >= ADD_CHANNEL_MIN_FEES,
"PushCoreV2::createChannelSettings: Insufficient Funds Passed"
);
string memory notifSetting = string(
abi.encodePacked(
Strings.toString(_notifOptions),
"+",
_notifSettings
)
);
channelNotifSettings[msg.sender] = notifSetting;
PROTOCOL_POOL_FEES = PROTOCOL_POOL_FEES.add(_amountDeposited);
IERC20(PUSH_TOKEN_ADDRESS).safeTransferFrom(
msg.sender,
address(this),
_amountDeposited
);
emit ChannelNotifcationSettingsAdded(
msg.sender,
_notifOptions,
notifSetting,
_notifDescription
);
}
/**
* @notice Allows Channel Owner to Deactivate his/her Channel for any period of Time. Channels Deactivated can be Activated again.
* @dev - Function can only be Called by Already Activated Channels
* - Calculates the totalRefundableAmount for the Channel Owner.
* - The function deducts MIN_POOL_CONTRIBUTION from refundAble amount to ensure that channel's weight & poolContribution never becomes ZERO.
* - Updates the State of the Channel(channelState) and the New Channel Weight in the Channel's Struct
* - In case, the Channel Owner wishes to reactivate his/her channel, they need to Deposit at least the Minimum required PUSH while reactivating.
**/
function deactivateChannel() external whenNotPaused {
onlyActivatedChannels(msg.sender);
Channel storage channelData = channels[msg.sender];
uint256 minPoolContribution = MIN_POOL_CONTRIBUTION;
uint256 totalRefundableAmount = channelData.poolContribution.sub(
minPoolContribution
);
uint256 _newChannelWeight = minPoolContribution
.mul(ADJUST_FOR_FLOAT)
.div(minPoolContribution);
channelData.channelState = 2;
CHANNEL_POOL_FUNDS = CHANNEL_POOL_FUNDS.sub(totalRefundableAmount);
channelData.channelWeight = _newChannelWeight;
channelData.poolContribution = minPoolContribution;
IERC20(PUSH_TOKEN_ADDRESS).safeTransfer(
msg.sender,
totalRefundableAmount
);
emit DeactivateChannel(msg.sender, totalRefundableAmount);
}
/**
* @notice Allows Channel Owner to Reactivate his/her Channel again.
* @dev - Function can only be called by previously Deactivated Channels
* - Channel Owner must Depost at least minimum amount of PUSH to reactivate his/her channel.
* - Deposited PUSH amount is distributed between CHANNEL_POOL_FUNDS and PROTOCOL_POOL_FEES
* - Calculation of the new Channel Weight and poolContribution is performed and stored
* - Updates the State of the Channel(channelState) in the Channel's Struct.
* @param _amount Amount of PUSH to be deposited
**/
function reactivateChannel(uint256 _amount) external whenNotPaused {
require(
_amount >= ADD_CHANNEL_MIN_FEES,
"PushCoreV2::reactivateChannel: Insufficient Funds"
);
require(
channels[msg.sender].channelState == 2,
"PushCoreV2::onlyDeactivatedChannels: Channel is Active"
);
IERC20(PUSH_TOKEN_ADDRESS).safeTransferFrom(
msg.sender,
address(this),
_amount
);
uint256 poolFeeAmount = FEE_AMOUNT;
uint256 poolFundAmount = _amount.sub(poolFeeAmount);
//store funds in pool_funds & pool_fees
CHANNEL_POOL_FUNDS = CHANNEL_POOL_FUNDS.add(poolFundAmount);
PROTOCOL_POOL_FEES = PROTOCOL_POOL_FEES.add(poolFeeAmount);
Channel storage channelData = channels[msg.sender];
uint256 _newPoolContribution = channelData.poolContribution.add(
poolFundAmount
);
uint256 _newChannelWeight = _newPoolContribution
.mul(ADJUST_FOR_FLOAT)
.div(MIN_POOL_CONTRIBUTION);
channelData.channelState = 1;
channelData.poolContribution = _newPoolContribution;
channelData.channelWeight = _newChannelWeight;
emit ReactivateChannel(msg.sender, _amount);
}
/**
* @notice ALlows the pushChannelAdmin to Block any particular channel Completely.
*
* @dev - Can only be called by pushChannelAdmin
* - Can only be Called for Activated Channels
* - Can only Be Called for NON-BLOCKED Channels
*
* - Updates channel's state to BLOCKED ('3')
* - Decreases the Channel Count
* - Since there is no refund, the channel's poolContribution is added to PROTOCOL_POOL_FEES and Removed from CHANNEL_POOL_FUNDS
* - Emit 'ChannelBlocked' Event
* @param _channelAddress Address of the Channel to be blocked
**/
function blockChannel(address _channelAddress) external whenNotPaused {
onlyPushChannelAdmin();
require(
((channels[_channelAddress].channelState != 3) &&
(channels[_channelAddress].channelState != 0)),
"PushCoreV2::onlyUnblockedChannels: Invalid Channel"
);
uint256 minPoolContribution = MIN_POOL_CONTRIBUTION;
Channel storage channelData = channels[_channelAddress];
// add channel's currentPoolContribution to PoolFees - (no refunds if Channel is blocked)
// Decrease CHANNEL_POOL_FUNDS by currentPoolContribution
uint256 currentPoolContribution = channelData.poolContribution.sub(
minPoolContribution
);
CHANNEL_POOL_FUNDS = CHANNEL_POOL_FUNDS.sub(currentPoolContribution);
PROTOCOL_POOL_FEES = PROTOCOL_POOL_FEES.add(currentPoolContribution);
uint256 _newChannelWeight = minPoolContribution
.mul(ADJUST_FOR_FLOAT)
.div(minPoolContribution);
channelsCount = channelsCount.sub(1);
channelData.channelState = 3;
channelData.channelWeight = _newChannelWeight;
channelData.channelUpdateBlock = block.number;
channelData.poolContribution = minPoolContribution;
emit ChannelBlocked(_channelAddress);
}
/* **************
=> CHANNEL VERIFICATION FUNCTIONALTIES <=
*************** */
/**
* @notice Function is designed to tell if a channel is verified or not
* @dev Get if channel is verified or not
* @param _channel Address of the channel to be Verified
* @return verificationStatus Returns 0 for not verified, 1 for primary verification, 2 for secondary verification
**/
function getChannelVerfication(address _channel)
public
view
returns (uint8 verificationStatus)
{
address verifiedBy = channels[_channel].verifiedBy;
bool logicComplete = false;
// Check if it's primary verification
if (
verifiedBy == pushChannelAdmin ||
_channel == address(0x0) ||
_channel == pushChannelAdmin
) {
// primary verification, mark and exit
verificationStatus = 1;
} else {
// can be secondary verification or not verified, dig deeper
while (!logicComplete) {
if (verifiedBy == address(0x0)) {
verificationStatus = 0;
logicComplete = true;
} else if (verifiedBy == pushChannelAdmin) {
verificationStatus = 2;
logicComplete = true;
} else {
// Upper drill exists, go up
verifiedBy = channels[verifiedBy].verifiedBy;
}
}
}
}
function batchVerification(
uint256 _startIndex,
uint256 _endIndex,
address[] calldata _channelList
) external returns (bool) {
onlyPushChannelAdmin();
for (uint256 i = _startIndex; i < _endIndex; i++) {
verifyChannel(_channelList[i]);
}
return true;
}
/**
* @notice Function is designed to verify a channel
* @dev Channel will be verified by primary or secondary verification, will fail or upgrade if already verified
* @param _channel Address of the channel to be Verified
**/
function verifyChannel(address _channel) public {
onlyActivatedChannels(_channel);
// Check if caller is verified first
uint8 callerVerified = getChannelVerfication(msg.sender);
require(
callerVerified > 0,
"PushCoreV2::verifyChannel: Caller is not verified"
);
// Check if channel is verified
uint8 channelVerified = getChannelVerfication(_channel);
require(
channelVerified == 0 || msg.sender == pushChannelAdmin,
"PushCoreV2::verifyChannel: Channel already verified"
);
// Verify channel
channels[_channel].verifiedBy = msg.sender;
// Emit event
emit ChannelVerified(_channel, msg.sender);
}
/**
* @notice Function is designed to unverify a channel
* @dev Channel who verified this channel or Push Channel Admin can only revoke
* @param _channel Address of the channel to be unverified
**/
function unverifyChannel(address _channel) public {
require(
channels[_channel].verifiedBy == msg.sender ||
msg.sender == pushChannelAdmin,
"PushCoreV2::unverifyChannel: Invalid Caller"
);
// Unverify channel
channels[_channel].verifiedBy = address(0x0);
// Emit Event
emit ChannelVerificationRevoked(_channel, msg.sender);
}
/*** Core-V2: Stake and Claim Functions ***/
/**
* Allows caller to add pool_fees at any given epoch
**/
function addPoolFees(uint256 _rewardAmount) external {
IERC20(PUSH_TOKEN_ADDRESS).safeTransferFrom(
msg.sender,
address(this),
_rewardAmount
);
PROTOCOL_POOL_FEES = PROTOCOL_POOL_FEES.add(_rewardAmount);
}
/**
* @notice Function to return User's Push Holder weight based on amount being staked & current block number
**/
function _returnPushTokenWeight(
address _account,
uint256 _amount,
uint256 _atBlock
) internal view returns (uint256) {
return
_amount.mul(
_atBlock.sub(IPUSH(PUSH_TOKEN_ADDRESS).holderWeight(_account))
);
}
/**
* @notice Returns the epoch ID based on the start and end block numbers passed as input
**/
function lastEpochRelative(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
require(
_to >= _from,
"PushCoreV2:lastEpochRelative:: Relative Block Number Overflow"
);
return uint256((_to - _from) / epochDuration + 1);
}
/**
* @notice Calculates and returns the claimable reward amount for a user at a given EPOCH ID.
* @dev Formulae for reward calculation:
* rewards = ( userStakedWeight at Epoch(n) * avalailable rewards at EPOCH(n) ) / totalStakedWeight at EPOCH(n)
**/
function calculateEpochRewards(address _user, uint256 _epochId)
public
view
returns (uint256 rewards)
{
rewards = userFeesInfo[_user]
.epochToUserStakedWeight[_epochId]
.mul(epochRewards[_epochId])
.div(epochToTotalStakedWeight[_epochId]);
}
/**
* @notice Function to initialize the staking procedure in Core contract
* @dev Requires caller to deposit/stake 1 PUSH token to ensure staking pool is never zero.
**/
function initializeStake() external {
require(
genesisEpoch == 0,
"PushCoreV2::initializeStake: Already Initialized"
);
genesisEpoch = block.number;
lastEpochInitialized = genesisEpoch;
IERC20(PUSH_TOKEN_ADDRESS).safeTransferFrom(
msg.sender,
address(this),
1e18
);
_stake(address(this), 1e18);
}
/**
* @notice Function to allow users to stake in the protocol
* @dev Records total Amount staked so far by a particular user
* Triggers weight adjustents functions
* @param _amount represents amount of tokens to be staked
**/
function stake(uint256 _amount) external {
_stake(msg.sender, _amount);
emit Staked(msg.sender, _amount);
}
function _stake(address _staker, uint256 _amount) private {
uint256 currentEpoch = lastEpochRelative(genesisEpoch, block.number);
uint256 blockNumberToConsider = genesisEpoch.add(
epochDuration.mul(currentEpoch)
);
uint256 userWeight = _returnPushTokenWeight(
_staker,
_amount,
blockNumberToConsider
);
IERC20(PUSH_TOKEN_ADDRESS).safeTransferFrom(
msg.sender,
address(this),
_amount
);
userFeesInfo[_staker].stakedAmount =
userFeesInfo[_staker].stakedAmount +
_amount;
userFeesInfo[_staker].lastClaimedBlock = userFeesInfo[_staker]
.lastClaimedBlock == 0
? genesisEpoch
: userFeesInfo[_staker].lastClaimedBlock;
totalStakedAmount += _amount;
// Adjust user and total rewards, piggyback method
_adjustUserAndTotalStake(_staker, userWeight);
}
/**
* @notice Function to allow users to Unstake from the protocol
* @dev Allows stakers to claim rewards before unstaking their tokens
* Triggers weight adjustents functions
* Allows users to unstake all amount at once
**/
function unstake() external {
require(
block.number >
userFeesInfo[msg.sender].lastStakedBlock + epochDuration,
"PushCoreV2::unstake: Can't Unstake before 1 complete EPOCH"
);
require(
userFeesInfo[msg.sender].stakedAmount > 0,
"PushCoreV2::unstake: Invalid Caller"
);
harvestAll();
uint256 stakedAmount = userFeesInfo[msg.sender].stakedAmount;
IERC20(PUSH_TOKEN_ADDRESS).safeTransfer(msg.sender, stakedAmount);
// Adjust user and total rewards, piggyback method
_adjustUserAndTotalStake(
msg.sender,
-userFeesInfo[msg.sender].stakedWeight
);
userFeesInfo[msg.sender].stakedAmount = 0;
userFeesInfo[msg.sender].stakedWeight = 0;
totalStakedAmount -= stakedAmount;
emit Unstaked(msg.sender, stakedAmount);
}
/**
* @notice Allows users to harvest/claim their earned rewards from the protocol
* @dev Computes nextFromEpoch and currentEpoch and uses them as startEPoch and endEpoch respectively.
* Rewards are claculated from start epoch till endEpoch(currentEpoch - 1).
* Once calculated, user's total claimed rewards and nextFromEpoch details is updated.
**/
function harvestAll() public {
uint256 currentEpoch = lastEpochRelative(genesisEpoch, block.number);
uint256 rewards = harvest(msg.sender, currentEpoch - 1);
IERC20(PUSH_TOKEN_ADDRESS).safeTransfer(msg.sender, rewards);
}
/**
* @notice Allows paginated harvests for users between a particular number of epochs.
* @param _tillEpoch - the end epoch number till which rewards shall be counted.
* @dev _tillEpoch should never be equal to currentEpoch.
* Transfers rewards to caller and updates user's details.
**/
function harvestPaginated(uint256 _tillEpoch) external {
uint256 rewards = harvest(msg.sender, _tillEpoch);
IERC20(PUSH_TOKEN_ADDRESS).safeTransfer(msg.sender, rewards);
}
/**
* @notice Allows Push Governance to harvest/claim the earned rewards for its stake in the protocol
* @param _tillEpoch - the end epoch number till which rewards shall be counted.
* @dev only accessible by Push Admin
* Unlike other harvest functions, this is designed to transfer rewards to Push Governance.
**/
function daoHarvestPaginated(uint256 _tillEpoch) external {
onlyGovernance();
uint256 rewards = harvest(address(this), _tillEpoch);
IERC20(PUSH_TOKEN_ADDRESS).safeTransfer(governance, rewards);
}
/**
* @notice Internal harvest function that is called for all types of harvest procedure.
* @param _user - The user address for which the rewards will be calculated.
* @param _tillEpoch - the end epoch number till which rewards shall be counted.
* @dev _tillEpoch should never be equal to currentEpoch.
* Transfers rewards to caller and updates user's details.
**/
function harvest(address _user, uint256 _tillEpoch)
internal
returns (uint256 rewards)
{
IPUSH(PUSH_TOKEN_ADDRESS).resetHolderWeight(_user);
_adjustUserAndTotalStake(_user, 0);
uint256 currentEpoch = lastEpochRelative(genesisEpoch, block.number);
uint256 nextFromEpoch = lastEpochRelative(
genesisEpoch,
userFeesInfo[_user].lastClaimedBlock
);
require(
currentEpoch > _tillEpoch,
"PushCoreV2::harvestPaginated::Invalid _tillEpoch w.r.t currentEpoch"
);
require(
_tillEpoch >= nextFromEpoch,
"PushCoreV2::harvestPaginated::Invalid _tillEpoch w.r.t nextFromEpoch"
);
for (uint256 i = nextFromEpoch; i <= _tillEpoch; i++) {
uint256 claimableReward = calculateEpochRewards(_user, i);
rewards = rewards.add(claimableReward);
}
usersRewardsClaimed[_user] = usersRewardsClaimed[_user].add(rewards);
// set the lastClaimedBlock to blocknumer at the end of `_tillEpoch`
uint256 _epoch_to_block_number = genesisEpoch +
_tillEpoch *
epochDuration;
userFeesInfo[_user].lastClaimedBlock = _epoch_to_block_number;
emit RewardsHarvested(_user, rewards, nextFromEpoch, _tillEpoch);
}
/**
* @notice This functions helps in adjustment of user's as well as totalWeigts, both of which are imperative for reward calculation at a particular epoch.
* @dev Enables adjustments of user's stakedWeight, totalStakedWeight, epochToTotalStakedWeight as well as epochToTotalStakedWeight.
* triggers _setupEpochsReward() to adjust rewards for every epoch till the current epoch
*
* Includes 2 main cases of weight adjustments
* 1st Case: User stakes for the very first time:
* - Simply update userFeesInfo, totalStakedWeight and epochToTotalStakedWeight of currentEpoch
*
* 2nd Case: User is NOT staking for first time - 2 Subcases
* 2.1 Case: User stakes again but in Same Epoch
* - Increase user's stake and totalStakedWeight
* - Record the epochToUserStakedWeight for that epoch
* - Record the epochToTotalStakedWeight of that epoch
*
* 2.2 Case: - User stakes again but in different Epoch
* - Update the epochs between lastStakedEpoch & (currentEpoch - 1) with the old staked weight amounts
* - While updating epochs between lastStaked & current Epochs, if any epoch has zero value for totalStakedWeight, update it with current totalStakedWeight value of the protocol
* - For currentEpoch, initialize the epoch id with updated weight values for epochToUserStakedWeight & epochToTotalStakedWeight
*/
function _adjustUserAndTotalStake(address _user, uint256 _userWeight)