-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy path0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190-DTH-Dether.sol
1016 lines (828 loc) · 35.4 KB
/
0x5adc961d6ac3f7062d2ea45fefb8d8167d44b190-DTH-Dether.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
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Whitelistable is Ownable {
event LogUserRegistered(address indexed sender, address indexed userAddress);
event LogUserUnregistered(address indexed sender, address indexed userAddress);
mapping(address => bool) public whitelisted;
function registerUser(address userAddress)
public
onlyOwner
{
require(userAddress != 0);
whitelisted[userAddress] = true;
LogUserRegistered(msg.sender, userAddress);
}
function unregisterUser(address userAddress)
public
onlyOwner
{
require(whitelisted[userAddress] == true);
whitelisted[userAddress] = false;
LogUserUnregistered(msg.sender, userAddress);
}
}
contract DisbursementHandler is Ownable {
struct Disbursement {
uint256 timestamp;
uint256 tokens;
}
event LogSetup(address indexed vestor, uint256 tokens, uint256 timestamp);
event LogChangeTimestamp(address indexed vestor, uint256 index, uint256 timestamp);
event LogWithdraw(address indexed to, uint256 value);
ERC20 public token;
mapping(address => Disbursement[]) public disbursements;
mapping(address => uint256) public withdrawnTokens;
function DisbursementHandler(address _token) public {
token = ERC20(_token);
}
/// @dev Called by the sale contract to create a disbursement.
/// @param vestor The address of the beneficiary.
/// @param tokens Amount of tokens to be locked.
/// @param timestamp Funds will be locked until this timestamp.
function setupDisbursement(
address vestor,
uint256 tokens,
uint256 timestamp
)
public
onlyOwner
{
require(block.timestamp < timestamp);
disbursements[vestor].push(Disbursement(timestamp, tokens));
LogSetup(vestor, timestamp, tokens);
}
/// @dev Change an existing disbursement.
/// @param vestor The address of the beneficiary.
/// @param timestamp Funds will be locked until this timestamp.
/// @param index Index of the DisbursementVesting in the vesting array.
function changeTimestamp(
address vestor,
uint256 index,
uint256 timestamp
)
public
onlyOwner
{
require(block.timestamp < timestamp);
require(index < disbursements[vestor].length);
disbursements[vestor][index].timestamp = timestamp;
LogChangeTimestamp(vestor, index, timestamp);
}
/// @dev Transfers tokens to a given address
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
function withdraw(address to, uint256 value)
public
{
uint256 maxTokens = calcMaxWithdraw();
uint256 withdrawAmount = value < maxTokens ? value : maxTokens;
withdrawnTokens[msg.sender] = SafeMath.add(withdrawnTokens[msg.sender], withdrawAmount);
token.transfer(to, withdrawAmount);
LogWithdraw(to, value);
}
/// @dev Calculates the maximum amount of vested tokens
/// @return Number of vested tokens to withdraw
function calcMaxWithdraw()
public
constant
returns (uint256)
{
uint256 maxTokens = 0;
Disbursement[] storage temp = disbursements[msg.sender];
for (uint256 i = 0; i < temp.length; i++) {
if (block.timestamp > temp[i].timestamp) {
maxTokens = SafeMath.add(maxTokens, temp[i].tokens);
}
}
maxTokens = SafeMath.sub(maxTokens, withdrawnTokens[msg.sender]);
return maxTokens;
}
}
library StateMachineLib {
struct Stage {
// The id of the next stage
bytes32 nextId;
// The identifiers for the available functions in each stage
mapping(bytes4 => bool) allowedFunctions;
}
struct State {
// The current stage id
bytes32 currentStageId;
// A callback that is called when entering this stage
function(bytes32) internal onTransition;
// Checks if a stage id is valid
mapping(bytes32 => bool) validStage;
// Maps stage ids to their Stage structs
mapping(bytes32 => Stage) stages;
}
/// @dev Creates and sets the initial stage. It has to be called before creating any transitions.
/// @param stageId The id of the (new) stage to set as initial stage.
function setInitialStage(State storage self, bytes32 stageId) internal {
self.validStage[stageId] = true;
self.currentStageId = stageId;
}
/// @dev Creates a transition from 'fromId' to 'toId'. If fromId already had a nextId, it deletes the now unreachable stage.
/// @param fromId The id of the stage from which the transition begins.
/// @param toId The id of the stage that will be reachable from "fromId".
function createTransition(State storage self, bytes32 fromId, bytes32 toId) internal {
require(self.validStage[fromId]);
Stage storage from = self.stages[fromId];
// Invalidate the stage that won't be reachable any more
if (from.nextId != 0) {
self.validStage[from.nextId] = false;
delete self.stages[from.nextId];
}
from.nextId = toId;
self.validStage[toId] = true;
}
/// @dev Goes to the next stage if posible (if the next stage is valid)
function goToNextStage(State storage self) internal {
Stage storage current = self.stages[self.currentStageId];
require(self.validStage[current.nextId]);
self.currentStageId = current.nextId;
self.onTransition(current.nextId);
}
/// @dev Checks if the a function is allowed in the current stage.
/// @param selector A function selector (bytes4[keccak256(functionSignature)])
/// @return true If the function is allowed in the current stage
function checkAllowedFunction(State storage self, bytes4 selector) internal constant returns(bool) {
return self.stages[self.currentStageId].allowedFunctions[selector];
}
/// @dev Allow a function in the given stage.
/// @param stageId The id of the stage
/// @param selector A function selector (bytes4[keccak256(functionSignature)])
function allowFunction(State storage self, bytes32 stageId, bytes4 selector) internal {
require(self.validStage[stageId]);
self.stages[stageId].allowedFunctions[selector] = true;
}
}
contract StateMachine {
using StateMachineLib for StateMachineLib.State;
event LogTransition(bytes32 indexed stageId, uint256 blockNumber);
StateMachineLib.State internal state;
/* This modifier performs the conditional transitions and checks that the function
* to be executed is allowed in the current stage
*/
modifier checkAllowed {
conditionalTransitions();
require(state.checkAllowedFunction(msg.sig));
_;
}
function StateMachine() public {
// Register the startConditions function and the onTransition callback
state.onTransition = onTransition;
}
/// @dev Gets the current stage id.
/// @return The current stage id.
function getCurrentStageId() public view returns(bytes32) {
return state.currentStageId;
}
/// @dev Performs conditional transitions. Can be called by anyone.
function conditionalTransitions() public {
bytes32 nextId = state.stages[state.currentStageId].nextId;
while (state.validStage[nextId]) {
StateMachineLib.Stage storage next = state.stages[nextId];
// If the next stage's condition is true, go to next stage and continue
if (startConditions(nextId)) {
state.goToNextStage();
nextId = next.nextId;
} else {
break;
}
}
}
/// @dev Determines whether the conditions for transitioning to the given stage are met.
/// @return true if the conditions are met for the given stageId. False by default (must override in child contracts).
function startConditions(bytes32) internal constant returns(bool) {
return false;
}
/// @dev Callback called when there is a stage transition. It should be overridden for additional functionality.
function onTransition(bytes32 stageId) internal {
LogTransition(stageId, block.number);
}
}
contract TimedStateMachine is StateMachine {
event LogSetStageStartTime(bytes32 indexed stageId, uint256 startTime);
// Stores the start timestamp for each stage (the value is 0 if the stage doesn't have a start timestamp).
mapping(bytes32 => uint256) internal startTime;
/// @dev This function overrides the startConditions function in the parent contract in order to enable automatic transitions that depend on the timestamp.
function startConditions(bytes32 stageId) internal constant returns(bool) {
// Get the startTime for stage
uint256 start = startTime[stageId];
// If the startTime is set and has already passed, return true.
return start != 0 && block.timestamp > start;
}
/// @dev Sets the starting timestamp for a stage.
/// @param stageId The id of the stage for which we want to set the start timestamp.
/// @param timestamp The start timestamp for the given stage. It should be bigger than the current one.
function setStageStartTime(bytes32 stageId, uint256 timestamp) internal {
require(state.validStage[stageId]);
require(timestamp > block.timestamp);
startTime[stageId] = timestamp;
LogSetStageStartTime(stageId, timestamp);
}
/// @dev Returns the timestamp for the given stage id.
/// @param stageId The id of the stage for which we want to set the start timestamp.
function getStageStartTime(bytes32 stageId) public view returns(uint256) {
return startTime[stageId];
}
}
contract Sale is Ownable, TimedStateMachine {
using SafeMath for uint256;
event LogContribution(address indexed contributor, uint256 amountSent, uint256 excessRefunded);
event LogTokenAllocation(address indexed contributor, uint256 contribution, uint256 tokens);
event LogDisbursement(address indexed beneficiary, uint256 tokens);
// Stages for the state machine
bytes32 public constant SETUP = "setup";
bytes32 public constant SETUP_DONE = "setupDone";
bytes32 public constant SALE_IN_PROGRESS = "saleInProgress";
bytes32 public constant SALE_ENDED = "saleEnded";
mapping(address => uint256) public contributions;
uint256 public weiContributed = 0;
uint256 public contributionCap;
// Wallet where funds will be sent
address public wallet;
MintableToken public token;
DisbursementHandler public disbursementHandler;
function Sale(
address _wallet,
uint256 _contributionCap
)
public
{
require(_wallet != 0);
require(_contributionCap != 0);
wallet = _wallet;
token = createTokenContract();
disbursementHandler = new DisbursementHandler(token);
contributionCap = _contributionCap;
setupStages();
}
function() external payable {
contribute();
}
/// @dev Sets the start timestamp for the SALE_IN_PROGRESS stage.
/// @param timestamp The start timestamp.
function setSaleStartTime(uint256 timestamp)
external
onlyOwner
checkAllowed
{
// require(_startTime < getStageStartTime(SALE_ENDED));
setStageStartTime(SALE_IN_PROGRESS, timestamp);
}
/// @dev Sets the start timestamp for the SALE_ENDED stage.
/// @param timestamp The start timestamp.
function setSaleEndTime(uint256 timestamp)
external
onlyOwner
checkAllowed
{
require(getStageStartTime(SALE_IN_PROGRESS) < timestamp);
setStageStartTime(SALE_ENDED, timestamp);
}
/// @dev Called in the SETUP stage, check configurations and to go to the SETUP_DONE stage.
function setupDone()
public
onlyOwner
checkAllowed
{
uint256 _startTime = getStageStartTime(SALE_IN_PROGRESS);
uint256 _endTime = getStageStartTime(SALE_ENDED);
require(block.timestamp < _startTime);
require(_startTime < _endTime);
state.goToNextStage();
}
/// @dev Called by users to contribute ETH to the sale.
function contribute()
public
payable
checkAllowed
{
require(msg.value > 0);
uint256 contributionLimit = getContributionLimit(msg.sender);
require(contributionLimit > 0);
// Check that the user is allowed to contribute
uint256 totalContribution = contributions[msg.sender].add(msg.value);
uint256 excess = 0;
// Check if it goes over the eth cap for the sale.
if (weiContributed.add(msg.value) > contributionCap) {
// Subtract the excess
excess = weiContributed.add(msg.value).sub(contributionCap);
totalContribution = totalContribution.sub(excess);
}
// Check if it goes over the contribution limit of the user.
if (totalContribution > contributionLimit) {
excess = excess.add(totalContribution).sub(contributionLimit);
contributions[msg.sender] = contributionLimit;
} else {
contributions[msg.sender] = totalContribution;
}
// We are only able to refund up to msg.value because the contract will not contain ether
// excess = excess < msg.value ? excess : msg.value;
require(excess <= msg.value);
weiContributed = weiContributed.add(msg.value).sub(excess);
if (excess > 0) {
msg.sender.transfer(excess);
}
wallet.transfer(this.balance);
assert(contributions[msg.sender] <= contributionLimit);
LogContribution(msg.sender, msg.value, excess);
}
/// @dev Create a disbursement of tokens.
/// @param beneficiary The beneficiary of the disbursement.
/// @param tokenAmount Amount of tokens to be locked.
/// @param timestamp Tokens will be locked until this timestamp.
function distributeTimelockedTokens(
address beneficiary,
uint256 tokenAmount,
uint256 timestamp
)
public
onlyOwner
checkAllowed
{
disbursementHandler.setupDisbursement(
beneficiary,
tokenAmount,
timestamp
);
token.mint(disbursementHandler, tokenAmount);
LogDisbursement(beneficiary, tokenAmount);
}
function setupStages() internal {
// Set the stages
state.setInitialStage(SETUP);
state.createTransition(SETUP, SETUP_DONE);
state.createTransition(SETUP_DONE, SALE_IN_PROGRESS);
state.createTransition(SALE_IN_PROGRESS, SALE_ENDED);
state.allowFunction(SETUP, this.distributeTimelockedTokens.selector);
state.allowFunction(SETUP, this.setSaleStartTime.selector);
state.allowFunction(SETUP, this.setSaleEndTime.selector);
state.allowFunction(SETUP, this.setupDone.selector);
state.allowFunction(SALE_IN_PROGRESS, this.contribute.selector);
state.allowFunction(SALE_IN_PROGRESS, 0); // fallback
}
// Override in the child sales
function createTokenContract() internal returns (MintableToken);
function getContributionLimit(address userAddress) public view returns (uint256);
/// @dev Stage start conditions.
function startConditions(bytes32 stageId) internal constant returns (bool) {
// If the cap has been reached, end the sale.
if (stageId == SALE_ENDED && contributionCap <= weiContributed) {
return true;
}
return super.startConditions(stageId);
}
/// @dev State transitions callbacks.
function onTransition(bytes32 stageId) internal {
if (stageId == SALE_ENDED) {
onSaleEnded();
}
super.onTransition(stageId);
}
/// @dev Callback that gets called when entering the SALE_ENDED stage.
function onSaleEnded() internal {}
}
contract ERC223ReceivingContract {
/// @dev Standard ERC223 function that will handle incoming token transfers.
/// @param _from Token sender address.
/// @param _value Amount of tokens.
/// @param _data Transaction metadata.
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract ERC223Basic is ERC20Basic {
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Now with a new parameter _data.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool);
/**
* @dev triggered when transfer is successfully called.
*
* @param _from Sender address.
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
event Transfer(address indexed _from, address indexed _to, uint256 indexed _value, bytes _data);
}
contract ERC223BasicToken is ERC223Basic, BasicToken {
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
require(super.transfer(_to, _value));
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
require(transfer(_to, _value, empty));
return true;
}
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract DetherToken is DetailedERC20, MintableToken, ERC223BasicToken {
string constant NAME = "Dether";
string constant SYMBOL = "DTH";
uint8 constant DECIMALS = 18;
/**
*@dev Constructor that set Detailed of the ERC20 token.
*/
function DetherToken()
DetailedERC20(NAME, SYMBOL, DECIMALS)
public
{}
}
contract DetherSale is Sale, Whitelistable {
uint256 public constant PRESALE_WEI = 3956 ether * 1.15 + 490 ether; // Amount raised in the presale including bonus
uint256 public constant DECIMALS_MULTIPLIER = 1000000000000000000;
uint256 public constant MAX_DTH = 100000000 * DECIMALS_MULTIPLIER;
// MAX_WEI - PRESALE_WEI
// TODO: change to actual amount
uint256 public constant WEI_CAP = 10554 ether;
// Duration of the whitelisting phase
uint256 public constant WHITELISTING_DURATION = 2 days;
// Contribution limit for the whitelisting phase
uint256 public constant WHITELISTING_MAX_CONTRIBUTION = 5 ether;
// Contribution limit for the public sale
uint256 public constant PUBLIC_MAX_CONTRIBUTION = 2**256 - 1;
// Minimum contribution allowed
uint256 public constant MIN_CONTRIBUTION = 0.1 ether;
// wei per DTH
uint256 public weiPerDTH;
// true if the locked tokens have been distributed
bool private lockedTokensDistributed;
// true if the presale tokens have been allocated
bool private presaleAllocated;
// Address for the presale buyers (Dether team will distribute manually)
address public presaleAddress;
uint256 private weiAllocated;
// Contribution limits specified for the presale
mapping(address => uint256) public presaleMaxContribution;
function DetherSale(address _wallet, address _presaleAddress) Sale(_wallet, WEI_CAP) public {
presaleAddress = _presaleAddress;
}
/// @dev Distributes timed locked tokens
function performInitialAllocations() external onlyOwner checkAllowed {
require(lockedTokensDistributed == false);
lockedTokensDistributed = true;
// Advisors
distributeTimelockedTokens(0x4dc976cEd66d1B87C099B338E1F1388AE657377d, MAX_DTH.mul(3).div(100), now + 6 * 4 weeks);
// Bounty
distributeTimelockedTokens(0xfEF675cC3068Ee798f2312e82B12c841157A0A0E, MAX_DTH.mul(3).div(100), now + 1 weeks);
// Early Contributors
distributeTimelockedTokens(0x8F38C4ddFE09Bd22545262FE160cf441D43d2489, MAX_DTH.mul(25).div(1000), now + 6 * 4 weeks);
distributeTimelockedTokens(0x87a4eb1c9fdef835DC9197FAff3E09b8007ADe5b, MAX_DTH.mul(25).div(1000), now + 6 * 4 weeks);
// Strategic Partnerships
distributeTimelockedTokens(0x6f63D5DF2D8644851cBb5F8607C845704C008284, MAX_DTH.mul(11).div(100), now + 1 weeks);
// Team (locked 3 years, 6 months release)
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 2 * 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 3 * 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 4 * 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 5 * 6 * 4 weeks);
distributeTimelockedTokens(0x24c14796f401D77fc401F9c2FA1dF42A136EbF83, MAX_DTH.mul(3).div(100), now + 6 * 6 * 4 weeks);
}
/// @dev Registers a user and sets the maximum contribution amount for the whitelisting period
function registerPresaleContributor(address userAddress, uint256 maxContribution)
external
onlyOwner
{
// Specified contribution has to be lower than the max
require(maxContribution <= WHITELISTING_MAX_CONTRIBUTION);
// Register user (Whitelistable contract)
registerUser(userAddress);
// Set contribution
presaleMaxContribution[userAddress] = maxContribution;
}
/// @dev Called to allocate the tokens depending on eth contributed.
/// @param contributor The address of the contributor.
function allocateTokens(address contributor)
external
checkAllowed
{
require(presaleAllocated);
require(contributions[contributor] != 0);
// We keep a record of how much wei contributed has already been used for allocations
weiAllocated = weiAllocated.add(contributions[contributor]);
// Mint the respective tokens to the contributor
token.mint(contributor, contributions[contributor].mul(DECIMALS_MULTIPLIER).div(weiPerDTH));
// Set contributions to 0
contributions[contributor] = 0;
// If all tokens were allocated, stop minting functionality
// and send the remaining (rounding errors) tokens to the owner
if (weiAllocated == weiContributed) {
uint256 remaining = MAX_DTH.sub(token.totalSupply());
token.mint(owner, remaining);
token.finishMinting();
}
}
/// @dev Called to allocate the tokens for presale address.
function presaleAllocateTokens()
external
checkAllowed
{
require(!presaleAllocated);
presaleAllocated = true;
// Mint the respective tokens to the contributor
token.mint(presaleAddress, PRESALE_WEI.mul(DECIMALS_MULTIPLIER).div(weiPerDTH));
}
function contribute()
public
payable
checkAllowed
{
require(msg.value >= MIN_CONTRIBUTION);
super.contribute();
}
/// @dev The limit will be different for every address during the whitelist period, and after that phase there is no limit for contributions.
function getContributionLimit(address userAddress) public view returns (uint256) {
uint256 saleStartTime = getStageStartTime(SALE_IN_PROGRESS);
// If not whitelisted or sale has not started, return 0
if (!whitelisted[userAddress] || block.timestamp < saleStartTime) {
return 0;
}
// Are we in the first two days?
bool whitelistingPeriod = block.timestamp - saleStartTime <= WHITELISTING_DURATION;
// If we are in the whitelisting period, return the contribution limit for the user
// If not, return the public max contribution
return whitelistingPeriod ? presaleMaxContribution[userAddress] : PUBLIC_MAX_CONTRIBUTION;
}
function createTokenContract() internal returns(MintableToken) {
return new DetherToken();
}
function setupStages() internal {