Dataset Viewer
Auto-converted to Parquet
source_codes
stringlengths
72
160k
labels
int64
0
1
__index_level_0__
int64
0
4.4k
pragma solidity ^0.4.23; 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); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } 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 StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; 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); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract FreezableToken is StandardToken { mapping (bytes32 => uint64) internal chains; mapping (bytes32 => uint) internal freezings; mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract TCNXToken is FreezableToken, BurnableToken, Pausable { address public fundsWallet = 0x368E1ED074e2F6bBEca5731C8BaE8460d1cA2529; uint256 public totalSupply = 20 * 1000000000 ether; uint256 public blockDate = 1561852800; constructor() public { transferOwnership(fundsWallet); balances[fundsWallet] = totalSupply; Transfer(0x0, fundsWallet, totalSupply); } function name() public pure returns (string _name) { return "Tercet Network"; } function symbol() public pure returns (string _symbol) { return "TCNX"; } function decimals() public pure returns (uint8 _decimals) { return 18; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); require(!isBlocked(_from, _value)); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); require(!isBlocked(msg.sender, _value)); return super.transfer(_to, _value); } function isBlocked(address _from, uint256 _value) returns(bool _blocked){ if(_from != fundsWallet || now > blockDate){ return false; } if(balances[_from].sub(_value) < totalSupply.mul(50).div(100)){ return true; } return false; } }
0
1,769
pragma solidity ^0.4.18; contract FUTX { uint256 constant MAX_UINT256 = 2**256 - 1; uint256 MAX_SUBMITTED = 5000671576194550000000; uint256 _totalSupply = 0; uint256[] levels = [ 87719298245614000000, 198955253301794000000, 373500707847248000000, 641147766670778000000, 984004909527921000000, 1484004909527920000000, 2184004909527920000000, 3084004909527920000000, 4150671576194590000000, 5000671576194550000000 ]; uint256[] ratios = [ 114, 89, 55, 34, 21, 13, 8, 5, 3, 2 ]; uint256 _submitted = 0; uint256 public tier = 0; event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); event Mined(address indexed _miner, uint _value); event WaitStarted(uint256 endTime); event SwapStarted(uint256 endTime); event MiningStart(uint256 end_time, uint256 swap_time, uint256 swap_end_time); event MiningExtended(uint256 end_time, uint256 swap_time, uint256 swap_end_time); string public name = "Futereum X"; uint8 public decimals = 18; string public symbol = "FUTX"; bool public swap = false; bool public wait = false; bool public extended = false; uint256 public endTime; uint256 swapTime; uint256 swapEndTime; uint256 endTimeExtended; uint256 swapTimeExtended; uint256 swapEndTimeExtended; uint256 public payRate = 0; uint256 submittedFeesPaid = 0; uint256 penalty = 0; uint256 reservedFees = 0; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function () external payable { require(msg.sender != address(0) && tier != 10 && swap == false && wait == false); uint256 issued = mint(msg.sender, msg.value); Mined(msg.sender, issued); Transfer(this, msg.sender, issued); } function FUTX() public { _start(); } function _start() internal { swap = false; wait = false; extended = false; endTime = now + 90 days; swapTime = endTime + 30 days; swapEndTime = swapTime + 5 days; endTimeExtended = now + 270 days; swapTimeExtended = endTimeExtended + 90 days; swapEndTimeExtended = swapTimeExtended + 5 days; submittedFeesPaid = 0; _submitted = 0; reservedFees = 0; payRate = 0; tier = 0; MiningStart(endTime, swapTime, swapEndTime); } function restart() public { require(swap && now >= endTime); penalty = this.balance * 2000 / 10000; payFees(); _start(); } function totalSupply() public constant returns (uint) { return _totalSupply; } function mint(address _to, uint256 _value) internal returns (uint256) { uint256 total = _submitted + _value; if (total > MAX_SUBMITTED) { uint256 refund = total - MAX_SUBMITTED - 1; _value = _value - refund; _to.transfer(refund); } _submitted += _value; total -= refund; uint256 tokens = calculateTokens(total, _value); balances[_to] += tokens; _totalSupply += tokens; return tokens; } function calculateTokens(uint256 total, uint256 _value) internal returns (uint256) { if (tier == 10) { return 74000000; } uint256 tokens = 0; if (total > levels[tier]) { uint256 remaining = total - levels[tier]; _value -= remaining; tokens = (_value) * ratios[tier]; tier += 1; tokens += calculateTokens(total, remaining); } else { tokens = _value * ratios[tier]; } return tokens; } function currentTier() public view returns (uint256) { if (tier == 10) { return 10; } else { return tier + 1; } } function leftInTier() public view returns (uint256) { if (tier == 10) { return 0; } else { return levels[tier] - _submitted; } } function submitted() public view returns (uint256) { return _submitted; } function balanceMinusFeesOutstanding() public view returns (uint256) { return this.balance - (penalty + (_submitted - submittedFeesPaid) * 1530 / 10000); } function calulateRate() internal { reservedFees = penalty + (_submitted - submittedFeesPaid) * 1530 / 10000; uint256 tokens = _totalSupply / 1 ether; payRate = (this.balance - reservedFees); payRate = payRate / tokens; } function _updateState() internal { if (now >= endTime) { if(!swap && !wait) { if (extended) { wait = true; endTime = swapTimeExtended; WaitStarted(endTime); } else if (tier == 10) { wait = true; endTime = swapTime; WaitStarted(endTime); } else { endTime = endTimeExtended; extended = true; MiningExtended(endTime, swapTime, swapEndTime); } } else if (wait) { swap = true; wait = false; if (extended) { endTime = swapEndTimeExtended; } else { endTime = swapEndTime; } SwapStarted(endTime); } } } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); _updateState(); if (_to == address(this)) { require(swap); if (payRate == 0) { calulateRate(); } uint256 amount = _value * payRate; amount /= 1 ether; balances[msg.sender] -= _value; _totalSupply -= _value; Transfer(msg.sender, _to, _value); msg.sender.transfer(amount); } else { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); } return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } address public foundation = 0x950ec4ef693d90f8519c4213821e462426d30905; address public owner = 0x78BFCA5E20B0D710EbEF98249f68d9320eE423be; address public dev = 0x5d2b9f5345e69e2390ce4c26ccc9c2910a097520; function payFees() public { _updateState(); uint256 fees = penalty + (_submitted - submittedFeesPaid) * 1530 / 10000; submittedFeesPaid = _submitted; reservedFees = 0; penalty = 0; if (fees > 0) { foundation.transfer(fees / 3); owner.transfer(fees / 3); dev.transfer(fees / 3); } } function changeFoundation (address _receiver) public { require(msg.sender == foundation); foundation = _receiver; } function changeOwner (address _receiver) public { require(msg.sender == owner); owner = _receiver; } function changeDev (address _receiver) public { require(msg.sender == dev); dev = _receiver; } }
0
1,220
pragma solidity ^0.4.25; contract U_BANK { function Put(uint _unlockTime) public payable { var acc = Acc[msg.sender]; acc.balance += msg.value; acc.unlockTime = _unlockTime>now?_unlockTime:now; LogFile.AddMessage(msg.sender,msg.value,"Put"); } function Collect(uint _am) public payable { var acc = Acc[msg.sender]; if( acc.balance>=MinSum && acc.balance>=_am && now>acc.unlockTime) { if(msg.sender.call.value(_am)()) { acc.balance-=_am; LogFile.AddMessage(msg.sender,_am,"Collect"); } } } function() public payable { Put(0); } struct Holder { uint unlockTime; uint balance; } mapping (address => Holder) public Acc; Log LogFile; uint public MinSum = 2 ether; function U_BANK(address log) public{ LogFile = Log(log); } } contract Log { struct Message { address Sender; string Data; uint Val; uint Time; } Message[] public History; Message LastMsg; function AddMessage(address _adr,uint _val,string _data) public { LastMsg.Sender = _adr; LastMsg.Time = now; LastMsg.Val = _val; LastMsg.Data = _data; History.push(LastMsg); } }
0
44
pragma solidity ^0.4.25; contract ERC20 { bytes32 public standard; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; uint8 public decimals; bool public allowTransactions; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } contract ExToke { string public name = "ExToke Token"; string public symbol = "XTE"; uint8 public decimals = 18; uint256 public crowdSaleSupply = 500000000 * (uint256(10) ** decimals); uint256 public tokenSwapSupply = 3000000000 * (uint256(10) ** decimals); uint256 public dividendSupply = 2400000000 * (uint256(10) ** decimals); uint256 public totalSupply = 7000000000 * (uint256(10) ** decimals); mapping(address => uint256) public balanceOf; address public oldAddress = 0x28925299Ee1EDd8Fd68316eAA64b651456694f0f; address tokenAdmin = 0xEd86f5216BCAFDd85E5875d35463Aca60925bF16; uint256 public finishTime = 1548057600; uint256[] public releaseDates = [1543665600, 1546344000, 1549022400, 1551441600, 1554120000, 1556712000, 1559390400, 1561982400, 1564660800, 1567339200, 1569931200, 1572609600, 1575201600, 1577880000, 1580558400, 1583064000, 1585742400, 1588334400, 1591012800, 1593604800, 1596283200, 1598961600, 1601553600, 1604232000]; uint256 public nextRelease = 0; function ExToke() public { balanceOf[tokenAdmin] = 1100000000 * (uint256(10) ** decimals); emit Transfer(address(0), msg.sender, totalSupply); } uint256 public scaling = uint256(10) ** 8; mapping(address => uint256) public scaledDividendBalanceOf; uint256 public scaledDividendPerToken; mapping(address => uint256) public scaledDividendCreditedTo; function update(address account) internal { if(nextRelease < 24 && block.timestamp > releaseDates[nextRelease]){ releaseDivTokens(); } uint256 owed = scaledDividendPerToken - scaledDividendCreditedTo[account]; scaledDividendBalanceOf[account] += balanceOf[account] * owed; scaledDividendCreditedTo[account] = scaledDividendPerToken; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => mapping(address => uint256)) public allowance; function transfer(address to, uint256 value) public returns (bool success) { require(balanceOf[msg.sender] >= value); update(msg.sender); update(to); balanceOf[msg.sender] -= value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(value <= balanceOf[from]); require(value <= allowance[from][msg.sender]); update(from); update(to); balanceOf[from] -= value; balanceOf[to] += value; allowance[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } uint256 public scaledRemainder = 0; function() public payable{ if(finishTime >= block.timestamp && crowdSaleSupply >= msg.value * 100000){ balanceOf[msg.sender] += msg.value * 100000; crowdSaleSupply -= msg.value * 100000; } else if(finishTime < block.timestamp){ balanceOf[tokenAdmin] += crowdSaleSupply; crowdSaleSupply = 0; } } function releaseDivTokens() public payable { require(block.timestamp > releaseDates[nextRelease]); uint256 releaseAmount = 100000000 * (uint256(10) ** decimals); dividendSupply -= 100000000 * (uint256(10) ** decimals); uint256 available = (releaseAmount * scaling) + scaledRemainder; scaledDividendPerToken += available / totalSupply; scaledRemainder = available % totalSupply; nextRelease += 1; } function withdraw() public { update(msg.sender); uint256 amount = scaledDividendBalanceOf[msg.sender] / scaling; scaledDividendBalanceOf[msg.sender] %= scaling; balanceOf[msg.sender] += amount; } function approve(address spender, uint256 value) public returns (bool success) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function swap(uint256 sendAmount) returns (bool success){ require(tokenSwapSupply >= sendAmount * 3); if(ERC20(oldAddress).transferFrom(msg.sender, tokenAdmin, sendAmount)){ balanceOf[msg.sender] += sendAmount * 3; tokenSwapSupply -= sendAmount * 3; } } }
0
289
pragma solidity ^0.4.18; contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract SatoMotive is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function SatoMotive() public { symbol = "SV2X"; name = "SatoMotive Token"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xf44970e29510EDE8fFED726CF8C447F7512fb59f] = _totalSupply; Transfer(address(0), 0xf44970e29510EDE8fFED726CF8C447F7512fb59f, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1
2,486
pragma solidity ^0.4.11; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant 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 constant 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 BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { 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; } } library Bonus { uint256 constant pointMultiplier = 1e18; uint16 constant ORIGIN_YEAR = 1970; function getBonusFactor(uint256 basisTokens, uint timestamp) internal pure returns (uint256 factor) { uint256[4][5] memory factors = [[uint256(300), 400, 500, 750], [uint256(200), 300, 400, 600], [uint256(150), 250, 300, 500], [uint256(100), 150, 250, 400], [uint256(0), 100, 150, 300]]; uint[4] memory cutofftimes = [toTimestamp(2018, 3, 24), toTimestamp(2018, 4, 5), toTimestamp(2018, 5, 5), toTimestamp(2018, 6, 5)]; uint256 tokenAmount = basisTokens / pointMultiplier; uint256 timeIndex = 4; uint256 amountIndex = 0; if (tokenAmount >= 500000000) { amountIndex = 3; } else if (tokenAmount >= 100000000) { amountIndex = 2; } else if (tokenAmount >= 25000000) { amountIndex = 1; } else { } uint256 maxcutoffindex = cutofftimes.length; for (uint256 i = 0; i < maxcutoffindex; i++) { if (timestamp < cutofftimes[i]) { timeIndex = i; break; } } return factors[timeIndex][amountIndex]; } function toTimestamp(uint16 year, uint8 month, uint8 day) internal pure returns (uint timestamp) { uint16 i; timestamp += (year - ORIGIN_YEAR) * 1 years; timestamp += (leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR)) * 1 days; uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += monthDayCounts[i - 1] * 1 days; } timestamp += (day - 1) * 1 days; return timestamp; } function leapYearsBefore(uint year) internal pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function isLeapYear(uint16 year) internal pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } } contract ClearToken is StandardToken { enum States { Initial, ValuationSet, Ico, Underfunded, Operational, Paused } mapping(address => uint256) public ethPossibleRefunds; uint256 public soldTokens; string public constant name = "CLEAR Token"; string public constant symbol = "CLEAR"; uint8 public constant decimals = 18; mapping(address => bool) public whitelist; address public reserves; address public stateControl; address public whitelistControl; address public withdrawControl; address public tokenAssignmentControl; States public state; uint256 public startAcceptingFundsBlock; uint256 public endTimestamp; uint256 public ETH_CLEAR; uint256 public constant NZD_CLEAR = 50; uint256 constant pointMultiplier = 1e18; uint256 public constant maxTotalSupply = 102400000000 * pointMultiplier; uint256 public constant percentForSale = 50; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; function ClearToken( address _stateControl , address _whitelistControl , address _withdrawControl , address _tokenAssignmentControl , address _reserves ) public { stateControl = _stateControl; whitelistControl = _whitelistControl; withdrawControl = _withdrawControl; tokenAssignmentControl = _tokenAssignmentControl; moveToState(States.Initial); endTimestamp = 0; ETH_CLEAR = 0; totalSupply = maxTotalSupply; soldTokens = 0; reserves = _reserves; balances[reserves] = totalSupply; Mint(reserves, totalSupply); Transfer(0x0, reserves, totalSupply); } event Whitelisted(address addr); event StateTransition(States oldState, States newState); modifier onlyWhitelist() { require(msg.sender == whitelistControl); _; } modifier onlyStateControl() { require(msg.sender == stateControl); _; } modifier onlyTokenAssignmentControl() { require(msg.sender == tokenAssignmentControl); _; } modifier onlyWithdraw() { require(msg.sender == withdrawControl); _; } modifier requireState(States _requiredState) { require(state == _requiredState); _; } function() payable public requireState(States.Ico) { require(whitelist[msg.sender] == true); require(block.timestamp < endTimestamp); require(block.number >= startAcceptingFundsBlock); uint256 soldToTuserWithBonus = calcBonus(msg.value); issueTokensToUser(msg.sender, soldToTuserWithBonus); ethPossibleRefunds[msg.sender] = ethPossibleRefunds[msg.sender].add(msg.value); } function issueTokensToUser(address beneficiary, uint256 amount) internal { uint256 soldTokensAfterInvestment = soldTokens.add(amount); require(soldTokensAfterInvestment <= maxTotalSupply.mul(percentForSale).div(100)); balances[beneficiary] = balances[beneficiary].add(amount); balances[reserves] = balances[reserves].sub(amount); soldTokens = soldTokensAfterInvestment; Transfer(reserves, beneficiary, amount); } function calcBonus(uint256 weiAmount) constant public returns (uint256 resultingTokens) { uint256 basisTokens = weiAmount.mul(ETH_CLEAR); uint256 perMillBonus = Bonus.getBonusFactor(basisTokens, now); return basisTokens.mul(per_mill + perMillBonus).div(per_mill); } uint256 constant per_mill = 1000; function moveToState(States _newState) internal { StateTransition(state, _newState); state = _newState; } function updateEthICOVariables(uint256 _new_ETH_NZD, uint256 _newEndTimestamp) public onlyStateControl { require(state == States.Initial || state == States.ValuationSet); require(_new_ETH_NZD > 0); require(block.timestamp < _newEndTimestamp); endTimestamp = _newEndTimestamp; ETH_CLEAR = _new_ETH_NZD.mul(NZD_CLEAR); moveToState(States.ValuationSet); } function updateETHNZD(uint256 _new_ETH_NZD) public onlyTokenAssignmentControl requireState(States.Ico) { require(_new_ETH_NZD > 0); ETH_CLEAR = _new_ETH_NZD.mul(NZD_CLEAR); } function startICO() public onlyStateControl requireState(States.ValuationSet) { require(block.timestamp < endTimestamp); startAcceptingFundsBlock = block.number; moveToState(States.Ico); } function addPresaleAmount(address beneficiary, uint256 amount) public onlyTokenAssignmentControl { require(state == States.ValuationSet || state == States.Ico); issueTokensToUser(beneficiary, amount); } function endICO() public onlyStateControl requireState(States.Ico) { finishMinting(); moveToState(States.Operational); } function anyoneEndICO() public requireState(States.Ico) { require(block.timestamp > endTimestamp); finishMinting(); moveToState(States.Operational); } function finishMinting() internal { mintingFinished = true; MintFinished(); } function addToWhitelist(address _whitelisted) public onlyWhitelist { whitelist[_whitelisted] = true; Whitelisted(_whitelisted); } function pause() public onlyStateControl requireState(States.Ico) { moveToState(States.Paused); } function abort() public onlyStateControl requireState(States.Paused) { moveToState(States.Underfunded); } function resumeICO() public onlyStateControl requireState(States.Paused) { moveToState(States.Ico); } function requestRefund() public requireState(States.Underfunded) { require(ethPossibleRefunds[msg.sender] > 0); uint256 payout = ethPossibleRefunds[msg.sender]; ethPossibleRefunds[msg.sender] = 0; msg.sender.transfer(payout); } function requestPayout(uint _amount) public onlyWithdraw requireState(States.Operational) { msg.sender.transfer(_amount); } function rescueToken(ERC20Basic _foreignToken, address _to) public onlyTokenAssignmentControl requireState(States.Operational) { _foreignToken.transfer(_to, _foreignToken.balanceOf(this)); } function transfer(address _to, uint256 _value) public requireState(States.Operational) returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public requireState(States.Operational) returns (bool success) { return super.transferFrom(_from, _to, _value); } function balanceOf(address _account) public constant returns (uint256 balance) { return balances[_account]; } }
0
907
pragma solidity ^0.4.4; contract ERC223Token { function transfer(address _from, uint _value, bytes _data) public; } contract Operations { mapping (address => uint) public balances; mapping (address => bytes32) public activeCall; mapping (bytes32 => address) public recipientsMap; mapping (address => uint) public endCallRequestDate; uint endCallRequestDelay = 1 hours; ERC223Token public exy; function Operations() public { exy = ERC223Token(0xFA74F89A6d4a918167C51132614BbBE193Ee8c22); } function tokenFallback(address _from, uint _value, bytes _data) public { balances[_from] += _value; } function withdraw(uint value) public { require(activeCall[msg.sender] == 0x0); uint balance = balances[msg.sender]; require(value <= balance); balances[msg.sender] -= value; bytes memory empty; exy.transfer(msg.sender, value, empty); } function startCall(uint timestamp, uint8 _v, bytes32 _r, bytes32 _s) public { address recipient = msg.sender; bytes32 callHash = keccak256('Experty.io startCall:', recipient, timestamp); address caller = ecrecover(callHash, _v, _r, _s); require(activeCall[caller] == 0x0); activeCall[caller] = callHash; recipientsMap[callHash] = recipient; endCallRequestDate[caller] = 0; } function endCall(bytes32 callHash, uint amount, uint8 _v, bytes32 _r, bytes32 _s) public { address recipient = recipientsMap[callHash]; require(recipient == msg.sender); bytes32 endHash = keccak256('Experty.io endCall:', recipient, callHash, amount); address caller = ecrecover(endHash, _v, _r, _s); require(activeCall[caller] == callHash); uint maxAmount = amount; if (maxAmount > balances[caller]) { maxAmount = balances[caller]; } recipientsMap[callHash] = 0x0; activeCall[caller] = 0x0; settlePayment(caller, msg.sender, maxAmount); } function requestEndCall() public { require(activeCall[msg.sender] != 0x0); endCallRequestDate[msg.sender] = block.timestamp; } function forceEndCall() public { require(activeCall[msg.sender] != 0x0); require(endCallRequestDate[msg.sender] != 0); require(endCallRequestDate[msg.sender] + endCallRequestDelay < block.timestamp); endCallRequestDate[msg.sender] = 0; recipientsMap[activeCall[msg.sender]] = 0x0; activeCall[msg.sender] = 0x0; } function settlePayment(address sender, address recipient, uint value) private { balances[sender] -= value; balances[recipient] += value; } }
0
1,289
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SafeDecimalMath { using SafeMath for uint; uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; uint public constant UNIT = 10 ** uint(decimals); uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); function unit() external pure returns (uint) { return UNIT; } function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } function multiplyDecimal(uint x, uint y) internal pure returns (uint) { return x.mul(y) / UNIT; } function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } function divideDecimal(uint x, uint y) internal pure returns (uint) { return x.mul(UNIT).div(y); } function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } contract State is Owned { address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } event AssociatedContractUpdated(address associatedContract); } contract TokenState is State { mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } contract Proxyable is Owned { Proxy public proxy; address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy, "Only the proxy can call this function"); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner, "This action can only be performed by the owner"); _; } event ProxyUpdated(address proxyAddress); } contract ReentrancyPreventer { bool isInFunctionBody = false; modifier preventReentrancy { require(!isInFunctionBody, "Reverted to prevent reentrancy"); isInFunctionBody = true; _; isInFunctionBody = false; } } contract TokenFallbackCaller is ReentrancyPreventer { function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data) internal preventReentrancy { uint length; assembly { length := extcodesize(recipient) } if (length > 0) { recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data)); } } } contract ExternStateToken is SelfDestructible, Proxyable, TokenFallbackCaller { using SafeMath for uint; using SafeDecimalMath for uint; TokenState public tokenState; string public name; string public symbol; uint public totalSupply; uint8 public decimals; constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); callTokenFallbackIfNeeded(from, to, value, data); emitTransfer(from, to, value); return true; } function _transfer_byProxy(address from, address to, uint value, bytes data) internal returns (bool) { return _internalTransfer(from, to, value, data); } function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data) internal returns (bool) { tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value, data); } function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } contract LimitedSetup { uint setupExpiryTime; constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } contract SynthetixEscrow is Owned, LimitedSetup(8 weeks) { using SafeMath for uint; Synthetix public synthetix; mapping(address => uint[2][]) public vestingSchedules; mapping(address => uint) public totalVestedAccountBalance; uint public totalVestedBalance; uint constant TIME_INDEX = 0; uint constant QUANTITY_INDEX = 1; uint constant MAX_VESTING_ENTRIES = 20; constructor(address _owner, Synthetix _synthetix) Owned(_owner) public { synthetix = _synthetix; } function setSynthetix(Synthetix _synthetix) external onlyOwner { synthetix = _synthetix; emit SynthetixUpdated(_synthetix); } function balanceOf(address account) public view returns (uint) { return totalVestedAccountBalance[account]; } function numVestingEntries(address account) public view returns (uint) { return vestingSchedules[account].length; } function getVestingScheduleEntry(address account, uint index) public view returns (uint[2]) { return vestingSchedules[account][index]; } function getVestingTime(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[TIME_INDEX]; } function getVestingQuantity(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[QUANTITY_INDEX]; } function getNextVestingIndex(address account) public view returns (uint) { uint len = numVestingEntries(account); for (uint i = 0; i < len; i++) { if (getVestingTime(account, i) != 0) { return i; } } return len; } function getNextVestingEntry(address account) public view returns (uint[2]) { uint index = getNextVestingIndex(account); if (index == numVestingEntries(account)) { return [uint(0), 0]; } return getVestingScheduleEntry(account, index); } function getNextVestingTime(address account) external view returns (uint) { return getNextVestingEntry(account)[TIME_INDEX]; } function getNextVestingQuantity(address account) external view returns (uint) { return getNextVestingEntry(account)[QUANTITY_INDEX]; } function withdrawSynthetix(uint quantity) external onlyOwner onlyDuringSetup { synthetix.transfer(synthetix, quantity); } function purgeAccount(address account) external onlyOwner onlyDuringSetup { delete vestingSchedules[account]; totalVestedBalance = totalVestedBalance.sub(totalVestedAccountBalance[account]); delete totalVestedAccountBalance[account]; } function appendVestingEntry(address account, uint time, uint quantity) public onlyOwner onlyDuringSetup { require(now < time, "Time must be in the future"); require(quantity != 0, "Quantity cannot be zero"); totalVestedBalance = totalVestedBalance.add(quantity); require(totalVestedBalance <= synthetix.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry"); uint scheduleLength = vestingSchedules[account].length; require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long"); if (scheduleLength == 0) { totalVestedAccountBalance[account] = quantity; } else { require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one"); totalVestedAccountBalance[account] = totalVestedAccountBalance[account].add(quantity); } vestingSchedules[account].push([time, quantity]); } function addVestingSchedule(address account, uint[] times, uint[] quantities) external onlyOwner onlyDuringSetup { for (uint i = 0; i < times.length; i++) { appendVestingEntry(account, times[i], quantities[i]); } } function vest() external { uint numEntries = numVestingEntries(msg.sender); uint total; for (uint i = 0; i < numEntries; i++) { uint time = getVestingTime(msg.sender, i); if (time > now) { break; } uint qty = getVestingQuantity(msg.sender, i); if (qty == 0) { continue; } vestingSchedules[msg.sender][i] = [0, 0]; total = total.add(qty); } if (total != 0) { totalVestedBalance = totalVestedBalance.sub(total); totalVestedAccountBalance[msg.sender] = totalVestedAccountBalance[msg.sender].sub(total); synthetix.transfer(msg.sender, total); emit Vested(msg.sender, now, total); } } event SynthetixUpdated(address newSynthetix); event Vested(address indexed beneficiary, uint time, uint value); } contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; struct IssuanceData { uint initialDebtOwnership; uint debtEntryIndex; } mapping(address => IssuanceData) public issuanceData; uint public totalIssuerCount; uint[] public debtLedger; uint public importedXDRAmount; uint public issuanceRatio = SafeDecimalMath.unit() / 5; uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); mapping(address => bytes4) public preferredCurrency; constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } function _addToDebtRegister(address account, uint amount) internal { Synthetix synthetix = Synthetix(associatedContract); uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); uint totalDebtIssued = importedXDRAmount; uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); importedXDRAmount = newTotalDebtIssued; uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } function debtLedgerLength() external view returns (uint) { return debtLedger.length; } function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); } contract ExchangeRates is SelfDestructible { using SafeMath for uint; mapping(bytes4 => uint) public rates; mapping(bytes4 => uint) public lastRateUpdateTimes; address public oracle; uint constant ORACLE_FUTURE_LIMIT = 10 minutes; uint public rateStalePeriod = 3 hours; bytes4[5] public xdrParticipants; struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes4 => InversePricing) public inversePricing; bytes4[] public invertedKeys; constructor( address _owner, address _oracle, bytes4[] _currencyKeys, uint[] _newRates ) SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; rates["sUSD"] = SafeDecimalMath.unit(); lastRateUpdateTimes["sUSD"] = now; xdrParticipants = [ bytes4("sUSD"), bytes4("sAUD"), bytes4("sCHF"), bytes4("sEUR"), bytes4("sGBP") ]; internalUpdateRates(_currencyKeys, _newRates, now); } function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); for (uint i = 0; i < currencyKeys.length; i++) { require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); if (timeSent < lastRateUpdateTimes[currencyKeys[i]]) { continue; } newRates[i] = rateOrInverted(currencyKeys[i], newRates[i]); rates[currencyKeys[i]] = newRates[i]; lastRateUpdateTimes[currencyKeys[i]] = timeSent; } emit RatesUpdated(currencyKeys, newRates); updateXDRRate(timeSent); return true; } function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) { InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } uint newInverseRate = rates[currencyKey]; if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } function updateXDRRate(uint timeSent) internal { uint total = 0; for (uint i = 0; i < xdrParticipants.length; i++) { total = rates[xdrParticipants[i]].add(total); } rates["XDR"] = total; lastRateUpdateTimes["XDR"] = timeSent; bytes4[] memory eventCurrencyCode = new bytes4[](1); eventCurrencyCode[0] = "XDR"; uint[] memory eventRate = new uint[](1); eventRate[0] = rates["XDR"]; emit RatesUpdated(eventCurrencyCode, eventRate); } function deleteRate(bytes4 currencyKey) external onlyOracle { require(rates[currencyKey] > 0, "Rate is zero"); delete rates[currencyKey]; delete lastRateUpdateTimes[currencyKey]; emit RateDeleted(currencyKey); } function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = false; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function removeInversePricing(bytes4 currencyKey) external onlyOwner { inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; for (uint8 i = 0; i < invertedKeys.length; i++) { if (invertedKeys[i] == currencyKey) { delete invertedKeys[i]; invertedKeys[i] = invertedKeys[invertedKeys.length - 1]; invertedKeys.length--; break; } } emit InversePriceConfigured(currencyKey, 0, 0, 0); } function rateForCurrency(bytes4 currencyKey) public view returns (uint) { return rates[currencyKey]; } function ratesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory _rates = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { _rates[i] = rates[currencyKeys[i]]; } return _rates; } function lastRateUpdateTimeForCurrency(bytes4 currencyKey) public view returns (uint) { return lastRateUpdateTimes[currencyKey]; } function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]]; } return lastUpdateTimes; } function rateIsStale(bytes4 currencyKey) external view returns (bool) { if (currencyKey == "sUSD") return false; return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now; } function rateIsFrozen(bytes4 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } function anyRateIsStale(bytes4[] currencyKeys) external view returns (bool) { uint256 i = 0; while (i < currencyKeys.length) { if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) { return true; } i += 1; } return false; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes4[] currencyKeys, uint[] newRates); event RateDeleted(bytes4 currencyKey); event InversePriceConfigured(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes4 currencyKey); } contract Synthetix is ExternStateToken { Synth[] public availableSynths; mapping(bytes4 => Synth) public synths; FeePool public feePool; SynthetixEscrow public escrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; uint constant SYNTHETIX_SUPPLY = 1e8 * SafeDecimalMath.unit(); string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, FeePool _feePool ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, SYNTHETIX_SUPPLY, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; } function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes4 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); availableSynths.push(synth); synths[currencyKey] = synth; emitSynthAdded(currencyKey, synth); } function removeSynth(bytes4 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR", "Cannot remove XDR synth"); address synthToRemove = synths[currencyKey]; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; availableSynths[i] = availableSynths[availableSynths.length - 1]; availableSynths.length--; break; } } delete synths[currencyKey]; emitSynthRemoved(currencyKey, synthToRemove); } function setEscrow(SynthetixEscrow _escrow) external optionalProxy_onlyOwner { escrow = _escrow; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setSynthetixState(SynthetixState _synthetixState) external optionalProxy_onlyOwner { synthetixState = _synthetixState; emitStateContractChanged(_synthetixState); } function setPreferredCurrency(bytes4 currencyKey) external optionalProxy { require(currencyKey == 0 || !exchangeRates.rateIsStale(currencyKey), "Currency rate is stale or doesn't exist."); synthetixState.setPreferredCurrency(messageSender, currencyKey); emitPreferredCurrencyChanged(messageSender, currencyKey); } function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; return sourceAmount.multiplyDecimalRound(exchangeRates.rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(exchangeRates.rateForCurrency(destinationCurrencyKey)); } function totalIssuedSynths(bytes4 currencyKey) public view rateNotStale(currencyKey) returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale"); for (uint8 i = 0; i < availableSynths.length; i++) { uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey())) .divideDecimalRound(currencyRate); total = total.add(synthValue); } return total; } function availableCurrencyKeys() internal view returns (bytes4[]) { bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length); for (uint8 i = 0; i < availableSynths.length; i++) { availableCurrencyKeys[i] = availableSynths[i].currencyKey(); } return availableCurrencyKeys; } function availableSynthCount() public view returns (uint) { return availableSynths.length; } function transfer(address to, uint value) public returns (bool) { bytes memory empty; return transfer(to, value, empty); } function transfer(address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(messageSender), "Insufficient balance"); _transfer_byProxy(messageSender, to, value, data); return true; } function transferFrom(address from, address to, uint value) public returns (bool) { bytes memory empty; return transferFrom(from, to, value, empty); } function transferFrom(address from, address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(from), "Insufficient balance"); _transferFrom_byProxy(messageSender, from, to, value, data); return true; } function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress) external optionalProxy returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths"); require(sourceAmount > 0, "Zero amount"); return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress == address(0) ? messageSender : destinationAddress, true ); } function synthInitiatedExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress ) external onlySynth returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } function synthInitiatedFeePayment( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) external onlySynth returns (bool) { if (sourceAmount == 0) { return true; } require(sourceAmount > 0, "Source can't be 0"); bool result = _internalExchange( from, sourceCurrencyKey, sourceAmount, "XDR", feePool.FEE_ADDRESS(), false ); feePool.feePaid(sourceCurrencyKey, sourceAmount); return result; } function _internalExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal notFeeAddress(from) returns (bool) { require(destinationAddress != address(0), "Zero destination"); require(destinationAddress != address(this), "Synthetix is invalid destination"); require(destinationAddress != address(proxy), "Proxy is invalid destination"); synths[sourceCurrencyKey].burn(from, sourceAmount); uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { amountReceived = feePool.amountReceivedFromExchange(destinationAmount); fee = destinationAmount.sub(amountReceived); } synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); } synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived); emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } function _addToDebtRegister(bytes4 currencyKey, uint amount) internal optionalProxy { uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = debtBalanceOf(messageSender, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (!synthetixState.hasIssued(messageSender)) { synthetixState.incrementTotalIssuerCount(); } synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } function issueSynths(bytes4 currencyKey, uint amount) public optionalProxy nonZeroAmount(amount) { require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); _addToDebtRegister(currencyKey, amount); synths[currencyKey].issue(messageSender, amount); } function issueMaxSynths(bytes4 currencyKey) external optionalProxy { uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); issueSynths(currencyKey, maxIssuable); } function burnSynths(bytes4 currencyKey, uint amount) external optionalProxy { uint debt = debtBalanceOf(messageSender, currencyKey); require(debt > 0, "No debt to forgive"); uint amountToBurn = debt < amount ? debt : amount; _removeFromDebtRegister(currencyKey, amountToBurn); synths[currencyKey].burn(messageSender, amountToBurn); } function _removeFromDebtRegister(bytes4 currencyKey, uint amount) internal { uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(totalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().add(debtPercentage); if (debtToRemove == existingDebt) { synthetixState.clearIssuanceData(messageSender); synthetixState.decrementTotalIssuerCount(); } else { uint newDebt = existingDebt.sub(debtToRemove); uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } function maxIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } function debtBalanceOf(address issuer, bytes4 currencyKey) public view returns (uint) { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); if (initialDebtOwnership == 0) return 0; uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); uint totalSystemValue = totalIssuedSynths(currencyKey); uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); return highPrecisionBalance.preciseDecimalToDecimal(); } function remainingIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } return balance; } function transferableSynthetix(address account) public view rateNotStale("SNX") returns (uint) { uint balance = tokenState.balanceOf(account); uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } modifier rateNotStale(bytes4 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Fee address not allowed"); _; } modifier onlySynth() { bool isSynth = false; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == msg.sender) { isSynth = true; break; } } require(isSynth, "Only synth allowed"); _; } modifier nonZeroAmount(uint _amount) { require(_amount > 0, "Amount needs to be larger than 0"); _; } event SynthExchange(address indexed account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes4,uint256,bytes4,uint256,address)"); function emitSynthExchange(address account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } event PreferredCurrencyChanged(address indexed account, bytes4 newPreferredCurrency); bytes32 constant PREFERREDCURRENCYCHANGED_SIG = keccak256("PreferredCurrencyChanged(address,bytes4)"); function emitPreferredCurrencyChanged(address account, bytes4 newPreferredCurrency) internal { proxy._emit(abi.encode(newPreferredCurrency), 2, PREFERREDCURRENCYCHANGED_SIG, bytes32(account), 0, 0); } event StateContractChanged(address stateContract); bytes32 constant STATECONTRACTCHANGED_SIG = keccak256("StateContractChanged(address)"); function emitStateContractChanged(address stateContract) internal { proxy._emit(abi.encode(stateContract), 1, STATECONTRACTCHANGED_SIG, 0, 0, 0); } event SynthAdded(bytes4 currencyKey, address newSynth); bytes32 constant SYNTHADDED_SIG = keccak256("SynthAdded(bytes4,address)"); function emitSynthAdded(bytes4 currencyKey, address newSynth) internal { proxy._emit(abi.encode(currencyKey, newSynth), 1, SYNTHADDED_SIG, 0, 0, 0); } event SynthRemoved(bytes4 currencyKey, address removedSynth); bytes32 constant SYNTHREMOVED_SIG = keccak256("SynthRemoved(bytes4,address)"); function emitSynthRemoved(bytes4 currencyKey, address removedSynth) internal { proxy._emit(abi.encode(currencyKey, removedSynth), 1, SYNTHREMOVED_SIG, 0, 0, 0); } } contract FeePool is Proxyable, SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; Synthetix public synthetix; uint public transferFeeRate; uint constant public MAX_TRANSFER_FEE_RATE = SafeDecimalMath.unit() / 10; uint public exchangeFeeRate; uint constant public MAX_EXCHANGE_FEE_RATE = SafeDecimalMath.unit() / 10; address public feeAuthority; address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; struct FeePeriod { uint feePeriodId; uint startingDebtIndex; uint startTime; uint feesToDistribute; uint feesClaimed; } uint8 constant public FEE_PERIOD_LENGTH = 6; FeePeriod[FEE_PERIOD_LENGTH] public recentFeePeriods; uint public nextFeePeriodId; uint public feePeriodDuration = 1 weeks; uint public constant MIN_FEE_PERIOD_DURATION = 1 days; uint public constant MAX_FEE_PERIOD_DURATION = 60 days; mapping(address => uint) public lastFeeWithdrawal; uint constant TWENTY_PERCENT = (20 * SafeDecimalMath.unit()) / 100; uint constant TWENTY_FIVE_PERCENT = (25 * SafeDecimalMath.unit()) / 100; uint constant THIRTY_PERCENT = (30 * SafeDecimalMath.unit()) / 100; uint constant FOURTY_PERCENT = (40 * SafeDecimalMath.unit()) / 100; uint constant FIFTY_PERCENT = (50 * SafeDecimalMath.unit()) / 100; uint constant SEVENTY_FIVE_PERCENT = (75 * SafeDecimalMath.unit()) / 100; constructor(address _proxy, address _owner, Synthetix _synthetix, address _feeAuthority, uint _transferFeeRate, uint _exchangeFeeRate) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate"); require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "Constructed exchange fee rate should respect the maximum fee rate"); synthetix = _synthetix; feeAuthority = _feeAuthority; transferFeeRate = _transferFeeRate; exchangeFeeRate = _exchangeFeeRate; recentFeePeriods[0].feePeriodId = 1; recentFeePeriods[0].startTime = now; nextFeePeriodId = 2; } function setExchangeFeeRate(uint _exchangeFeeRate) external optionalProxy_onlyOwner { require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "Exchange fee rate must be below MAX_EXCHANGE_FEE_RATE"); exchangeFeeRate = _exchangeFeeRate; emitExchangeFeeUpdated(_exchangeFeeRate); } function setTransferFeeRate(uint _transferFeeRate) external optionalProxy_onlyOwner { require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE"); transferFeeRate = _transferFeeRate; emitTransferFeeUpdated(_transferFeeRate); } function setFeeAuthority(address _feeAuthority) external optionalProxy_onlyOwner { feeAuthority = _feeAuthority; emitFeeAuthorityUpdated(_feeAuthority); } function setFeePeriodDuration(uint _feePeriodDuration) external optionalProxy_onlyOwner { require(_feePeriodDuration >= MIN_FEE_PERIOD_DURATION, "New fee period cannot be less than minimum fee period duration"); require(_feePeriodDuration <= MAX_FEE_PERIOD_DURATION, "New fee period cannot be greater than maximum fee period duration"); feePeriodDuration = _feePeriodDuration; emitFeePeriodDurationUpdated(_feePeriodDuration); } function setSynthetix(Synthetix _synthetix) external optionalProxy_onlyOwner { require(address(_synthetix) != address(0), "New Synthetix must be non-zero"); synthetix = _synthetix; emitSynthetixUpdated(_synthetix); } function feePaid(bytes4 currencyKey, uint amount) external onlySynthetix { uint xdrAmount = synthetix.effectiveValue(currencyKey, amount, "XDR"); recentFeePeriods[0].feesToDistribute = recentFeePeriods[0].feesToDistribute.add(xdrAmount); } function closeCurrentFeePeriod() external onlyFeeAuthority { require(recentFeePeriods[0].startTime <= (now - feePeriodDuration), "It is too early to close the current fee period"); FeePeriod memory secondLastFeePeriod = recentFeePeriods[FEE_PERIOD_LENGTH - 2]; FeePeriod memory lastFeePeriod = recentFeePeriods[FEE_PERIOD_LENGTH - 1]; recentFeePeriods[FEE_PERIOD_LENGTH - 2].feesToDistribute = lastFeePeriod.feesToDistribute .sub(lastFeePeriod.feesClaimed) .add(secondLastFeePeriod.feesToDistribute); for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) { uint next = i + 1; recentFeePeriods[next].feePeriodId = recentFeePeriods[i].feePeriodId; recentFeePeriods[next].startingDebtIndex = recentFeePeriods[i].startingDebtIndex; recentFeePeriods[next].startTime = recentFeePeriods[i].startTime; recentFeePeriods[next].feesToDistribute = recentFeePeriods[i].feesToDistribute; recentFeePeriods[next].feesClaimed = recentFeePeriods[i].feesClaimed; } delete recentFeePeriods[0]; recentFeePeriods[0].feePeriodId = nextFeePeriodId; recentFeePeriods[0].startingDebtIndex = synthetix.synthetixState().debtLedgerLength(); recentFeePeriods[0].startTime = now; nextFeePeriodId = nextFeePeriodId.add(1); emitFeePeriodClosed(recentFeePeriods[1].feePeriodId); } function claimFees(bytes4 currencyKey) external optionalProxy returns (bool) { uint availableFees = feesAvailable(messageSender, "XDR"); require(availableFees > 0, "No fees available for period, or fees already claimed"); lastFeeWithdrawal[messageSender] = recentFeePeriods[1].feePeriodId; _recordFeePayment(availableFees); _payFees(messageSender, availableFees, currencyKey); emitFeesClaimed(messageSender, availableFees); return true; } function _recordFeePayment(uint xdrAmount) internal { uint remainingToAllocate = xdrAmount; for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) { uint delta = recentFeePeriods[i].feesToDistribute.sub(recentFeePeriods[i].feesClaimed); if (delta > 0) { uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate; recentFeePeriods[i].feesClaimed = recentFeePeriods[i].feesClaimed.add(amountInPeriod); remainingToAllocate = remainingToAllocate.sub(amountInPeriod); if (remainingToAllocate == 0) return; } } assert(remainingToAllocate == 0); } function _payFees(address account, uint xdrAmount, bytes4 destinationCurrencyKey) internal notFeeAddress(account) { require(account != address(0), "Account can't be 0"); require(account != address(this), "Can't send fees to fee pool"); require(account != address(proxy), "Can't send fees to proxy"); require(account != address(synthetix), "Can't send fees to synthetix"); Synth xdrSynth = synthetix.synths("XDR"); Synth destinationSynth = synthetix.synths(destinationCurrencyKey); xdrSynth.burn(FEE_ADDRESS, xdrAmount); uint destinationAmount = synthetix.effectiveValue("XDR", xdrAmount, destinationCurrencyKey); destinationSynth.issue(account, destinationAmount); destinationSynth.triggerTokenFallbackIfNeeded(FEE_ADDRESS, account, destinationAmount); } function transferFeeIncurred(uint value) public view returns (uint) { return value.multiplyDecimal(transferFeeRate); } function transferredAmountToReceive(uint value) external view returns (uint) { return value.add(transferFeeIncurred(value)); } function amountReceivedFromTransfer(uint value) external view returns (uint) { return value.divideDecimal(transferFeeRate.add(SafeDecimalMath.unit())); } function exchangeFeeIncurred(uint value) public view returns (uint) { return value.multiplyDecimal(exchangeFeeRate); } function exchangedAmountToReceive(uint value) external view returns (uint) { return value.add(exchangeFeeIncurred(value)); } function amountReceivedFromExchange(uint value) external view returns (uint) { return value.divideDecimal(exchangeFeeRate.add(SafeDecimalMath.unit())); } function totalFeesAvailable(bytes4 currencyKey) external view returns (uint) { uint totalFees = 0; for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(recentFeePeriods[i].feesToDistribute); totalFees = totalFees.sub(recentFeePeriods[i].feesClaimed); } return synthetix.effectiveValue("XDR", totalFees, currencyKey); } function feesAvailable(address account, bytes4 currencyKey) public view returns (uint) { uint[FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account); uint totalFees = 0; for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(userFees[i]); } return synthetix.effectiveValue("XDR", totalFees, currencyKey); } function currentPenalty(address account) public view returns (uint) { uint ratio = synthetix.collateralisationRatio(account); if (ratio <= TWENTY_PERCENT) { return 0; } else if (ratio > TWENTY_PERCENT && ratio <= THIRTY_PERCENT) { return TWENTY_FIVE_PERCENT; } else if (ratio > THIRTY_PERCENT && ratio <= FOURTY_PERCENT) { return FIFTY_PERCENT; } return SEVENTY_FIVE_PERCENT; } function feesByPeriod(address account) public view returns (uint[FEE_PERIOD_LENGTH]) { uint[FEE_PERIOD_LENGTH] memory result; uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetix.synthetixState().issuanceData(account); if (initialDebtOwnership == 0) return result; uint totalSynths = synthetix.totalIssuedSynths("XDR"); if (totalSynths == 0) return result; uint debtBalance = synthetix.debtBalanceOf(account, "XDR"); uint userOwnershipPercentage = debtBalance.divideDecimal(totalSynths); uint penalty = currentPenalty(account); for (uint i = 0; i < FEE_PERIOD_LENGTH; i++) { if (recentFeePeriods[i].startingDebtIndex > debtEntryIndex && lastFeeWithdrawal[account] < recentFeePeriods[i].feePeriodId) { uint feesFromPeriodWithoutPenalty = recentFeePeriods[i].feesToDistribute .multiplyDecimal(userOwnershipPercentage); uint penaltyFromPeriod = feesFromPeriodWithoutPenalty.multiplyDecimal(penalty); uint feesFromPeriod = feesFromPeriodWithoutPenalty.sub(penaltyFromPeriod); result[i] = feesFromPeriod; } } return result; } modifier onlyFeeAuthority { require(msg.sender == feeAuthority, "Only the fee authority can perform this action"); _; } modifier onlySynthetix { require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action"); _; } modifier notFeeAddress(address account) { require(account != FEE_ADDRESS, "Fee address not allowed"); _; } event TransferFeeUpdated(uint newFeeRate); bytes32 constant TRANSFERFEEUPDATED_SIG = keccak256("TransferFeeUpdated(uint256)"); function emitTransferFeeUpdated(uint newFeeRate) internal { proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEEUPDATED_SIG, 0, 0, 0); } event ExchangeFeeUpdated(uint newFeeRate); bytes32 constant EXCHANGEFEEUPDATED_SIG = keccak256("ExchangeFeeUpdated(uint256)"); function emitExchangeFeeUpdated(uint newFeeRate) internal { proxy._emit(abi.encode(newFeeRate), 1, EXCHANGEFEEUPDATED_SIG, 0, 0, 0); } event FeePeriodDurationUpdated(uint newFeePeriodDuration); bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)"); function emitFeePeriodDurationUpdated(uint newFeePeriodDuration) internal { proxy._emit(abi.encode(newFeePeriodDuration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0); } event FeeAuthorityUpdated(address newFeeAuthority); bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)"); function emitFeeAuthorityUpdated(address newFeeAuthority) internal { proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0); } event FeePeriodClosed(uint feePeriodId); bytes32 constant FEEPERIODCLOSED_SIG = keccak256("FeePeriodClosed(uint256)"); function emitFeePeriodClosed(uint feePeriodId) internal { proxy._emit(abi.encode(feePeriodId), 1, FEEPERIODCLOSED_SIG, 0, 0, 0); } event FeesClaimed(address account, uint xdrAmount); bytes32 constant FEESCLAIMED_SIG = keccak256("FeesClaimed(address,uint256)"); function emitFeesClaimed(address account, uint xdrAmount) internal { proxy._emit(abi.encode(account, xdrAmount), 1, FEESCLAIMED_SIG, 0, 0, 0); } event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } } contract Synth is ExternStateToken { FeePool public feePool; Synthetix public synthetix; bytes4 public currencyKey; uint8 constant DECIMALS = 18; constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, FeePool _feePool, string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, 0, DECIMALS, _owner) public { require(_proxy != 0, "_proxy cannot be 0"); require(address(_synthetix) != 0, "_synthetix cannot be 0"); require(address(_feePool) != 0, "_feePool cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(_synthetix.synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePool = _feePool; synthetix = _synthetix; currencyKey = _currencyKey; } function setSynthetix(Synthetix _synthetix) external optionalProxy_onlyOwner { synthetix = _synthetix; emitSynthetixUpdated(_synthetix); } function setFeePool(FeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; emitFeePoolUpdated(_feePool); } function transfer(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); bytes memory empty; return _internalTransfer(messageSender, to, amountReceived, empty); } function transfer(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); return _internalTransfer(messageSender, to, amountReceived, data); } function transferFrom(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, amountReceived, empty); } function transferFrom(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, amountReceived, data); } function transferSenderPaysFee(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); bytes memory empty; return _internalTransfer(messageSender, to, value, empty); } function transferSenderPaysFee(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); return _internalTransfer(messageSender, to, value, data); } function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, value, empty); } function transferFromSenderPaysFee(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, value, data); } function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to); if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) { return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to); } else { return super._internalTransfer(from, to, value, data); } } function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount) external onlySynthetixOrFeePool { bytes memory empty; callTokenFallbackIfNeeded(sender, recipient, amount, empty); } modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(synthetix); bool isFeePool = msg.sender == address(feePool); require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address"); _; } event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } }
1
4,364
pragma solidity ^0.4.25; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ReentrancyGuard { uint256 private _guardCounter; constructor () internal { _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } contract Crowdsale is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 private _token; address private _wallet; uint256 private _rate; uint256 private _weiRaised; event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor (uint256 rate, address wallet, IERC20 token) internal { require(rate > 0); require(wallet != address(0)); require(token != address(0)); _rate = rate; _wallet = wallet; _token = token; } function () external payable { buyTokens(msg.sender); } function token() public view returns (IERC20) { return _token; } function wallet() public view returns (address) { return _wallet; } function rate() public view returns (uint256) { return _rate; } function weiRaised() public view returns (uint256) { return _weiRaised; } function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0)); require(weiAmount != 0); } function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { } function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { } function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } function _forwardFunds() internal { _wallet.transfer(msg.value); } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _cap; constructor (uint256 cap) internal { require(cap > 0); _cap = cap; } function cap() public view returns (uint256) { return _cap; } function capReached() public view returns (bool) { return weiRaised() >= _cap; } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= _cap); } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; modifier onlyWhileOpen { require(isOpen()); _; } constructor (uint256 openingTime, uint256 closingTime) internal { require(openingTime >= block.timestamp); require(closingTime > openingTime); _openingTime = openingTime; _closingTime = closingTime; } function openingTime() public view returns (uint256) { return _openingTime; } function closingTime() public view returns (uint256) { return _closingTime; } function isOpen() public view returns (bool) { return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } function hasClosed() public view returns (bool) { return block.timestamp > _closingTime; } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } } contract FthCrowdsale is CappedCrowdsale, TimedCrowdsale { using SafeMath for uint256; uint256 constant MIN_WEI_AMOUNT = 0.1 ether; uint256 private _rewardPeriod; uint256 private _unlockPeriod; struct Contribution { uint256 contributeTime; uint256 buyTokenAmount; uint256 rewardTokenAmount; uint256 lastWithdrawTime; uint256 withdrawPercent; } mapping(address => Contribution[]) private _contributions; constructor ( uint256 rewardPeriod, uint256 unlockPeriod, uint256 cap, uint256 openingTime, uint256 closingTime, uint256 rate, address wallet, IERC20 token ) public CappedCrowdsale(cap) TimedCrowdsale(openingTime, closingTime) Crowdsale(rate, wallet, token) { _rewardPeriod = rewardPeriod; _unlockPeriod = unlockPeriod; } function contributionsOf(address beneficiary) public view returns ( uint256[] memory contributeTimes, uint256[] memory buyTokenAmounts, uint256[] memory rewardTokenAmounts, uint256[] memory lastWithdrawTimes, uint256[] memory withdrawPercents ) { Contribution[] memory contributions = _contributions[beneficiary]; uint256 length = contributions.length; contributeTimes = new uint256[](length); buyTokenAmounts = new uint256[](length); rewardTokenAmounts = new uint256[](length); lastWithdrawTimes = new uint256[](length); withdrawPercents = new uint256[](length); for (uint256 i = 0; i < length; i++) { contributeTimes[i] = contributions[i].contributeTime; buyTokenAmounts[i] = contributions[i].buyTokenAmount; rewardTokenAmounts[i] = contributions[i].rewardTokenAmount; lastWithdrawTimes[i] = contributions[i].lastWithdrawTime; withdrawPercents[i] = contributions[i].withdrawPercent; } } function withdrawTokens(address beneficiary) public { require(isOver()); if (msg.sender == beneficiary && msg.sender == wallet()) { _withdrawTokensToWallet(); } else { _withdrawTokensTo(beneficiary); } } function unlockBalanceOf(address beneficiary) public view returns (uint256) { uint256 unlockBalance = 0; Contribution[] memory contributions = _contributions[beneficiary]; for (uint256 i = 0; i < contributions.length; i++) { uint256 unlockPercent = _unlockPercent(contributions[i]); if (unlockPercent == 0) { continue; } unlockBalance = unlockBalance.add( contributions[i].buyTokenAmount.mul(unlockPercent).div(100) ).add( contributions[i].rewardTokenAmount.mul(unlockPercent).div(100) ); } return unlockBalance; } function rewardTokenAmount(uint256 buyTokenAmount) public view returns (uint256) { if (!isOpen()) { return 0; } uint256 rewardTokenPercent = 0; uint256 timePeriod = block.timestamp.sub(openingTime()).div(_rewardPeriod); if (timePeriod < 1) { rewardTokenPercent = 15; } else if (timePeriod < 2) { rewardTokenPercent = 10; } else if (timePeriod < 3) { rewardTokenPercent = 5; } else { return 0; } return buyTokenAmount.mul(rewardTokenPercent).div(100); } function rewardPeriod() public view returns (uint256) { return _rewardPeriod; } function unlockPeriod() public view returns (uint256) { return _unlockPeriod; } function isOver() public view returns (bool) { return capReached() || hasClosed(); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(weiAmount >= MIN_WEI_AMOUNT); super._preValidatePurchase(beneficiary, weiAmount); } function _processPurchase(address beneficiary, uint256 buyTokenAmount) internal { Contribution[] storage contributions = _contributions[beneficiary]; require(contributions.length < 100); contributions.push(Contribution({ contributeTime: block.timestamp, buyTokenAmount: buyTokenAmount, rewardTokenAmount: rewardTokenAmount(buyTokenAmount), lastWithdrawTime: 0, withdrawPercent: 0 })); } function _withdrawTokensToWallet() private { uint256 balanceTokenAmount = token().balanceOf(address(this)); require(balanceTokenAmount > 0); _deliverTokens(wallet(), balanceTokenAmount); } function _withdrawTokensTo(address beneficiary) private { uint256 unlockBalance = unlockBalanceOf(beneficiary); require(unlockBalance > 0); Contribution[] storage contributions = _contributions[beneficiary]; for (uint256 i = 0; i < contributions.length; i++) { uint256 unlockPercent = _unlockPercent(contributions[i]); if (unlockPercent == 0) { continue; } contributions[i].lastWithdrawTime = block.timestamp; contributions[i].withdrawPercent = contributions[i].withdrawPercent.add(unlockPercent); } _deliverTokens(beneficiary, unlockBalance); } function _unlockPercent(Contribution memory contribution) private view returns (uint256) { if (contribution.withdrawPercent >= 100) { return 0; } uint256 baseTimestamp = contribution.contributeTime; if (contribution.lastWithdrawTime > baseTimestamp) { baseTimestamp = contribution.lastWithdrawTime; } uint256 period = block.timestamp.sub(baseTimestamp); if (period < _unlockPeriod) { return 0; } uint256 unlockPercent = period.div(_unlockPeriod).sub(1).mul(10); if (contribution.withdrawPercent == 0) { unlockPercent = unlockPercent.add(50); } else { unlockPercent = unlockPercent.add(10); } uint256 max = 100 - contribution.withdrawPercent; if (unlockPercent > max) { unlockPercent = max; } return unlockPercent; } }
0
354
pragma solidity ^0.4.16; interface token { function transfer(address receiver, uint amount); } contract Crowdsale { address public beneficiary; uint public fundingGoal; uint public amountRaised; uint public deadline; uint public price; token public tokenReward; mapping(address => uint256) public balanceOf; bool fundingGoalReached = false; bool crowdsaleClosed = false; event GoalReached(address recipient, uint totalAmountRaised); event FundTransfer(address backer, uint amount, bool isContribution); function Crowdsale( address ifSuccessfulSendTo, uint fundingGoalInEthers, uint durationInMinutes, uint etherCostOfEachToken, address addressOfTokenUsedAsReward ) { beneficiary = ifSuccessfulSendTo; fundingGoal = fundingGoalInEthers * 1 ether; deadline = now + durationInMinutes * 1 minutes; price = etherCostOfEachToken * 1 ether; tokenReward = token(addressOfTokenUsedAsReward); } function () payable { require(!crowdsaleClosed); uint amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; tokenReward.transfer(msg.sender, amount / price); FundTransfer(msg.sender, amount, true); } modifier afterDeadline() { if (now >= deadline) _; } function checkGoalReached() afterDeadline { if (amountRaised >= fundingGoal){ fundingGoalReached = true; GoalReached(beneficiary, amountRaised); } crowdsaleClosed = true; } function safeWithdrawal() afterDeadline { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { FundTransfer(msg.sender, amount, false); } else { balanceOf[msg.sender] = amount; } } } if (fundingGoalReached && beneficiary == msg.sender) { if (beneficiary.send(amountRaised)) { FundTransfer(beneficiary, amountRaised, false); } else { fundingGoalReached = false; } } } }
0
1,090
pragma solidity ^0.4.21; interface ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) external; } library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(owner == msg.sender); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract AlphaToken is Ownable { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); mapping(address => uint) balances; mapping(address => mapping (address => uint256)) allowed; string _name; string _symbol; uint8 DECIMALS = 18; uint256 _totalSupply; uint256 _saledTotal = 0; uint256 _amounToSale = 0; uint _buyPrice = 4500; uint256 _totalEther = 0; function AlphaToken( string tokenName, string tokenSymbol ) public { _totalSupply = 4000000000 * 10 ** uint256(DECIMALS); _amounToSale = _totalSupply; _saledTotal = 0; _name = tokenName; _symbol = tokenSymbol; owner = msg.sender; } function name() public constant returns (string) { return _name; } function symbol() public constant returns (string) { return _symbol; } function totalSupply() public constant returns (uint256) { return _totalSupply; } function buyPrice() public constant returns (uint256) { return _buyPrice; } function decimals() public constant returns (uint8) { return DECIMALS; } function _transfer(address _from, address _to, uint _value, bytes _data) internal { uint codeLength; require (_to != 0x0); require(balances[_from]>=_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); if (codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } emit Transfer(_from, _to, _value); } function transfer(address _to, uint _value, bytes _data) public returns (bool ok) { _transfer(msg.sender, _to, _value, _data); return true; } function transfer(address _to, uint _value) public returns(bool ok) { bytes memory empty; _transfer(msg.sender, _to, _value, empty); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { require(balances[msg.sender]>=tokens); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address _from, address _to, uint _value) onlyOwner public returns (bool success) { require(_value <= allowed[_from][msg.sender]); bytes memory empty; _transfer(_from, _to, _value, empty); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); return true; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } function setPrices(uint256 newBuyPrice) onlyOwner public { _buyPrice = newBuyPrice; } function buyCoin() payable public returns (bool ok) { uint amount = ((msg.value * _buyPrice) * 10 ** uint256(DECIMALS))/1000000000000000000; require ((_amounToSale - _saledTotal)>=amount); balances[msg.sender] = balances[msg.sender].add(amount); _saledTotal = _saledTotal.add(amount); _totalEther += msg.value; return true; } function dispatchTo(address target, uint256 amount) onlyOwner public returns (bool ok) { require ((_amounToSale - _saledTotal)>=amount); balances[target] = balances[target].add(amount); _saledTotal = _saledTotal.add(amount); return true; } function withdrawTo(address _target, uint256 _value) onlyOwner public returns (bool ok) { require(_totalEther <= _value); _totalEther -= _value; _target.transfer(_value); return true; } function () payable public { } }
1
3,744
pragma solidity ^0.4.9; library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value); function approve(address spender, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; modifier onlyPayloadSize(uint256 size) { require(!(msg.data.length < size + 4)); _; } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint256 _value) { require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)) ); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract Pixiu_Beta is StandardToken { uint public decimals = 6; bool public isPayable = true; bool public isWithdrawable = true; struct exchangeRate { uint time1; uint time2; uint value; } struct Member { bool isExists; bool isDividend; bool isWithdraw; uint256 dividend; uint256 withdraw; } exchangeRate[] public exchangeRateArray; mapping (address => Member) public members; address[] public adminArray; address[] public memberArray; address public deposit_address; uint256 public INITIAL_SUPPLY = 21000000000000; uint256 public tokenExchangeRateInWei = 300000000; uint256 public total_tokenwei = 0; uint256 public min_pay_wei = 0; uint256 public total_devidend = 0; uint256 public total_withdraw = 0; uint256 public deposit_amount = 0; uint256 public withdraw_amount = 0; uint256 public dividend_amount = 0; function Pixiu_Beta() { totalSupply = INITIAL_SUPPLY; adminArray.push(msg.sender); admin_set_deposit(msg.sender); } modifier onlyDeposit() { require(msg.sender == deposit_address); _; } modifier onlyAdmin() { bool ok = admin_check(msg.sender); require(ok); _; } modifier adminExists(address admin) { bool ok = false; if(admin != msg.sender){ ok = admin_check(admin); } require(ok); _; } modifier adminDoesNotExist(address admin) { bool ok = admin_check(admin); require(!ok); _; } function admin_check(address admin) private constant returns(bool){ bool ok = false; for (uint i = 0; i < adminArray.length; i++) { if (admin == adminArray[i]) { ok = true; break; } } return ok; } modifier memberExists(address member) { bool ok = false; if (members[member].isExists == true) { ok = true; } require(ok); _; } modifier isMember() { bool ok = false; if (members[msg.sender].isExists == true) { ok = true; } require(ok); _; } function admin_deposit(uint xEth) onlyAdmin{ uint256 xwei = xEth * 10**18; deposit_amount += xwei; } function admin_dividend(uint xEth) onlyAdmin{ uint256 xwei = xEth * 10**18; require(xwei <= (deposit_amount-dividend_amount) ); dividend_amount += xwei; uint256 len = memberArray.length; uint i = 0; address _member; uint total_balance_dividened=0; for( i = 0; i < len; i++){ _member = memberArray[i]; if(members[_member].isDividend){ total_balance_dividened = balances[_member]; } } uint256 perTokenWei = xwei / (total_balance_dividened / 10 ** 6); for( i = 0; i < len; i++){ _member = memberArray[i]; if(members[_member].isDividend){ uint256 thisWei = (balances[_member] / 10 ** 6) * perTokenWei; members[_member].dividend += thisWei; total_devidend += thisWei; } } } function admin_set_exchange_rate(uint[] exchangeRates) onlyAdmin{ uint len = exchangeRates.length; exchangeRateArray.length = 0; for(uint i = 0; i < len; i += 3){ uint time1 = exchangeRates[i]; uint time2 = exchangeRates[i + 1]; uint value = exchangeRates[i + 2]*1000; exchangeRateArray.push(exchangeRate(time1, time2, value)); } } function get_exchange_wei() constant returns(uint256){ uint len = exchangeRateArray.length; uint nowTime = block.timestamp; for(uint i = 0; i < len; i += 3){ exchangeRate memory rate = exchangeRateArray[i]; uint time1 = rate.time1; uint time2 = rate.time2; uint value = rate.value; if (nowTime>= time1 && nowTime<=time2) { tokenExchangeRateInWei = value; return value; } } return tokenExchangeRateInWei; } function admin_set_min_pay(uint256 _min_pay) onlyAdmin{ require(_min_pay >= 0); min_pay_wei = _min_pay * 10 ** 18; } function get_admin_list() constant returns(address[] _adminArray){ _adminArray = adminArray; } function admin_add(address admin) onlyAdmin adminDoesNotExist(admin){ adminArray.push(admin); } function admin_del(address admin) onlyAdmin adminExists(admin){ for (uint i = 0; i < adminArray.length - 1; i++) if (adminArray[i] == admin) { adminArray[i] = adminArray[adminArray.length - 1]; break; } adminArray.length -= 1; } function admin_set_deposit(address addr) onlyAdmin{ deposit_address = addr; } function admin_active_payable() onlyAdmin{ isPayable = true; } function admin_inactive_payable() onlyAdmin{ isPayable = false; } function admin_active_withdrawable() onlyAdmin{ isWithdrawable = true; } function admin_inactive_withdrawable() onlyAdmin{ isWithdrawable = false; } function admin_active_dividend(address _member) onlyAdmin memberExists(_member){ members[_member].isDividend = true; } function admin_inactive_dividend(address _member) onlyAdmin memberExists(_member){ members[_member].isDividend = false; } function admin_active_withdraw(address _member) onlyAdmin memberExists(_member){ members[_member].isWithdraw = true; } function admin_inactive_withdraw(address _member) onlyAdmin memberExists(_member){ members[_member].isWithdraw = false; } function get_total_info() constant returns(uint256 _deposit_amount, uint256 _total_devidend, uint256 _total_remain, uint256 _total_withdraw){ _total_remain = total_devidend - total_withdraw; _deposit_amount = deposit_amount; _total_devidend = total_devidend; _total_withdraw = total_withdraw; } function get_info(address _member) constant returns (uint256 _balance, uint256 _devidend, uint256 _remain, uint256 _withdraw){ _devidend = members[_member].dividend; _withdraw = members[_member].withdraw; _remain = _devidend - _withdraw; _balance = balances[_member]; } function withdraw() isMember { uint256 _remain = members[msg.sender].dividend - members[msg.sender].withdraw; require(_remain > 0); require(isWithdrawable); require(members[msg.sender].isWithdraw); msg.sender.transfer(_remain); members[msg.sender].withdraw += _remain; total_withdraw += _remain; } function withdraw_admin(uint xEth) onlyDeposit{ uint256 _withdraw = xEth * 10**18; require( msg.sender == deposit_address ); require(this.balance > _withdraw); msg.sender.transfer(_withdraw); withdraw_amount += _withdraw; } function withdraw_all_admin(address _deposit) onlyAdmin { require( _deposit == deposit_address ); _deposit.transfer(this.balance); total_devidend = 0; total_withdraw = 0; deposit_amount = 0; withdraw_amount = 0; dividend_amount = 0; } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) { require(_to != deposit_address); require(isPayable); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (members[_to].isExists != true) { members[_to].isExists = true; members[_to].isDividend = true; members[_to].isWithdraw = true; memberArray.push(_to); } Transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { require(_to != deposit_address); require(_from != deposit_address); require(isPayable); var _allowance = allowed[_from][msg.sender]; require(_allowance >= _value); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); if (members[_to].isExists != true) { members[_to].isExists = true; members[_to].isDividend = true; members[_to].isWithdraw = true; memberArray.push(_to); } Transfer(_from, _to, _value); } function () payable { pay(); } function pay() public payable returns (bool) { require(msg.value > min_pay_wei); require(isPayable); if(msg.sender == deposit_address){ deposit_amount += msg.value; }else{ uint256 exchangeWei = get_exchange_wei(); uint256 thisTokenWei = exchangeWei * msg.value / 10**18 ; if (members[msg.sender].isExists != true) { members[msg.sender].isExists = true; members[msg.sender].isDividend = true; members[msg.sender].isWithdraw = true; memberArray.push(msg.sender); } balances[msg.sender] += thisTokenWei; total_tokenwei += thisTokenWei; } return true; } function get_this_balance() constant returns(uint256){ return this.balance; } }
0
1,586
pragma solidity ^0.4.25; contract CryptoMinerTokenAlpha { modifier onlyBagholders { require(myTokens() > 0); _; } modifier onlyStronghands { require(myDividends(true) > 0); _; } event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event Transfer( address indexed from, address indexed to, uint256 tokens ); string public name = "Crypto Miner Token Alpha"; string public symbol = "CMA"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 50; uint8 constant internal transferFee_ = 0; uint8 constant internal exitFee_ = 0; uint8 constant internal refferalFee_ = 33; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2 ** 64; uint256 public stakingRequirement = 50e18; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint256 internal tokenSupply_; uint256 internal profitPerShare_; function buy(address _referredBy) public payable returns (uint256) { purchaseTokens(msg.value, _referredBy); } function() payable public { purchaseTokens(msg.value, 0x0); } function reinvest() onlyStronghands public { uint256 _dividends = myDividends(false); address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint256 _tokens = purchaseTokens(_dividends, 0x0); emit onReinvestment(_customerAddress, _dividends, _tokens); } function exit() public { address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); withdraw(); } function withdraw() onlyStronghands public { address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; _customerAddress.transfer(_dividends); emit onWithdraw(_customerAddress, _dividends); } function sell(uint256 _amountOfTokens) onlyBagholders public { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; if (tokenSupply_ > 0) { profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); } function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); if (myDividends(true) > 0) { withdraw(); } uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); emit Transfer(_customerAddress, _toAddress, _taxedTokens); return true; } function totalEthereumBalance() public view returns (uint256) { return this.balance; } function totalSupply() public view returns (uint256) { return tokenSupply_; } function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } function balanceOf(address _customerAddress) public view returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } function sellPrice() public view returns (uint256) { if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } function buyPrice() public view returns (uint256) { if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) { address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); if ( _referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != _customerAddress && tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } if (tokenSupply_ > 0) { tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / tokenSupply_); _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_))); } else { tokenSupply_ = _amountOfTokens; } tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice()); return _amountOfTokens; } function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + ((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2)) + (2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
2,753
pragma solidity ^0.4.20; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant 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 constant 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); } library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } contract Pausable is Ownable { address public saleAgent; address public partner; modifier onlyAdmin() { require(msg.sender == owner || msg.sender == saleAgent || msg.sender == partner); _; } function setSaleAgent(address newSaleAgent) onlyOwner public { require(newSaleAgent != address(0)); saleAgent = newSaleAgent; } function setPartner(address newPartner) onlyOwner public { require(newPartner != address(0)); partner = newPartner; } event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract BasicToken is ERC20Basic, Pausable { using SafeMath for uint256; mapping(address => uint256) balances; uint256 public storageTime = 1522749600; modifier checkStorageTime() { require(now >= storageTime); _; } modifier onlyPayloadSize(uint256 numwords) { assert(msg.data.length >= numwords * 32 + 4); _; } function setStorageTime(uint256 _time) public onlyOwner { storageTime = _time; } function transfer(address _to, uint256 _value) public onlyPayloadSize(2) whenNotPaused checkStorageTime returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) whenNotPaused checkStorageTime 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; } function approve(address _spender, uint256 _value) public onlyPayloadSize(2) whenNotPaused returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public onlyPayloadSize(2) returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public onlyPayloadSize(2) 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{ event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) public onlyAdmin whenNotPaused canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(this), _to, _amount); return true; } function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract BurnableToken is MintableToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public onlyPayloadSize(1) { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } function burnFrom(address _from, uint256 _value) public onlyPayloadSize(2) returns (bool success) { require(balances[_from] >= _value); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(_from, _value); return true; } } contract AlttexToken is BurnableToken { string public constant name = "Alttex"; string public constant symbol = "ALTX"; uint8 public constant decimals = 8; }
1
2,994
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
49