-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAthTraderCEX.sol
More file actions
842 lines (730 loc) · 24.4 KB
/
AthTraderCEX.sol
File metadata and controls
842 lines (730 loc) · 24.4 KB
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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
// 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-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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) {
return a + b;
}
/**
* @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) {
return a - b;
}
/**
* @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) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message 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,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// Link to bep20 token smart contract
interface IBEP20Token {
// Transfer tokens on behalf
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
// Transfer tokens
function transfer(address to, uint256 value)
external
returns (bool success);
// Approve tokens for spending
function approve(address spender, uint256 amount) external returns (bool);
// Returns user balance
function balanceOf(address user) external view returns (uint256 value);
//Returns token Decimals
function decimals() external view returns (uint256);
}
// Link to AthSatking contract
interface IATHLEVEL {
// Returns ath level of given address
function athLevel(address user) external view returns (uint256 level);
}
// Link to AthReferral contract
interface IREFERRAL {
// record referral Address
function recordReferral(address user, address referrer) external;
// record referral commission amount
function recordReferralCommission(address referrer, uint256 commission)
external;
// record referral commissions
function recordReferralCommissions(
address[] memory _referrers,
uint256[] memory _commissions
) external;
// Returns referred address
function getReferrer(address traderAddress, address user)
external
view
returns (address);
// Return true if its referral contract
function isReferralContract() external pure returns (bool);
// Add operator
function addOperator(address _operator) external;
}
contract AthTraderCEX {
using SafeMath for uint256;
// Timestamp of last payout
uint256 public lastPayoutAt;
// Address of AthTrader owner
address payable public owner;
// Address of trader account
address payable public trader;
IBEP20Token public usdtToken =
IBEP20Token(0x337610d27c682E347C9cD60BD4b3b107C9d34dDd);
IBEP20Token public bnbToken =
IBEP20Token(0x337610d27c682E347C9cD60BD4b3b107C9d34dDd);
// Address of AthStaking contract
address public immutable athLevel;
// Minimum contribution required to deposit
uint256 public immutable minDeposit = 10000000000000000000;
// Address of Ath Referral Contract
address public athReferral;
// Status of emergency withdraw
bool public isEmergencyWithdrawlEnabled;
// Deposit fee for followers
uint256 public depositFee = 500000000000000;
// Claim fee for trader
uint256 public claimFee = 500000000000000;
// Total deposit amount
uint256 public totalDeposit;
// Total collectedfee amount
uint256 public totalCollectedFee;
// List of claimable addresses
address[] public claimableAddresses;
// List of unrecorded referral payout addresses
address[] public unrecordedReferralAddresses;
/**
* @dev Returns deposit amount for given address
*/
mapping(address => uint256) public depositAmounts;
/**
* @dev Returns unrecorded referral payout for given address
*/
mapping(address => uint256) private unrecordedReferralPayouts;
/**
* @dev Returns fee in percentage for given level
*/
mapping(uint8 => uint8) public athLevelFee;
/**
* @dev Returns trader fee in percentage for given level
*/
mapping(uint8 => uint8) public athLevelTraderFee;
/**
* @dev Returns referral commission in percentage for given level
*/
mapping(uint8 => uint8) public athLevelReferralCommission;
/**
* @dev Fired in deposit() when tokens are deposited by user
*
* @param investor address of investor
* @param amount number of tokens deposited
*/
event Deposit(address indexed investor, uint256 amount);
/**
* @dev Fired in withdraw() and emergencyWithdraw() when tokens are withdrawn by user
*
* @param investor address of an investor
* @param amount number of tokens withdrawn
*/
event WithdrawDeposit(address indexed investor, uint256 amount);
/**
* @dev Fired in claim() when tokens are withdrawn by trader
*
* @param trader address of the trader
* @param amount number of tokens withdrawn
*/
event Claim(address trader, uint256 amount);
/**
* @dev Creates/deploys AthenaBank trading contract Version 1.0
*
* @param athStaking_ address of AthStaking smart contract
* @param athReferral_ address of athReferral smart contract
*/
constructor(
address athStaking_,
address athReferral_,
address payable trader_,
address athenaOwner
) {
// Setup smart contract internal state
owner = payable(athenaOwner);
athLevel = athStaking_;
athReferral = athReferral_;
trader = trader_;
lastPayoutAt = block.timestamp;
// Set initial fees
athLevelFee[0] = 50;
athLevelFee[1] = 30;
athLevelFee[2] = 25;
athLevelFee[3] = 20;
// Set trader fees
athLevelTraderFee[0] = 30;
athLevelTraderFee[1] = 50;
athLevelTraderFee[2] = 60;
athLevelTraderFee[3] = 70;
// Set initial referral commissions
athLevelReferralCommission[0] = 5;
athLevelReferralCommission[1] = 10;
athLevelReferralCommission[2] = 15;
athLevelReferralCommission[3] = 20;
}
// To check if accessed by an owner
modifier onlyOwner() {
isOwner();
_;
}
// To check if accessed by a trader
modifier onlyTrader() {
require(trader == msg.sender, "Not a trader");
_;
}
// To check if accessed by an owner or a tarder
modifier traderOrOwner() {
require(trader == msg.sender || owner == msg.sender, "Invalid access");
_;
}
/**
* @dev view function to check msg.sender is owner
*/
function isOwner() internal view {
require(owner == msg.sender, "Not an owner");
}
/**
* @dev Transfer ownership to given address
*
* @notice restricted function, should be called by owner only
* @param newOwner_ address of new owner
*/
function transferOwnership(address payable newOwner_) external onlyOwner {
// Update owner address
owner = newOwner_;
}
/**
* @dev Enables/disables emergency withdraw
*
* @notice restricted function, should be called by owner only
*/
function emergencyWithdrawSwitch() external onlyOwner {
// Trigger emergency withdraw switch
isEmergencyWithdrawlEnabled = !isEmergencyWithdrawlEnabled;
}
/**
* @dev Sets deposit and claim fees for followers and trader
*
* @notice restricted function, should be called by owner only
* @param depositFee_ new deposit fee
* @param claimFee_ new claim fee
*/
function setDepositAndClaimFees(uint256 depositFee_, uint256 claimFee_)
external
onlyOwner
{
depositFee = depositFee_;
claimFee = claimFee_;
}
/**
* @dev Sets fee for given level
*
* @notice restricted function, should be called by owner only
* @param level_ index of level
* @param fee_ fee defined in percentage for given level
*/
function setAthLevelFee(uint8[] memory level_, uint8[] memory fee_)
external
onlyOwner
{
require(level_.length == fee_.length, "Invalid input");
for (uint8 i; i < level_.length; i++) {
// Record fee for given level
athLevelFee[level_[i]] = fee_[i];
}
}
/**
* @dev Sets trader fee for given level
*
* @notice restricted function, should be called by owner only
* @param level_ index of level
* @param fee_ fee defined in percentage for given level
*/
function setAthLevelTraderFee(uint8[] memory level_, uint8[] memory fee_)
external
onlyOwner
{
require(level_.length == fee_.length, "Invalid input");
for (uint8 i; i < level_.length; i++) {
// Record fee for given level
athLevelTraderFee[level_[i]] = fee_[i];
}
}
/**
* @dev Sets referral commission rate for given level
*
* @notice restricted function, should be called by owner only
* @param level_ index of level
* @param commissionRate_ commission rate defined in percentage for given level
*/
function setAthLevelReferralCommission(
uint8[] memory level_,
uint8[] memory commissionRate_
) external onlyOwner {
require(level_.length == commissionRate_.length, "Invalid input");
for (uint8 i; i < level_.length; i++) {
// Record commission for given level
athLevelReferralCommission[level_[i]] = commissionRate_[i];
}
}
/**
* @dev Deposits tokens to the contract
*
* @param amount_ number of tokens to deposit
*/
function deposit(uint256 amount_) external payable {
// Check that the sender has sufficient USDT balance
require(
amount_ + depositAmounts[msg.sender] >= minDeposit,
"Amount smaller than minimum deposit"
);
// Check that the sender has sufficient USDT balance
require(
usdtToken.balanceOf(msg.sender) >= amount_,
"Insufficient USDT balance"
);
// Check that the sender has sufficient BNB balance
require(msg.value >= depositFee, "Insufficient BNB deposit fee");
// Transfer tokens to AthTrader contract
usdtToken.approve(msg.sender, amount_);
usdtToken.transferFrom(msg.sender, address(this), amount_);
// Transfer the fee amount from the sender to the owner
owner.transfer(depositFee);
// Record deposited amount of given address
depositAmounts[msg.sender] += amount_;
// Record total deposit
totalDeposit += amount_;
// Record total collected fee
totalCollectedFee += depositFee;
// Update last payout timestamp
setLastPayout();
// Emit an event
emit Deposit(msg.sender, amount_);
}
function testEvent(uint256 eventType) external {
if (eventType == 0) {
// Emit an event
emit Deposit(msg.sender, 1234);
}
if (eventType == 1) {
// Emit an event
emit WithdrawDeposit(msg.sender, 1234);
}
if (eventType == 2) {
// Emit an event
emit Claim(trader, 1234);
}
}
/**
* @dev Returns deposited amount for given address
*
* @param investor_ investor address
*/
function getDepositedAmount(address investor_)
external
view
returns (uint256 depositedAmount_)
{
depositedAmount_ = depositAmounts[investor_];
return depositedAmount_;
}
/**
* @dev Allows to withdraw deposited tokens
*/
function withdraw(uint256 amount_) external onlyOwner {
require(
depositAmounts[msg.sender] < amount_,
"No enough funds to withdraw!"
);
// Get deposited amount of given address
uint256 _amount = depositAmounts[msg.sender];
// Transfer deposited amount to given address
usdtToken.transfer(msg.sender, _amount);
// Remove deposited amount data for given address
depositAmounts[msg.sender] = 0;
// Emit an event
emit WithdrawDeposit(msg.sender, _amount);
}
/**
* @dev Allows to set the last payout timestamp
*
* @notice restricted function, should be called by owner only
*/
function setLastPayout() internal {
lastPayoutAt = block.timestamp;
}
/**
* @dev Allows to record the last payout
*
* @notice restricted function, should be called by owner only
*/
function recordPayout(
address[] memory addresses_,
uint256[] memory profits_
) external onlyTrader {
// Check if we are currently allowed to record payouts
// require(
// lastPayoutAt + 30 days <= block.timestamp,
// "No enough time has passed since last payout!"
// );
// Initialize variable to store Athena payout data
uint256 _totalAthenaPayout;
uint256 _totalClaimable;
// Iterate through every follower address
for (uint256 i = 0; i < addresses_.length; i++) {
address _followerAddress = addresses_[i];
uint256 _commissionFee = calculateFollowerFee(
_followerAddress,
profits_[i]
);
// Update deposit for follower
depositAmounts[_followerAddress] =
depositAmounts[_followerAddress] -
_commissionFee;
// Calculate trader and Athena payout
uint256 _currTraderPayout = calculateTraderFee(_commissionFee);
uint256 _currAthenaPayout = _commissionFee - _currTraderPayout;
// Get follower's first-level referrer
address referrer = IREFERRAL(athReferral).getReferrer(
address(this),
_followerAddress
);
if (referrer != address(0)) {
// Add address to current referrers list if needed
if (unrecordedReferralPayouts[referrer] == 0) {
unrecordedReferralAddresses.push(referrer);
}
// Calculate payout for follower's first-level referrer
uint256 _firstReferrerPayout = calculateReferralCommission(
referrer,
_currAthenaPayout
);
// Record payout for follower's first-level referrer
unrecordedReferralPayouts[referrer] += _firstReferrerPayout;
// Get follower's second-level referrer
address secondReferrer = IREFERRAL(athReferral).getReferrer(
address(this),
referrer
);
if (secondReferrer != address(0)) {
// Add address to current referrers list if needed
if (unrecordedReferralPayouts[secondReferrer] == 0) {
unrecordedReferralAddresses.push(secondReferrer);
}
// Calculate payout for follower's second-level referrer
uint256 _secondReferrerPayout = calculateReferralCommission(
secondReferrer,
_currAthenaPayout
);
// Record payout for follower's second-level referrer
unrecordedReferralPayouts[
secondReferrer
] += _secondReferrerPayout;
// Subtract second-level referral fee from Athena's payout
_currAthenaPayout -= _secondReferrerPayout;
}
// Subtract first-level referral fee from Athena's payout
_currAthenaPayout -= _firstReferrerPayout;
}
// Update total claimable amount for trader
_totalClaimable += _currTraderPayout;
// Update total payout for Athena
_totalAthenaPayout += _currAthenaPayout;
}
// Transfer tokens to Athena
usdtToken.transfer(owner, _totalAthenaPayout);
uint256[] memory _unrecordedReferralPayouts = new uint256[](
unrecordedReferralAddresses.length
);
// Iterate through every referrer address
for (uint256 i = 0; i < unrecordedReferralAddresses.length; i++) {
_unrecordedReferralPayouts[i] = unrecordedReferralPayouts[
unrecordedReferralAddresses[i]
];
unrecordedReferralPayouts[unrecordedReferralAddresses[i]] = 0;
}
// Send data to referral contract
IREFERRAL(athReferral).recordReferralCommissions(
unrecordedReferralAddresses,
_unrecordedReferralPayouts
);
if (_totalClaimable > 0) {
// Send tokens to the trader
usdtToken.transfer(trader, _totalClaimable);
// Emit an event
emit Claim(msg.sender, _totalClaimable);
// Reset claimable amount
_totalClaimable = 0;
}
}
/**
* @dev Returns trader fee
* @param amount_ amount from which to calculate
*/
function calculateTraderFee(uint256 amount_) public view returns (uint256) {
return
(athLevelTraderFee[uint8(IATHLEVEL(athLevel).athLevel(trader))] *
amount_).div(100);
}
/**
* @dev Returns trader fee
*
* @param follower_ follower address
* @param amount_ amount from which to calculate
*/
function calculateFollowerFee(address follower_, uint256 amount_)
internal
view
returns (uint256)
{
return
(athLevelFee[uint8(IATHLEVEL(athLevel).athLevel(follower_))] *
amount_).div(100);
}
/**
* @dev Returns referral commission
*
* @param referrer_ referrer address
* @param amount_ amount from which to calculate
*/
function calculateReferralCommission(address referrer_, uint256 amount_)
internal
view
returns (uint256)
{
return
(athLevelReferralCommission[
uint8(IATHLEVEL(athLevel).athLevel(referrer_))
] * amount_).div(100);
}
/**
* @dev Activates emergency withdraw
*
* @notice restricted function, should be called by owner only
*/
function emergencyWithdraw() external onlyOwner {
// Trigger emergency withdraw
usdtToken.transfer(owner, usdtToken.balanceOf(address(this)));
bnbToken.transfer(owner, bnbToken.balanceOf(address(this)));
}
function recordReferral(address referrer_) public {
IREFERRAL(athReferral).recordReferral(msg.sender, referrer_);
}
}