-
Notifications
You must be signed in to change notification settings - Fork 8
/
Zethr.sol
1321 lines (1058 loc) · 41.6 KB
/
Zethr.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.4.23;
/**
https://zethr.io https://zethr.io https://zethr.io https://zethr.io https://zethr.io
███████╗███████╗████████╗██╗ ██╗██████╗
╚══███╔╝██╔════╝╚══██╔══╝██║ ██║██╔══██╗
███╔╝ █████╗ ██║ ███████║██████╔╝
███╔╝ ██╔══╝ ██║ ██╔══██║██╔══██╗
███████╗███████╗ ██║ ██║ ██║██║ ██║
╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝
.------..------. .------..------..------. .------..------..------..------..------.
|B.--. ||E.--. |.-. |T.--. ||H.--. ||E.--. |.-. |H.--. ||O.--. ||U.--. ||S.--. ||E.--. |
| :(): || (\/) (( )) | :/\: || :/\: || (\/) (( )) | :/\: || :/\: || (\/) || :/\: || (\/) |
| ()() || :\/: |'-.-.| (__) || (__) || :\/: |'-.-.| (__) || :\/: || :\/: || :\/: || :\/: |
| '--'B|| '--'E| (( )) '--'T|| '--'H|| '--'E| (( )) '--'H|| '--'O|| '--'U|| '--'S|| '--'E|
`------'`------' '-'`------'`------'`------' '-'`------'`------'`------'`------'`------'
An interactive, variable-dividend rate contract with an ICO-capped price floor and collectibles.
Credits
=======
Analysis:
blurr
Randall
Contract Developers:
Etherguy
klob
Norsefire
Front-End Design:
cryptodude
oguzhanox
TropicalRogue
**/
contract Zethr {
using SafeMath for uint;
/*=================================
= MODIFIERS =
=================================*/
modifier onlyHolders() {
require(myFrontEndTokens() > 0);
_;
}
modifier dividendHolder() {
require(myDividends(true) > 0);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint incomingEthereum,
uint tokensMinted,
address indexed referredBy
);
event UserDividendRate(
address user,
uint divRate
);
event onTokenSell(
address indexed customerAddress,
uint tokensBurned,
uint ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint ethereumReinvested,
uint tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint ethereumWithdrawn
);
event Transfer(
address indexed from,
address indexed to,
uint tokens
);
event Approval(
address indexed tokenOwner,
address indexed spender,
uint tokens
);
event Allocation(
uint toBankRoll,
uint toReferrer,
uint toTokenHolders,
uint toDivCardHolders,
uint forTokens
);
event Referral(
address referrer,
uint amountReceived
);
/*=====================================
= CONSTANTS =
=====================================*/
uint8 constant public decimals = 18;
uint constant internal tokenPriceInitial_ = 0.000653 ether;
uint constant internal magnitude = 2**64;
uint constant internal icoHardCap = 250 ether;
uint constant internal addressICOLimit = 1 ether;
uint constant internal icoMinBuyIn = 0.1 finney;
uint constant internal icoMaxGasPrice = 50000000000 wei;
uint constant internal MULTIPLIER = 9615;
uint constant internal MIN_ETH_BUYIN = 0.0001 ether;
uint constant internal MIN_TOKEN_SELL_AMOUNT = 0.0001 ether;
uint constant internal MIN_TOKEN_TRANSFER = 1e10;
uint constant internal referrer_percentage = 25;
uint public stakingRequirement = 100e18;
/*================================
= CONFIGURABLES =
================================*/
string public name = "Zethr";
string public symbol = "ZTH";
bytes32 constant public icoHashedPass = bytes32(0x5ddcde33b94b19bdef79dd9ea75be591942b9ec78286d64b44a356280fb6a262);
address internal bankrollAddress;
ZethrDividendCards divCardContract;
/*================================
= DATASETS =
================================*/
// Tracks front & backend tokens
mapping(address => uint) internal frontTokenBalanceLedger_;
mapping(address => uint) internal dividendTokenBalanceLedger_;
mapping(address =>
mapping (address => uint))
public allowed;
// Tracks dividend rates for users
mapping(uint8 => bool) internal validDividendRates_;
mapping(address => bool) internal userSelectedRate;
mapping(address => uint8) internal userDividendRate;
// Payout tracking
mapping(address => uint) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
// ICO per-address limit tracking
mapping(address => uint) internal ICOBuyIn;
uint public tokensMintedDuringICO;
uint public ethInvestedDuringICO;
uint public currentEthInvested;
uint internal tokenSupply = 0;
uint internal divTokenSupply = 0;
uint internal profitPerDivToken;
mapping(address => bool) public administrators;
bool public icoPhase = false;
bool public regularPhase = false;
uint icoOpenTime;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
constructor (address _bankrollAddress, address _divCardAddress)
public
{
bankrollAddress = _bankrollAddress;
divCardContract = ZethrDividendCards(_divCardAddress);
administrators[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true; // Norsefire
administrators[0x11e52c75998fe2E7928B191bfc5B25937Ca16741] = true; // klob
administrators[0x20C945800de43394F70D789874a4daC9cFA57451] = true; // Etherguy
administrators[0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB] = true; // blurr
administrators[0x8537aa2911b193e5B377938A723D805bb0865670] = true; // oguzhanox
administrators[0x9D221b2100CbE5F05a0d2048E2556a6Df6f9a6C3] = true; // Randall
administrators[0xDa83156106c4dba7A26E9bF2Ca91E273350aa551] = true; // TropicalRogue
administrators[0x71009e9E4e5e68e77ECc7ef2f2E95cbD98c6E696] = true; // cryptodude
administrators[msg.sender] = true; // Helps with debugging!
validDividendRates_[2] = true;
validDividendRates_[5] = true;
validDividendRates_[10] = true;
validDividendRates_[15] = true;
validDividendRates_[20] = true;
validDividendRates_[25] = true;
validDividendRates_[33] = true;
userSelectedRate[bankrollAddress] = true;
userDividendRate[bankrollAddress] = 33;
}
/**
* Same as buy, but explicitly sets your dividend percentage.
* If this has been called before, it will update your `default' dividend
* percentage for regular buy transactions going forward.
*/
function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string providedUnhashedPass)
public
payable
returns (uint)
{
require(icoPhase || regularPhase);
if (icoPhase) {
// Anti-bot measures - not perfect, but should help some.
bytes32 hashedProvidedPass = keccak256(providedUnhashedPass);
require(hashedProvidedPass == icoHashedPass || msg.sender == bankrollAddress);
uint gasPrice = tx.gasprice;
// Prevents ICO buyers from getting substantially burned if the ICO is reached
// before their transaction is processed.
require(gasPrice <= icoMaxGasPrice && ethInvestedDuringICO <= icoHardCap);
}
// Dividend percentage should be a currently accepted value.
require (validDividendRates_[_divChoice]);
// Set the dividend fee percentage denominator.
userSelectedRate[msg.sender] = true;
userDividendRate[msg.sender] = _divChoice;
emit UserDividendRate(msg.sender, _divChoice);
// Finally, purchase tokens.
purchaseTokens(msg.value, _referredBy);
}
// All buys except for the above one require regular phase.
function buy(address _referredBy)
public
payable
returns(uint)
{
require(regularPhase);
address _customerAddress = msg.sender;
require (userSelectedRate[_customerAddress]);
purchaseTokens(msg.value, _referredBy);
}
function buyAndTransfer(address _referredBy, address target)
public
payable
{
bytes memory empty;
buyAndTransfer(_referredBy,target, empty, 20);
}
function buyAndTransfer(address _referredBy, address target, bytes _data)
public
payable
{
buyAndTransfer(_referredBy, target, _data, 20);
}
// Overload
function buyAndTransfer(address _referredBy, address target, bytes _data, uint8 divChoice)
public
payable
{
require(regularPhase);
address _customerAddress = msg.sender;
uint256 frontendBalance = frontTokenBalanceLedger_[msg.sender];
if (userSelectedRate[_customerAddress] && divChoice == 0) {
purchaseTokens(msg.value, _referredBy);
} else {
buyAndSetDivPercentage(_referredBy, divChoice, "0x0");
}
uint256 difference = SafeMath.sub(frontTokenBalanceLedger_[msg.sender], frontendBalance);
transferTo(msg.sender, target, difference, _data);
}
// Fallback function only works during regular phase - part of anti-bot protection.
function()
payable
public
{
/**
/ If the user has previously set a dividend rate, sending
/ Ether directly to the contract simply purchases more at
/ the most recent rate. If this is their first time, they
/ are automatically placed into the 20% rate `bucket'.
**/
require(regularPhase);
address _customerAddress = msg.sender;
if (userSelectedRate[_customerAddress]) {
purchaseTokens(msg.value, 0x0);
} else {
buyAndSetDivPercentage(0x0, 20, "0x0");
}
}
function reinvest()
dividendHolder()
public
{
require(regularPhase);
uint _dividends = myDividends(false);
// Pay out requisite `virtual' dividends.
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint _tokens = purchaseTokens(_dividends, 0x0);
// Fire logging event.
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit()
public
{
require(regularPhase);
// Retrieve token balance for caller, then sell them all.
address _customerAddress = msg.sender;
uint _tokens = frontTokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw(_customerAddress);
}
function withdraw(address _recipient)
dividendHolder()
public
{
require(regularPhase);
// Setup data
address _customerAddress = msg.sender;
uint _dividends = myDividends(false);
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
if (_recipient == address(0x0)){
_recipient = msg.sender;
}
_recipient.transfer(_dividends);
// Fire logging event.
emit onWithdraw(_recipient, _dividends);
}
// Sells front-end tokens.
// Logic concerning step-pricing of tokens pre/post-ICO is encapsulated in tokensToEthereum_.
function sell(uint _amountOfTokens)
onlyHolders()
public
{
// No selling during the ICO. You don't get to flip that fast, sorry!
require(!icoPhase);
require(regularPhase);
require(_amountOfTokens <= frontTokenBalanceLedger_[msg.sender]);
uint _frontEndTokensToBurn = _amountOfTokens;
// Calculate how many dividend tokens this action burns.
// Computed as the caller's average dividend rate multiplied by the number of front-end tokens held.
// As an additional guard, we ensure that the dividend rate is between 2 and 50 inclusive.
uint userDivRate = getUserAverageDividendRate(msg.sender);
require ((2*magnitude) <= userDivRate && (50*magnitude) >= userDivRate );
uint _divTokensToBurn = (_frontEndTokensToBurn.mul(userDivRate)).div(magnitude);
// Calculate ethereum received before dividends
uint _ethereum = tokensToEthereum_(_frontEndTokensToBurn);
if (_ethereum > currentEthInvested){
// Well, congratulations, you've emptied the coffers.
currentEthInvested = 0;
} else { currentEthInvested = currentEthInvested - _ethereum; }
// Calculate dividends generated from the sale.
uint _dividends = (_ethereum.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude);
// Calculate Ethereum receivable net of dividends.
uint _taxedEthereum = _ethereum.sub(_dividends);
// Burn the sold tokens (both front-end and back-end variants).
tokenSupply = tokenSupply.sub(_frontEndTokensToBurn);
divTokenSupply = divTokenSupply.sub(_divTokensToBurn);
// Subtract the token balances for the seller
frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].sub(_frontEndTokensToBurn);
dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].sub(_divTokensToBurn);
// Update dividends tracker
int256 _updatedPayouts = (int256) (profitPerDivToken * _divTokensToBurn + (_taxedEthereum * magnitude));
payoutsTo_[msg.sender] -= _updatedPayouts;
// Let's avoid breaking arithmetic where we can, eh?
if (divTokenSupply > 0) {
// Update the value of each remaining back-end dividend token.
profitPerDivToken = profitPerDivToken.add((_dividends * magnitude) / divTokenSupply);
}
// Fire logging event.
emit onTokenSell(msg.sender, _frontEndTokensToBurn, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* No charge incurred for the transfer. We'd make a terrible bank.
*/
function transfer(address _toAddress, uint _amountOfTokens)
onlyHolders()
public
returns(bool)
{
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[msg.sender]);
bytes memory empty;
transferFromInternal(msg.sender, _toAddress, _amountOfTokens, empty);
return true;
}
function approve(address spender, uint tokens)
public
returns (bool)
{
address _customerAddress = msg.sender;
allowed[_customerAddress][spender] = tokens;
// Fire logging event.
emit Approval(_customerAddress, spender, tokens);
// Good old ERC20.
return true;
}
/**
* Transfer tokens from the caller to a new holder: the Used By Smart Contracts edition.
* No charge incurred for the transfer. No seriously, we'd make a terrible bank.
*/
function transferFrom(address _from, address _toAddress, uint _amountOfTokens)
public
returns(bool)
{
// Setup variables
address _customerAddress = _from;
bytes memory empty;
// Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens,
// and are transferring at least one full token.
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[_customerAddress]
&& _amountOfTokens <= allowed[_customerAddress][msg.sender]);
transferFromInternal(_from, _toAddress, _amountOfTokens, empty);
// Good old ERC20.
return true;
}
function transferTo (address _from, address _to, uint _amountOfTokens, bytes _data)
public
{
if (_from != msg.sender){
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[_from]
&& _amountOfTokens <= allowed[_from][msg.sender]);
}
else{
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[_from]);
}
transferFromInternal(_from, _to, _amountOfTokens, _data);
}
// Who'd have thought we'd need this thing floating around?
function totalSupply()
public
view
returns (uint256)
{
return tokenSupply;
}
// Anyone can start the regular phase 2 weeks after the ICO phase starts.
// In case the devs die. Or something.
function publicStartRegularPhase()
public
{
require(now > (icoOpenTime + 2 weeks) && icoOpenTime != 0);
icoPhase = false;
regularPhase = true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
// Fire the starting gun and then duck for cover.
function startICOPhase()
onlyAdministrator()
public
{
// Prevent us from startaring the ICO phase again
require(icoOpenTime == 0);
icoPhase = true;
icoOpenTime = now;
}
// Fire the ... ending gun?
function endICOPhase()
onlyAdministrator()
public
{
icoPhase = false;
}
function startRegularPhase()
onlyAdministrator
public
{
// disable ico phase in case if that was not disabled yet
icoPhase = false;
regularPhase = true;
}
// The death of a great man demands the birth of a great son.
function setAdministrator(address _newAdmin, bool _status)
onlyAdministrator()
public
{
administrators[_newAdmin] = _status;
}
function setStakingRequirement(uint _amountOfTokens)
onlyAdministrator()
public
{
// This plane only goes one way, lads. Never below the initial.
require (_amountOfTokens >= 100e18);
stakingRequirement = _amountOfTokens;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function changeBankroll(address _newBankrollAddress)
onlyAdministrator
public
{
bankrollAddress = _newBankrollAddress;
}
/*---------- HELPERS AND CALCULATORS ----------*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
function totalEthereumICOReceived()
public
view
returns(uint)
{
return ethInvestedDuringICO;
}
/**
* Retrieves your currently selected dividend rate.
*/
function getMyDividendRate()
public
view
returns(uint8)
{
address _customerAddress = msg.sender;
require(userSelectedRate[_customerAddress]);
return userDividendRate[_customerAddress];
}
/**
* Retrieve the total frontend token supply
*/
function getFrontEndTokenSupply()
public
view
returns(uint)
{
return tokenSupply;
}
/**
* Retreive the total dividend token supply
*/
function getDividendTokenSupply()
public
view
returns(uint)
{
return divTokenSupply;
}
/**
* Retrieve the frontend tokens owned by the caller
*/
function myFrontEndTokens()
public
view
returns(uint)
{
address _customerAddress = msg.sender;
return getFrontEndTokenBalanceOf(_customerAddress);
}
/**
* Retrieve the dividend tokens owned by the caller
*/
function myDividendTokens()
public
view
returns(uint)
{
address _customerAddress = msg.sender;
return getDividendTokenBalanceOf(_customerAddress);
}
function myReferralDividends()
public
view
returns(uint)
{
return myDividends(true) - myDividends(false);
}
function myDividends(bool _includeReferralBonus)
public
view
returns(uint)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function theDividendsOf(bool _includeReferralBonus, address _customerAddress)
public
view
returns(uint)
{
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function getFrontEndTokenBalanceOf(address _customerAddress)
view
public
returns(uint)
{
return frontTokenBalanceLedger_[_customerAddress];
}
function balanceOf(address _owner)
view
public
returns(uint)
{
return getFrontEndTokenBalanceOf(_owner);
}
function getDividendTokenBalanceOf(address _customerAddress)
view
public
returns(uint)
{
return dividendTokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress)
view
public
returns(uint)
{
return (uint) ((int256)(profitPerDivToken * dividendTokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
// Get the sell price at the user's average dividend rate
function sellPrice()
public
view
returns(uint)
{
uint price;
if (icoPhase || currentEthInvested < ethInvestedDuringICO) {
price = tokenPriceInitial_;
} else {
// Calculate the tokens received for 100 finney.
// Divide to find the average, to calculate the price.
uint tokensReceivedForEth = ethereumToTokens_(0.001 ether);
price = (1e18 * 0.001 ether) / tokensReceivedForEth;
}
// Factor in the user's average dividend rate
uint theSellPrice = price.sub((price.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude));
return theSellPrice;
}
// Get the buy price at a particular dividend rate
function buyPrice(uint dividendRate)
public
view
returns(uint)
{
uint price;
if (icoPhase || currentEthInvested < ethInvestedDuringICO) {
price = tokenPriceInitial_;
} else {
// Calculate the tokens received for 100 finney.
// Divide to find the average, to calculate the price.
uint tokensReceivedForEth = ethereumToTokens_(0.001 ether);
price = (1e18 * 0.001 ether) / tokensReceivedForEth;
}
// Factor in the user's selected dividend rate
uint theBuyPrice = (price.mul(dividendRate).div(100)).add(price);
return theBuyPrice;
}
function calculateTokensReceived(uint _ethereumToSpend)
public
view
returns(uint)
{
uint _dividends = (_ethereumToSpend.mul(userDividendRate[msg.sender])).div(100);
uint _taxedEthereum = _ethereumToSpend.sub(_dividends);
uint _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
// When selling tokens, we need to calculate the user's current dividend rate.
// This is different from their selected dividend rate.
function calculateEthereumReceived(uint _tokensToSell)
public
view
returns(uint)
{
require(_tokensToSell <= tokenSupply);
uint _ethereum = tokensToEthereum_(_tokensToSell);
uint userAverageDividendRate = getUserAverageDividendRate(msg.sender);
uint _dividends = (_ethereum.mul(userAverageDividendRate).div(100)).div(magnitude);
uint _taxedEthereum = _ethereum.sub(_dividends);
return _taxedEthereum;
}
/*
* Get's a user's average dividend rate - which is just their divTokenBalance / tokenBalance
* We multiply by magnitude to avoid precision errors.
*/
function getUserAverageDividendRate(address user) public view returns (uint) {
return (magnitude * dividendTokenBalanceLedger_[user]).div(frontTokenBalanceLedger_[user]);
}
function getMyAverageDividendRate() public view returns (uint) {
return getUserAverageDividendRate(msg.sender);
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
/* Purchase tokens with Ether.
During ICO phase, dividends should go to the bankroll
During normal operation:
0.5% should go to the master dividend card
0.5% should go to the matching dividend card
25% of dividends should go to the referrer, if any is provided. */
function purchaseTokens(uint _incomingEthereum, address _referredBy)
internal
returns(uint)
{
require(_incomingEthereum >= MIN_ETH_BUYIN || msg.sender == bankrollAddress, "Tried to buy below the min eth buyin threshold.");
uint toBankRoll;
uint toReferrer;
uint toTokenHolders;
uint toDivCardHolders;
uint dividendAmount;
uint tokensBought;
uint dividendTokensBought;
uint remainingEth = _incomingEthereum;
uint fee;
// 1% for dividend card holders is taken off before anything else
if (regularPhase) {
toDivCardHolders = _incomingEthereum.div(100);
remainingEth = remainingEth.sub(toDivCardHolders);
}
/* Next, we tax for dividends:
Dividends = (ethereum * div%) / 100
Important note: if we're out of the ICO phase, the 1% sent to div-card holders
is handled prior to any dividend taxes are considered. */
// Grab the user's dividend rate
uint dividendRate = userDividendRate[msg.sender];
// Calculate the total dividends on this buy
dividendAmount = (remainingEth.mul(dividendRate)).div(100);
remainingEth = remainingEth.sub(dividendAmount);
// If we're in the ICO and bankroll is buying, don't tax
if (icoPhase && msg.sender == bankrollAddress) {
remainingEth = remainingEth + dividendAmount;
}
// Calculate how many tokens to buy:
tokensBought = ethereumToTokens_(remainingEth);
dividendTokensBought = tokensBought.mul(dividendRate);
// This is where we actually mint tokens:
tokenSupply = tokenSupply.add(tokensBought);
divTokenSupply = divTokenSupply.add(dividendTokensBought);
/* Update the total investment tracker
Note that this must be done AFTER we calculate how many tokens are bought -
because ethereumToTokens needs to know the amount *before* investment, not *after* investment. */
currentEthInvested = currentEthInvested + remainingEth;
// If ICO phase, all the dividends go to the bankroll
if (icoPhase) {
toBankRoll = dividendAmount;
// If the bankroll is buying, we don't want to send eth back to the bankroll
// Instead, let's just give it the tokens it would get in an infinite recursive buy
if (msg.sender == bankrollAddress) {
toBankRoll = 0;
}
toReferrer = 0;
toTokenHolders = 0;
/* ethInvestedDuringICO tracks how much Ether goes straight to tokens,
not how much Ether we get total.
this is so that our calculation using "investment" is accurate. */
ethInvestedDuringICO = ethInvestedDuringICO + remainingEth;
tokensMintedDuringICO = tokensMintedDuringICO + tokensBought;
// Cannot purchase more than the hard cap during ICO.
require(ethInvestedDuringICO <= icoHardCap);
// Contracts aren't allowed to participate in the ICO.
require(tx.origin == msg.sender || msg.sender == bankrollAddress);
// Cannot purchase more then the limit per address during the ICO.
ICOBuyIn[msg.sender] += remainingEth;
require(ICOBuyIn[msg.sender] <= addressICOLimit || msg.sender == bankrollAddress);
// Stop the ICO phase if we reach the hard cap
if (ethInvestedDuringICO == icoHardCap){
icoPhase = false;
}
} else {
// Not ICO phase, check for referrals
// 25% goes to referrers, if set
// toReferrer = (dividends * 25)/100
if (_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != msg.sender &&
frontTokenBalanceLedger_[_referredBy] >= stakingRequirement)
{
toReferrer = (dividendAmount.mul(referrer_percentage)).div(100);
referralBalance_[_referredBy] += toReferrer;
emit Referral(_referredBy, toReferrer);
}
// The rest of the dividends go to token holders
toTokenHolders = dividendAmount.sub(toReferrer);
fee = toTokenHolders * magnitude;
fee = fee - (fee - (dividendTokensBought * (toTokenHolders * magnitude / (divTokenSupply))));
// Finally, increase the divToken value
profitPerDivToken = profitPerDivToken.add((toTokenHolders.mul(magnitude)).div(divTokenSupply));
payoutsTo_[msg.sender] += (int256) ((profitPerDivToken * dividendTokensBought) - fee);
}
// Update the buyer's token amounts
frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].add(tokensBought);
dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].add(dividendTokensBought);
// Transfer to bankroll and div cards
if (toBankRoll != 0) { ZethrBankroll(bankrollAddress).receiveDividends.value(toBankRoll)(); }
if (regularPhase) { divCardContract.receiveDividends.value(toDivCardHolders)(dividendRate); }
// This event should help us track where all the eth is going
emit Allocation(toBankRoll, toReferrer, toTokenHolders, toDivCardHolders, remainingEth);
// Sanity checking
uint sum = toBankRoll + toReferrer + toTokenHolders + toDivCardHolders + remainingEth - _incomingEthereum;
assert(sum == 0);
}
// How many tokens one gets from a certain amount of ethereum.
function ethereumToTokens_(uint _ethereumAmount)
public
view
returns(uint)
{
require(_ethereumAmount > MIN_ETH_BUYIN, "Tried to buy tokens with too little eth.");
if (icoPhase) {
return _ethereumAmount.div(tokenPriceInitial_) * 1e18;
}
/*
* i = investment, p = price, t = number of tokens
*
* i_current = p_initial * t_current (for t_current <= t_initial)
* i_current = i_initial + (2/3)(t_current)^(3/2) (for t_current > t_initial)
*
* t_current = i_current / p_initial (for i_current <= i_initial)
* t_current = t_initial + ((3/2)(i_current))^(2/3) (for i_current > i_initial)
*/
// First, separate out the buy into two segments:
// 1) the amount of eth going towards ico-price tokens