-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlattened_strategy_factory.sol
779 lines (665 loc) · 22.2 KB
/
Flattened_strategy_factory.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
// File: contracts/interfaces/IPredictionMarket.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.0;
interface IPredictionMarket {
function conditions(uint256 _index)
external
view
returns (
string memory market,
address oracle,
int256 triggerPrice,
uint256 settlementTime,
bool isSettled,
int256 settledPrice,
address lowBetToken,
address highBetToken,
uint256 totalStakedAbove,
uint256 totalStakedBelow
);
function prepareCondition(
address _oracle,
uint256 _settlementTime,
int256 _triggerPrice,
string memory _market
) external;
function probabilityRatio(uint256 _conditionIndex)
external
view
returns (uint256 aboveProbabilityRatio, uint256 belowProbabilityRatio);
function userTotalETHStaked(uint256 _conditionIndex, address userAddress)
external
view
returns (uint256 totalEthStaked);
function betOnCondition(uint256 _conditionIndex, uint8 _prediction)
external
payable;
function settleCondition(uint256 _conditionIndex) external;
function claim(uint256 _conditionIndex) external;
function calculateClaimAmount(uint256 _conditionIndex)
external
returns (
uint8 winningSide,
uint256 userstake,
uint256 totalWinnerRedeemable,
uint256 platformFees
);
function getPerUserClaimAmount(uint256 _conditionIndex)
external
returns (uint8, uint256);
function getBalance(uint256 _conditionIndex, address _user)
external
view
returns (uint256 LBTBalance, uint256 HBTBalance);
}
// File: contracts/interfaces/IStrategyFactory.sol
pragma solidity 0.8.0;
interface IStrategyFactory {
function predictionMarket() external view returns (address);
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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.
*
* IMPORTANT: 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/StrategyStorage.sol
pragma solidity 0.8.0;
contract StrategyStorage {
//strategy details
StrategyStatus public status;
IStrategyFactory public strategyFactory;
uint256 internal constant PERCENTAGE_MULTIPLIER = 10000;
uint256 internal constant MAX_BET_PERCENTAGE = 50000;
string public strategyName;
address payable public trader;
address payable public operator;
uint256 public initialTraderFunds;
uint256 public traderClaimedAmount;
uint256 public userPortfolio;
uint256 public traderPortfolio;
uint256 public depositPeriod;
uint256 public tradingPeriod;
//Fees Percentage
//PERCENTAGE_MULTIPLIER decimals
uint256 public constant FEE_PERCENTAGE = 2000; // 20%
uint256 public traderFees;
bool isFeeClaimed;
enum StrategyStatus {
ACTIVE,
INACTIVE
}
uint256 public totalUserActiveMarkets;
uint256 public totalTraderActiveMarkets;
uint256 public totalUserFunds;
struct User {
uint256 depositAmount;
uint256 claimedAmount;
bool exited;
}
struct Market {
uint256 userLowBets;
uint256 userHighBets;
uint256 traderLowBets;
uint256 traderHighBets;
bool isClaimed;
uint256 amountClaimed;
}
//user details]
uint256 public totalUsers;
mapping(address => User) public userInfo;
mapping(uint256 => Market) public markets;
//conditionIndex -> 1 -> users
//conditionIndex -> 0 -> trader
mapping(uint256 => mapping(uint8 => bool)) public isBetPlaced;
event StrategyFollowed(address follower, uint256 amount);
event StrategyUnfollowed(
address follower,
uint256 amountClaimed,
string unfollowType
);
event BetPlaced(uint256 conditionIndex, uint8 side, uint256 totalAmount);
event BetClaimed(
uint256 conditionIndex,
uint8 winningSide,
uint256 amountReceived
);
event StrategyInactive();
event TraderClaimed(uint256 amountClaimed);
event TraderFeeClaimed(uint256 traderFees);
event AddedTraderFunds(address trader, uint256 amount);
}
// File: contracts/Strategy.sol
pragma solidity 0.8.0;
contract Strategy is StrategyStorage {
modifier isStrategyActive() {
require(
status == StrategyStatus.ACTIVE,
"Strategy::isStrategyActive: STRATEGY_INACTIVE"
);
_;
}
modifier onlyTrader() {
require(msg.sender == trader, "Strategy::onlyTrader: INVALID_TRADER");
_;
}
modifier onlyUser() {
require(
userInfo[msg.sender].depositAmount > 0,
"Strategy::onlyTrader: INVALID_USER"
);
_;
}
modifier inDepositPeriod() {
require(
depositPeriod >= block.timestamp,
"Strategy: DEPOSIT_PERIOD_ENDED"
);
_;
}
modifier inTradingPeriod() {
require(
tradingPeriod >= block.timestamp && depositPeriod < block.timestamp,
"Strategy: TRADING_PERIOD_NOT_STARTED"
);
_;
}
modifier tradingPeriodEnded() {
require(
tradingPeriod < block.timestamp,
"Strategy: TRADING_PERIOD_ACTIVE"
);
_;
}
constructor(
string memory _name,
address payable _trader,
uint256 _depositPeriod, //time remaining from now
uint256 _tradingPeriod, //deposit time + trading period
address payable _operator
) payable {
require(
_trader != address(0),
"Strategy::constructor:INVALID TRADER ADDRESS."
);
require(msg.value > 0, "Strategy::constructor: ZERO_FUNDS");
strategyFactory = IStrategyFactory(msg.sender);
strategyName = _name;
trader = _trader;
initialTraderFunds = msg.value;
traderPortfolio = msg.value;
operator = _operator;
depositPeriod = block.timestamp + _depositPeriod;
tradingPeriod = depositPeriod + _tradingPeriod;
status = StrategyStatus.ACTIVE;
}
function follow() external payable isStrategyActive inDepositPeriod {
User storage user = userInfo[msg.sender];
require(msg.value > 0, "Strategy::follow: ZERO_FUNDS");
require(user.depositAmount == 0, "Strategy::follow: ALREADY_FOLLOWING");
totalUserFunds += msg.value;
totalUsers++;
userPortfolio = totalUserFunds;
user.depositAmount = msg.value;
emit StrategyFollowed(msg.sender, msg.value);
}
function deposit()
external
payable
isStrategyActive
inDepositPeriod
onlyTrader
{
require(msg.value > 0, "Strategy::deposit: ZERO_FUNDS");
initialTraderFunds += msg.value;
traderPortfolio += msg.value;
emit AddedTraderFunds(msg.sender, msg.value);
}
/**--------------------------BET PLACE RELATED FUNCTIONS-------------------------- */
function placeBet(
uint256 _conditionIndex,
uint8 _side,
uint256 _amount
) external isStrategyActive onlyTrader {
require(
!_isMarketSettled(_conditionIndex),
"Strategy:placeBet:: MARKET_SETTLED"
);
require(
traderPortfolio >= _amount && _amount > 0,
"Strategy:placeBet:: INVALID_BET_AMOUNT"
);
uint256 betAmount;
if (
tradingPeriod >= block.timestamp && depositPeriod < block.timestamp
) {
betAmount = _betInTradingPeriod(_amount, _side, _conditionIndex);
} else {
betAmount = _betInDepositPeriod(_amount, _side, _conditionIndex);
}
_getPredictionMarket().betOnCondition{value: betAmount}(
_conditionIndex,
_side
);
emit BetPlaced(_conditionIndex, _side, betAmount);
}
//0 - deposit and claiming period
//1 - trading
function _updateActiveMarkets(uint256 _conditionIndex, uint8 _scenario)
internal
{
if (_scenario == 1) {
if (!isBetPlaced[_conditionIndex][1]) {
isBetPlaced[_conditionIndex][1] = true;
totalUserActiveMarkets++;
}
}
if (!isBetPlaced[_conditionIndex][0]) {
isBetPlaced[_conditionIndex][0] = true;
totalTraderActiveMarkets++;
}
}
function _betInDepositPeriod(
uint256 _amount,
uint8 _side,
uint256 _conditionIndex
) internal returns (uint256 betAmount) {
betAmount = _amount;
traderPortfolio -= _amount;
Market storage market = markets[_conditionIndex];
if (_side == 0) {
market.traderLowBets += _amount;
} else {
market.traderHighBets += _amount;
}
_updateActiveMarkets(_conditionIndex, 0);
}
function _betInTradingPeriod(
uint256 _amount,
uint8 _side,
uint256 _conditionIndex
) internal inTradingPeriod returns (uint256 betAmount) {
betAmount = _getBetAmount(_amount);
require(betAmount <= userPortfolio, "Strategy:placeBet OUT_OF_FUNDS");
userPortfolio -= betAmount;
traderPortfolio -= _amount;
Market storage market = markets[_conditionIndex];
if (_side == 0) {
market.userLowBets += betAmount;
market.traderLowBets += _amount;
} else {
market.userHighBets += betAmount;
market.traderHighBets += _amount;
}
_updateActiveMarkets(_conditionIndex, 1);
betAmount += _amount;
}
function _getBetAmount(uint256 _amount)
internal
view
returns (uint256 betAmount)
{
uint256 percentage = _getPercentage(_amount);
require(
percentage < MAX_BET_PERCENTAGE,
"Strategy::placeBet:: AMOUNT_EXCEEDS_5_PERCENTAGE"
);
betAmount =
(totalUserFunds * percentage) /
(PERCENTAGE_MULTIPLIER * 100);
//safety check
require(betAmount < totalUserFunds);
}
function _getPercentage(uint256 _amount)
internal
view
returns (uint256 percentage)
{
percentage = (_amount * 100 * PERCENTAGE_MULTIPLIER) / traderPortfolio;
}
/**--------------------------BET CLAIM RELATED FUNCTIONS-------------------------- */
function claimBet(uint256 _conditionIndex) external {
Market storage market = markets[_conditionIndex];
require(
isBetPlaced[_conditionIndex][0] || isBetPlaced[_conditionIndex][1],
"Strategy:claimBet:: NO_BETS"
);
require(
_isMarketSettled(_conditionIndex),
"Strategy:claimBet:: MARKET_ACTIVE"
);
require(!market.isClaimed, "Strategy:claimBet:: ALREADY_CLAIMED");
uint256 totalLowBets = market.userLowBets + market.traderLowBets;
uint256 totalHighBets = market.userHighBets + market.traderHighBets;
if (totalLowBets == 0 && totalHighBets == 0) return;
if (isBetPlaced[_conditionIndex][1]) totalUserActiveMarkets--;
totalTraderActiveMarkets--;
market.isClaimed = true;
uint256 initialAmount = address(this).balance;
_getPredictionMarket().claim(_conditionIndex);
market.amountClaimed = address(this).balance - initialAmount;
uint8 winningSide = _getWinningSide(_conditionIndex);
uint256 userClaim;
if (winningSide == 1) {
userClaim = _updatePortfolio(
market.amountClaimed,
totalHighBets,
market.userHighBets
);
} else {
userClaim = _updatePortfolio(
market.amountClaimed,
totalLowBets,
market.userLowBets
);
}
emit BetClaimed(_conditionIndex, winningSide, userClaim);
}
function _updatePortfolio(
uint256 _amountClaimed,
uint256 _totalBets,
uint256 _userBets
) internal returns (uint256 userClaim) {
if (_totalBets == 0) return 0;
userClaim = (_amountClaimed * _userBets) / _totalBets;
userPortfolio += userClaim;
traderPortfolio += (_amountClaimed - userClaim);
}
function _getPredictionMarket()
internal
view
returns (IPredictionMarket predictionMarket)
{
predictionMarket = IPredictionMarket(
strategyFactory.predictionMarket()
);
}
/**--------------------------MARKET RELATED VIEW FUNCTIONS-------------------------- */
function _isMarketSettled(uint256 _conditionIndex)
internal
view
returns (bool)
{
(, , , uint256 settlementTime, , , , , , ) = _getPredictionMarket()
.conditions(_conditionIndex);
if (settlementTime > block.timestamp) return false;
return true;
}
function _getWinningSide(uint256 _conditionIndex)
internal
view
returns (uint8)
{
(
,
,
int256 triggerPrice,
,
,
int256 settledPrice,
,
,
,
) = _getPredictionMarket().conditions(_conditionIndex);
if (triggerPrice >= settledPrice) return 0;
return 1;
}
/**--------------------------UNFOLLOW AND CLAIMS-------------------------- */
function unfollow() external onlyUser {
require(
depositPeriod >= block.timestamp || tradingPeriod < block.timestamp,
"Strategy:unfollow:: CANNOT_CLAIM_IN_TRADING_PERIOD"
);
if (depositPeriod >= block.timestamp) {
_returnUserFunds();
} else {
_unfollow();
}
}
function _returnUserFunds() internal {
User storage user = userInfo[msg.sender];
require(user.depositAmount != 0, "Strategy:unfollow:: ALREADY_CLAIMED");
uint256 toClaim = getUserClaimAmount(msg.sender);
totalUserFunds -= user.depositAmount;
userPortfolio = totalUserFunds;
user.depositAmount = 0;
payable(msg.sender).transfer(toClaim);
emit StrategyUnfollowed(msg.sender, toClaim, "BEFORE_TRADE");
}
function _unfollow() internal {
require(
totalUserActiveMarkets == 0,
"Strategy:unfollow:: MARKET_ACTIVE"
);
User storage user = userInfo[msg.sender];
require(!user.exited, "Strategy:unfollow:: ALREADY_CLAIMED");
uint256 toClaim = getUserClaimAmount(msg.sender);
user.exited = true;
user.claimedAmount = toClaim;
payable(msg.sender).transfer(toClaim);
emit StrategyUnfollowed(msg.sender, toClaim, "AFTER_TRADE");
}
function getUserClaimAmount(address _user)
public
view
returns (uint256 amount)
{
User memory userDetails = userInfo[_user];
if (userPortfolio > totalUserFunds) {
uint256 profit = ((userPortfolio - getTraderFees()) *
userDetails.depositAmount) / totalUserFunds;
amount = userDetails.depositAmount + profit;
} else if (userPortfolio == totalUserFunds) {
amount = userDetails.depositAmount;
} else {
uint256 loss = (userPortfolio * userDetails.depositAmount) /
totalUserFunds;
amount = userDetails.depositAmount - loss;
}
}
function getTraderFees() public view returns (uint256 fees) {
fees = 0;
if (userPortfolio > totalUserFunds) {
fees = (userPortfolio * FEE_PERCENTAGE) / PERCENTAGE_MULTIPLIER;
}
}
function removeTraderFund() external tradingPeriodEnded onlyTrader {
require(
totalTraderActiveMarkets == 0,
"Strategy:removeTraderFund:: MARKET_ACTIVE"
);
require(
traderClaimedAmount == 0,
"Strategy:removeTraderFund:: ALREADY_CLAIMED"
);
traderClaimedAmount = traderPortfolio;
traderPortfolio = 0;
initialTraderFunds = 0;
status = StrategyStatus.INACTIVE;
_claimFee();
_transferETH(trader, traderFees + traderClaimedAmount);
emit StrategyInactive();
emit TraderFeeClaimed(traderFees);
emit TraderClaimed(traderClaimedAmount);
}
// function claimFees() public onlyTrader {
// require(
// totalUserActiveMarkets == 0,
// "Strategy:removeTraderFund:: MARKET_ACTIVE"
// );
// _claimFee();
// }
function _claimFee() internal {
require(!isFeeClaimed, "Strategy:claimFees:: ALREADY_CLAIMED");
isFeeClaimed = true;
traderFees = getTraderFees();
}
function _transferETH(address payable _to, uint256 _amount) internal {
require(
address(this).balance >= _amount,
"Strategy:_transferETH:: AMOUNT_EXCEED_STRATEGY_BALANCE"
);
_to.transfer(_amount);
}
function inCaseTokensGetStuck(address _token) external {
require(
operator == msg.sender,
"Strategy:inCaseTokensGetStuck:: INVALID_OPERATOR"
);
if (_token != address(0)) {
IERC20 token = IERC20(_token);
token.transfer(operator, token.balanceOf(address(this)));
} else {
operator.transfer(address(this).balance);
status = StrategyStatus.INACTIVE;
emit StrategyInactive();
}
}
receive() external payable {
require(
address(_getPredictionMarket()) == msg.sender,
"Strategy:receive:: INVALID_ETH_SOURCE"
);
}
}
// File: contracts/StrategyFactory.sol
pragma solidity 0.8.0;
contract StrategyFactory {
address public predictionMarket;
address payable public operator;
uint256 public strategyID;
//strategyID -> strategy
mapping(uint256 => address) public strategies;
mapping(address => uint256[]) public traderStrategies;
mapping(address => bool) public isStrategy;
event StartegyCreated(
address traderAddress,
string strategyName,
uint256 id,
uint256 amount,
address strategyAddress
);
constructor(address _predictionMarket) {
require(
_predictionMarket != address(0),
"StrategyFactory::constructor: INVALID_PREDICTION_MARKET_ADDRESS."
);
predictionMarket = _predictionMarket;
operator = payable(msg.sender);
}
function updatePredictionMarket(address _predictionMarket) external {
require(
msg.sender == operator,
"StrategyFactory:updatePredictionMarket:: INVALID_SENDER"
);
require(
_predictionMarket != address(0) ||
_predictionMarket != predictionMarket,
"StrategyFactory:updatePredictionMarket:: INVALID_ADDRESS"
);
predictionMarket = _predictionMarket;
}
function createStrategy(
string memory _name,
uint256 _depositPeriod,
uint256 _tradingPeriod
) external payable {
require(
msg.value > 0,
"StrategyFactory::createStrategy: ZERO_DEPOSIT_FUND"
);
strategyID = strategyID + 1;
traderStrategies[msg.sender].push(strategyID);
Strategy strategy = new Strategy{value: msg.value}(
_name,
payable(msg.sender),
_depositPeriod,
_tradingPeriod,
operator
);
strategies[strategyID] = address(strategy);
isStrategy[address(strategy)] = true;
emit StartegyCreated(
msg.sender,
_name,
strategyID,
msg.value,
address(strategy)
);
}
}