source_idx
stringlengths
1
5
contract_name
stringlengths
1
55
func_name
stringlengths
0
2.45k
masked_body
stringlengths
60
686k
masked_all
stringlengths
34
686k
func_body
stringlengths
6
324k
signature_only
stringlengths
11
2.47k
signature_extend
stringlengths
11
8.95k
73112
ScheduleHold
vestedPercent
contract ScheduleHold is Schedule { constructor(uint256 _tokenReleaseDate) Schedule(_tokenReleaseDate) public { } /// @notice Calculates the percent of tokens that may be claimed at this time /// @return Number of tokens vested function vestedPercent() public view returns (uint256) {<FILL_FUNCTION_BODY> } }
contract ScheduleHold is Schedule { constructor(uint256 _tokenReleaseDate) Schedule(_tokenReleaseDate) public { } <FILL_FUNCTION> }
if(now < tokenReleaseDate || now < getReleaseTime(6)) { return 0; } else { return 100; }
function vestedPercent() public view returns (uint256)
/// @notice Calculates the percent of tokens that may be claimed at this time /// @return Number of tokens vested function vestedPercent() public view returns (uint256)
43179
StandardToken
approve
contract StandardToken is StandardAuth { using SafeMath for uint; mapping(address => uint) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => bool) optionPoolMembers; mapping(address => uint) optionPoolMemberApproveTotal; string public name; string public symbol; uint8 public decimals = 9; uint256 public totalSupply; uint256 public optionPoolLockTotal = 500000000; uint [2][7] public optionPoolMembersUnlockPlans = [ [1596211200,15], //2020-08-01 00:00:00 unlock 15% [1612108800,30], //2021-02-01 00:00:00 unlock 30% [1627747200,45], //2021-08-01 00:00:00 unlock 45% [1643644800,60], //2022-02-01 00:00:00 unlock 60% [1659283200,75], //2022-08-01 00:00:00 unlock 75% [1675180800,90], //2023-02-01 00:00:00 unlock 90% [1690819200,100] //2023-08-01 00:00:00 unlock 100% ]; constructor(uint256 _initialAmount, string _tokenName, string _tokenSymbol) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; symbol = _tokenSymbol; optionPoolMembers[0x36b4F89608B5a5d5bd675b13a9d1075eCb64C2B5] = true; optionPoolMembers[0xDdcEb1A0c975Da8f0E0c457e06D6eBfb175570A7] = true; optionPoolMembers[0x46b6bA8ff5b91FF6B76964e143f3573767a20c1C] = true; optionPoolMembers[0xBF95141188dB8FDeFe85Ce2412407A9266d96dA3] = true; } modifier verifyTheLock(uint _value) { if(optionPoolMembers[msg.sender] == true) { if(balances[msg.sender] - optionPoolMemberApproveTotal[msg.sender] - _value < optionPoolMembersLockTotalOf(msg.sender)) { revert(); } else { _; } } else { _; } } // Function to access name of token . function name() public view returns (string _name) { return name; } // Function to access symbol of token . function symbol() public view returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() public view returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() public view returns (uint _totalSupply) { return totalSupply; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } function verifyOptionPoolMembers(address _add) public view returns (bool _verifyResults) { return optionPoolMembers[_add]; } function optionPoolMembersLockTotalOf(address _memAdd) public view returns (uint _optionPoolMembersLockTotal) { if(optionPoolMembers[_memAdd] != true){ return 0; } uint unlockPercent = 0; for (uint8 i = 0; i < optionPoolMembersUnlockPlans.length; i++) { if(now >= optionPoolMembersUnlockPlans[i][0]) { unlockPercent = optionPoolMembersUnlockPlans[i][1]; } else { break; } } return optionPoolLockTotal * (100 - unlockPercent) / 100; } function transfer(address _to, uint _value) public verifyTheLock(_value) returns (bool success) { assert(_value > 0); assert(balances[msg.sender] >= _value); assert(msg.sender != _to); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { assert(balances[_from] >= _value); assert(allowed[_from][msg.sender] >= _value); if(optionPoolMembers[_from] == true) { optionPoolMemberApproveTotal[_from] = optionPoolMemberApproveTotal[_from].sub(_value); } allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public verifyTheLock(_value) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract StandardToken is StandardAuth { using SafeMath for uint; mapping(address => uint) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => bool) optionPoolMembers; mapping(address => uint) optionPoolMemberApproveTotal; string public name; string public symbol; uint8 public decimals = 9; uint256 public totalSupply; uint256 public optionPoolLockTotal = 500000000; uint [2][7] public optionPoolMembersUnlockPlans = [ [1596211200,15], //2020-08-01 00:00:00 unlock 15% [1612108800,30], //2021-02-01 00:00:00 unlock 30% [1627747200,45], //2021-08-01 00:00:00 unlock 45% [1643644800,60], //2022-02-01 00:00:00 unlock 60% [1659283200,75], //2022-08-01 00:00:00 unlock 75% [1675180800,90], //2023-02-01 00:00:00 unlock 90% [1690819200,100] //2023-08-01 00:00:00 unlock 100% ]; constructor(uint256 _initialAmount, string _tokenName, string _tokenSymbol) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; symbol = _tokenSymbol; optionPoolMembers[0x36b4F89608B5a5d5bd675b13a9d1075eCb64C2B5] = true; optionPoolMembers[0xDdcEb1A0c975Da8f0E0c457e06D6eBfb175570A7] = true; optionPoolMembers[0x46b6bA8ff5b91FF6B76964e143f3573767a20c1C] = true; optionPoolMembers[0xBF95141188dB8FDeFe85Ce2412407A9266d96dA3] = true; } modifier verifyTheLock(uint _value) { if(optionPoolMembers[msg.sender] == true) { if(balances[msg.sender] - optionPoolMemberApproveTotal[msg.sender] - _value < optionPoolMembersLockTotalOf(msg.sender)) { revert(); } else { _; } } else { _; } } // Function to access name of token . function name() public view returns (string _name) { return name; } // Function to access symbol of token . function symbol() public view returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() public view returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() public view returns (uint _totalSupply) { return totalSupply; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } function verifyOptionPoolMembers(address _add) public view returns (bool _verifyResults) { return optionPoolMembers[_add]; } function optionPoolMembersLockTotalOf(address _memAdd) public view returns (uint _optionPoolMembersLockTotal) { if(optionPoolMembers[_memAdd] != true){ return 0; } uint unlockPercent = 0; for (uint8 i = 0; i < optionPoolMembersUnlockPlans.length; i++) { if(now >= optionPoolMembersUnlockPlans[i][0]) { unlockPercent = optionPoolMembersUnlockPlans[i][1]; } else { break; } } return optionPoolLockTotal * (100 - unlockPercent) / 100; } function transfer(address _to, uint _value) public verifyTheLock(_value) returns (bool success) { assert(_value > 0); assert(balances[msg.sender] >= _value); assert(msg.sender != _to); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { assert(balances[_from] >= _value); assert(allowed[_from][msg.sender] >= _value); if(optionPoolMembers[_from] == true) { optionPoolMemberApproveTotal[_from] = optionPoolMemberApproveTotal[_from].sub(_value); } allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } <FILL_FUNCTION> }
assert(_value > 0); assert(msg.sender != _spender); if(optionPoolMembers[msg.sender] == true) { if(allowed[msg.sender][_spender] > 0){ optionPoolMemberApproveTotal[msg.sender] = optionPoolMemberApproveTotal[msg.sender].sub(allowed[msg.sender][_spender]); } optionPoolMemberApproveTotal[msg.sender] = optionPoolMemberApproveTotal[msg.sender].add(_value); } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) public verifyTheLock(_value) returns (bool success)
function approve(address _spender, uint256 _value) public verifyTheLock(_value) returns (bool success)
19947
NoMintRewardPool
null
contract NoMintRewardPool is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public immutable rewardToken; uint256 public immutable duration; // making it not a constant is less gas efficient, but portable uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } // [Hardwork] setting the reward, lpToken, duration, and rewardDistribution for each pool constructor(address _rewardToken, address _lpToken, uint256 _duration, address _rewardDistribution) public LPTokenWrapper(_lpToken) IRewardDistributionRecipient(_rewardDistribution) {<FILL_FUNCTION_BODY> } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) override { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) override { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(duration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(duration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(duration); emit RewardAdded(reward); } }
contract NoMintRewardPool is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public immutable rewardToken; uint256 public immutable duration; // making it not a constant is less gas efficient, but portable uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } <FILL_FUNCTION> function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) override { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) override { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; rewardToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external override onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(duration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(duration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(duration); emit RewardAdded(reward); } }
rewardToken = IERC20(_rewardToken); duration = _duration;
constructor(address _rewardToken, address _lpToken, uint256 _duration, address _rewardDistribution) public LPTokenWrapper(_lpToken) IRewardDistributionRecipient(_rewardDistribution)
// [Hardwork] setting the reward, lpToken, duration, and rewardDistribution for each pool constructor(address _rewardToken, address _lpToken, uint256 _duration, address _rewardDistribution) public LPTokenWrapper(_lpToken) IRewardDistributionRecipient(_rewardDistribution)
93083
StandardToken
transferFrom
contract StandardToken is ERC20, SafeMathLib { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to] ) { balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } else{ return false; } } function transferFrom(address _from, address _to, uint _value) returns (bool success) {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); //if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } }
contract StandardToken is ERC20, SafeMathLib { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to] ) { balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } else{ return false; } } <FILL_FUNCTION> function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); //if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } }
uint _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value // From a/c has balance && _allowance >= _value // Transfer approved && _value > 0 // Non-zero transfer && balances[_to] + _value > balances[_to] // Overflow check ){ balances[_to] = safeAdd(balances[_to],_value); balances[_from] = safeSub(balances[_from],_value); allowed[_from][msg.sender] = safeSub(_allowance,_value); Transfer(_from, _to, _value); return true; } else { return false; }
function transferFrom(address _from, address _to, uint _value) returns (bool success)
function transferFrom(address _from, address _to, uint _value) returns (bool success)
52923
MintableToken
mint
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } }
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } <FILL_FUNCTION> /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } }
_amount = _amount * 1 ether; totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true;
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool)
/** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool)
41131
Piti
Piti
contract Piti 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 Piti() public {<FILL_FUNCTION_BODY> } 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); } }
contract Piti 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; <FILL_FUNCTION> 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); } }
symbol = "PITI"; name = "Piti"; decimals = 18; _totalSupply = 99000000000000000000000000; balances[0x34082605dC345C2DaACFB11a4e56efeaEbD33aE5] = _totalSupply; Transfer(address(0), 0x34082605dC345C2DaACFB11a4e56efeaEbD33aE5, _totalSupply);
function Piti() public
function Piti() public
89057
StandardViroBoss
null
contract StandardViroBoss is ERC20Basic,Pausable { using SafeMath for uint256; string public constant name = "Viroboss"; string public constant symbol = "VC"; uint8 public constant decimals = 18; mapping(address => uint256) balances; uint256 totalSupply_= 1000000000 * 10**uint(decimals); constructor() public{<FILL_FUNCTION_BODY> } function totalSupply() public view returns (uint256) { return totalSupply_.sub(balances[address(0)]); } function transfer(address _to, uint256 _value) public whenNotPaused 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 StandardViroBoss is ERC20Basic,Pausable { using SafeMath for uint256; string public constant name = "Viroboss"; string public constant symbol = "VC"; uint8 public constant decimals = 18; mapping(address => uint256) balances; uint256 totalSupply_= 1000000000 * 10**uint(decimals); <FILL_FUNCTION> function totalSupply() public view returns (uint256) { return totalSupply_.sub(balances[address(0)]); } function transfer(address _to, uint256 _value) public whenNotPaused 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]; } }
emit Transfer(address(this),address(this),totalSupply_);
constructor() public
constructor() public
31867
ProductionUnitToken
transfer
contract ProductionUnitToken { /*================================= = MODIFIERS = =================================*/ /// @dev Only people with tokens modifier onlyBagholders { require(myTokens() > 0); _; } /// @dev Only people with profits modifier onlyStronghands { require(myDividends(true) > 0); _; } /*============================== = EVENTS = ==============================*/ 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 ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = DEPENDENCIES = =====================================*/ // MoonInc contract MoonInc public moonIncContract; /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Production Unit | Moon, Inc."; string public symbol = "ProductionUnit"; uint8 constant public decimals = 18; /// @dev dividends for token purchase uint8 public entryFee_; /// @dev dividends for token transfer uint8 public transferFee_; /// @dev dividends for token selling uint8 public exitFee_; /// @dev 20% of entryFee_ is given to referrer uint8 constant internal refferalFee_ = 20; uint256 public tokenPriceInitial_; // original is 0.0000001 ether uint256 public tokenPriceIncremental_; // original is 0.00000001 ether uint256 constant internal magnitude = 2 ** 64; /// @dev proof of stake (10 tokens) uint256 public stakingRequirement = 10e18; // cookie production multiplier (how many cookies do 1 token make per second) uint256 public cookieProductionMultiplier; // auto start timer uint256 public startTime; // Maximum amount of dev one time pre-mine mapping(address => uint) public ambassadorsMaxPremine; mapping(address => bool) public ambassadorsPremined; mapping(address => address) public ambassadorsPrerequisite; /*================================= = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint256 internal tokenSupply_; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /// @dev Set the MoonInc contract address to notify when token amount changes function ProductionUnitToken( address _moonIncContractAddress, uint8 _entryFee, uint8 _transferFee, uint8 _exitFee, uint _tokenPriceInitial, uint _tokenPriceIncremental, uint _cookieProductionMultiplier, uint _startTime ) public { moonIncContract = MoonInc(_moonIncContractAddress); entryFee_ = _entryFee; transferFee_ = _transferFee; exitFee_ = _exitFee; tokenPriceInitial_ = _tokenPriceInitial; tokenPriceIncremental_ = _tokenPriceIncremental; cookieProductionMultiplier = _cookieProductionMultiplier; startTime = _startTime; // Set ambassadors' maximum one time pre-mine amount (Total 1.29 ETH pre-mine). uint BETA_DIVISOR = 1000; // TODO: remove this in main launch contract // MA ambassadorsMaxPremine[0xFEA0904ACc8Df0F3288b6583f60B86c36Ea52AcD] = 0.28 ether / BETA_DIVISOR; ambassadorsPremined[address(0)] = true; // first ambassador don't need prerequisite // BL ambassadorsMaxPremine[0xc951D3463EbBa4e9Ec8dDfe1f42bc5895C46eC8f] = 0.28 ether / BETA_DIVISOR; ambassadorsPrerequisite[0xc951D3463EbBa4e9Ec8dDfe1f42bc5895C46eC8f] = 0xFEA0904ACc8Df0F3288b6583f60B86c36Ea52AcD; // PH ambassadorsMaxPremine[0x183feBd8828a9ac6c70C0e27FbF441b93004fC05] = 0.28 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x183feBd8828a9ac6c70C0e27FbF441b93004fC05] = 0xc951D3463EbBa4e9Ec8dDfe1f42bc5895C46eC8f; // RS ambassadorsMaxPremine[0x1fbc2Ca750E003A56d706C595b49a0A430EBA92d] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x1fbc2Ca750E003A56d706C595b49a0A430EBA92d] = 0x183feBd8828a9ac6c70C0e27FbF441b93004fC05; // LN ambassadorsMaxPremine[0x41F29054E7c0BC59a8AF10f3a6e7C0E53B334e05] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x41F29054E7c0BC59a8AF10f3a6e7C0E53B334e05] = 0x1fbc2Ca750E003A56d706C595b49a0A430EBA92d; // LE ambassadorsMaxPremine[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = 0x41F29054E7c0BC59a8AF10f3a6e7C0E53B334e05; // MI ambassadorsMaxPremine[0x0a3239799518E7F7F339867A4739282014b97Dcf] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x0a3239799518E7F7F339867A4739282014b97Dcf] = 0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41; // PO ambassadorsMaxPremine[0x31529d5Ab0D299D9b0594B7f2ef3515Be668AA87] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x31529d5Ab0D299D9b0594B7f2ef3515Be668AA87] = 0x0a3239799518E7F7F339867A4739282014b97Dcf; } /// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) function buy(address _referredBy) public payable returns (uint256) { purchaseTokens(msg.value, _referredBy); } /** * @dev Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /// @dev Converts all of caller's dividends to tokens. function reinvest() onlyStronghands public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /// @dev Alias of sell() and withdraw(). function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /// @dev Withdraws all of the callers earnings. function withdraw() onlyStronghands public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /// @dev Liquifies tokens to ethereum. function sell(uint256 _amountOfTokens) onlyBagholders public { require(now >= startTime); // setup data address _customerAddress = msg.sender; // russian hackers BTFO 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); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (_taxedEthereum * magnitude); payoutsTo_[_customerAddress] -= _updatedPayouts; // Tell MoonInc contract for tokens amount change, and transfer dividends. moonIncContract.handleProductionDecrease.value(_dividends)(_customerAddress, _tokens * cookieProductionMultiplier); // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); } /** * @dev Transfer tokens from the caller to a new holder. * Remember, there's a fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {<FILL_FUNCTION_BODY> } /*===================================== = HELPERS AND CALCULATORS = =====================================*/ function getSettings() public view returns (uint8, uint8, uint8, uint256, uint256, uint256, uint256) { return (entryFee_, transferFee_, exitFee_, tokenPriceInitial_, tokenPriceIncremental_, cookieProductionMultiplier, startTime); } /** * @dev Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns (uint256) { return this.balance; } /// @dev Retrieve the total token supply. function totalSupply() public view returns (uint256) { return tokenSupply_; } /// @dev Retrieve the tokens owned by the caller. function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * @dev Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /// @dev Retrieve the token balance of any single address. function balanceOf(address _customerAddress) public view returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } /// @dev Retrieve the dividend balance of any single address. function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (-payoutsTo_[_customerAddress])) / magnitude; } /// @dev Return the sell price of 1 individual token. function sellPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. 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; } } /// @dev Return the buy price of 1 individual token. function buyPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. 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; } } /// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders. 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; } /// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders. 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; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /// @dev Internal function to actually purchase the tokens. function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) { // Remove this on main launch require(_incomingEthereum <= 1 finney); require( // auto start now >= startTime || // ambassador pre-mine within 1 hour before startTime, sequences enforced (now >= startTime - 1 hours && !ambassadorsPremined[msg.sender] && ambassadorsPremined[ambassadorsPrerequisite[msg.sender]] && _incomingEthereum <= ambassadorsMaxPremine[msg.sender]) || // ambassador pre-mine within 10 minutes before startTime, sequences not enforced (now >= startTime - 10 minutes && !ambassadorsPremined[msg.sender] && _incomingEthereum <= ambassadorsMaxPremine[msg.sender]) ); if (now < startTime) { ambassadorsPremined[msg.sender] = true; } // data setup 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); // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); } // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tell MoonInc contract for tokens amount change, and transfer dividends. moonIncContract.handleProductionIncrease.value(_dividends)(_customerAddress, _amountOfTokens * cookieProductionMultiplier); // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice()); return _amountOfTokens; } /** * @dev Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + ((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2)) + (2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } /** * @dev Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } /// @dev This is where all your gas goes. 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; } } }
contract ProductionUnitToken { /*================================= = MODIFIERS = =================================*/ /// @dev Only people with tokens modifier onlyBagholders { require(myTokens() > 0); _; } /// @dev Only people with profits modifier onlyStronghands { require(myDividends(true) > 0); _; } /*============================== = EVENTS = ==============================*/ 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 ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = DEPENDENCIES = =====================================*/ // MoonInc contract MoonInc public moonIncContract; /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Production Unit | Moon, Inc."; string public symbol = "ProductionUnit"; uint8 constant public decimals = 18; /// @dev dividends for token purchase uint8 public entryFee_; /// @dev dividends for token transfer uint8 public transferFee_; /// @dev dividends for token selling uint8 public exitFee_; /// @dev 20% of entryFee_ is given to referrer uint8 constant internal refferalFee_ = 20; uint256 public tokenPriceInitial_; // original is 0.0000001 ether uint256 public tokenPriceIncremental_; // original is 0.00000001 ether uint256 constant internal magnitude = 2 ** 64; /// @dev proof of stake (10 tokens) uint256 public stakingRequirement = 10e18; // cookie production multiplier (how many cookies do 1 token make per second) uint256 public cookieProductionMultiplier; // auto start timer uint256 public startTime; // Maximum amount of dev one time pre-mine mapping(address => uint) public ambassadorsMaxPremine; mapping(address => bool) public ambassadorsPremined; mapping(address => address) public ambassadorsPrerequisite; /*================================= = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint256 internal tokenSupply_; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /// @dev Set the MoonInc contract address to notify when token amount changes function ProductionUnitToken( address _moonIncContractAddress, uint8 _entryFee, uint8 _transferFee, uint8 _exitFee, uint _tokenPriceInitial, uint _tokenPriceIncremental, uint _cookieProductionMultiplier, uint _startTime ) public { moonIncContract = MoonInc(_moonIncContractAddress); entryFee_ = _entryFee; transferFee_ = _transferFee; exitFee_ = _exitFee; tokenPriceInitial_ = _tokenPriceInitial; tokenPriceIncremental_ = _tokenPriceIncremental; cookieProductionMultiplier = _cookieProductionMultiplier; startTime = _startTime; // Set ambassadors' maximum one time pre-mine amount (Total 1.29 ETH pre-mine). uint BETA_DIVISOR = 1000; // TODO: remove this in main launch contract // MA ambassadorsMaxPremine[0xFEA0904ACc8Df0F3288b6583f60B86c36Ea52AcD] = 0.28 ether / BETA_DIVISOR; ambassadorsPremined[address(0)] = true; // first ambassador don't need prerequisite // BL ambassadorsMaxPremine[0xc951D3463EbBa4e9Ec8dDfe1f42bc5895C46eC8f] = 0.28 ether / BETA_DIVISOR; ambassadorsPrerequisite[0xc951D3463EbBa4e9Ec8dDfe1f42bc5895C46eC8f] = 0xFEA0904ACc8Df0F3288b6583f60B86c36Ea52AcD; // PH ambassadorsMaxPremine[0x183feBd8828a9ac6c70C0e27FbF441b93004fC05] = 0.28 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x183feBd8828a9ac6c70C0e27FbF441b93004fC05] = 0xc951D3463EbBa4e9Ec8dDfe1f42bc5895C46eC8f; // RS ambassadorsMaxPremine[0x1fbc2Ca750E003A56d706C595b49a0A430EBA92d] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x1fbc2Ca750E003A56d706C595b49a0A430EBA92d] = 0x183feBd8828a9ac6c70C0e27FbF441b93004fC05; // LN ambassadorsMaxPremine[0x41F29054E7c0BC59a8AF10f3a6e7C0E53B334e05] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x41F29054E7c0BC59a8AF10f3a6e7C0E53B334e05] = 0x1fbc2Ca750E003A56d706C595b49a0A430EBA92d; // LE ambassadorsMaxPremine[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41] = 0x41F29054E7c0BC59a8AF10f3a6e7C0E53B334e05; // MI ambassadorsMaxPremine[0x0a3239799518E7F7F339867A4739282014b97Dcf] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x0a3239799518E7F7F339867A4739282014b97Dcf] = 0x15Fda64fCdbcA27a60Aa8c6ca882Aa3e1DE4Ea41; // PO ambassadorsMaxPremine[0x31529d5Ab0D299D9b0594B7f2ef3515Be668AA87] = 0.09 ether / BETA_DIVISOR; ambassadorsPrerequisite[0x31529d5Ab0D299D9b0594B7f2ef3515Be668AA87] = 0x0a3239799518E7F7F339867A4739282014b97Dcf; } /// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) function buy(address _referredBy) public payable returns (uint256) { purchaseTokens(msg.value, _referredBy); } /** * @dev Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /// @dev Converts all of caller's dividends to tokens. function reinvest() onlyStronghands public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /// @dev Alias of sell() and withdraw(). function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /// @dev Withdraws all of the callers earnings. function withdraw() onlyStronghands public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /// @dev Liquifies tokens to ethereum. function sell(uint256 _amountOfTokens) onlyBagholders public { require(now >= startTime); // setup data address _customerAddress = msg.sender; // russian hackers BTFO 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); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (_taxedEthereum * magnitude); payoutsTo_[_customerAddress] -= _updatedPayouts; // Tell MoonInc contract for tokens amount change, and transfer dividends. moonIncContract.handleProductionDecrease.value(_dividends)(_customerAddress, _tokens * cookieProductionMultiplier); // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); } <FILL_FUNCTION> /*===================================== = HELPERS AND CALCULATORS = =====================================*/ function getSettings() public view returns (uint8, uint8, uint8, uint256, uint256, uint256, uint256) { return (entryFee_, transferFee_, exitFee_, tokenPriceInitial_, tokenPriceIncremental_, cookieProductionMultiplier, startTime); } /** * @dev Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns (uint256) { return this.balance; } /// @dev Retrieve the total token supply. function totalSupply() public view returns (uint256) { return tokenSupply_; } /// @dev Retrieve the tokens owned by the caller. function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * @dev Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /// @dev Retrieve the token balance of any single address. function balanceOf(address _customerAddress) public view returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } /// @dev Retrieve the dividend balance of any single address. function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (-payoutsTo_[_customerAddress])) / magnitude; } /// @dev Return the sell price of 1 individual token. function sellPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. 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; } } /// @dev Return the buy price of 1 individual token. function buyPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. 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; } } /// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders. 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; } /// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders. 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; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /// @dev Internal function to actually purchase the tokens. function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) { // Remove this on main launch require(_incomingEthereum <= 1 finney); require( // auto start now >= startTime || // ambassador pre-mine within 1 hour before startTime, sequences enforced (now >= startTime - 1 hours && !ambassadorsPremined[msg.sender] && ambassadorsPremined[ambassadorsPrerequisite[msg.sender]] && _incomingEthereum <= ambassadorsMaxPremine[msg.sender]) || // ambassador pre-mine within 10 minutes before startTime, sequences not enforced (now >= startTime - 10 minutes && !ambassadorsPremined[msg.sender] && _incomingEthereum <= ambassadorsMaxPremine[msg.sender]) ); if (now < startTime) { ambassadorsPremined[msg.sender] = true; } // data setup 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); // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); } // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tell MoonInc contract for tokens amount change, and transfer dividends. moonIncContract.handleProductionIncrease.value(_dividends)(_customerAddress, _amountOfTokens * cookieProductionMultiplier); // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice()); return _amountOfTokens; } /** * @dev Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + ((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2)) + (2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } /** * @dev Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } /// @dev This is where all your gas goes. 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; } } }
// setup address _customerAddress = msg.sender; // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if (myDividends(true) > 0) { withdraw(); } // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // Tell MoonInc contract for tokens amount change, and transfer dividends. moonIncContract.handleProductionDecrease.value(_dividends)(_customerAddress, _amountOfTokens * cookieProductionMultiplier); moonIncContract.handleProductionIncrease(_toAddress, _taxedTokens * cookieProductionMultiplier); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true;
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool)
/** * @dev Transfer tokens from the caller to a new holder. * Remember, there's a fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool)
1309
ZITOKEN
approveAndCall
contract ZITOKEN is StandardToken, Ownable { function () { throw; } /* Public variables of the token */ string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function ZITOKEN( ) { balances[msg.sender] = 988000000000000000000000000; totalSupply = 988000000000000000000000000; name = "ZITOKEN"; decimals = 18; symbol = "ZIT"; } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract ZITOKEN is StandardToken, Ownable { function () { throw; } /* Public variables of the token */ string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function ZITOKEN( ) { balances[msg.sender] = 988000000000000000000000000; totalSupply = 988000000000000000000000000; name = "ZITOKEN"; decimals = 18; symbol = "ZIT"; } <FILL_FUNCTION> }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
/* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
33929
LinkToken
LinkToken
contract LinkToken is StandardToken { string public name; uint8 public decimals; string public symbol; function LinkToken() {<FILL_FUNCTION_BODY> } }
contract LinkToken is StandardToken { string public name; uint8 public decimals; string public symbol; <FILL_FUNCTION> }
balances[msg.sender] = 21000000000000000; totalSupply = 21000000000000000; name = "LINK"; decimals = 8; symbol = "LKC";
function LinkToken()
function LinkToken()
60109
TokenTimelock
release
contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; constructor( ERC20Basic _token, address _beneficiary, uint256 _releaseTime ) public { // solium-disable-next-line security/no-block-members require(_releaseTime > block.timestamp); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public {<FILL_FUNCTION_BODY> } }
contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; constructor( ERC20Basic _token, address _beneficiary, uint256 _releaseTime ) public { // solium-disable-next-line security/no-block-members require(_releaseTime > block.timestamp); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } <FILL_FUNCTION> }
// solium-disable-next-line security/no-block-members require(block.timestamp >= releaseTime, "It's not the time"); uint256 amount = token.balanceOf(this); require(amount > 0, "Amount is 0"); token.safeTransfer(beneficiary, amount);
function release() public
/** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public
89066
HCToken
transferFrom
contract HCToken { address public owner; string public constant name = "Hash Credit Token"; string public constant symbol = "HCT"; uint256 public constant decimals = 6; uint256 public constant totalSupply = 15 * 100 * 1000 * 1000 * 10 ** decimals; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; modifier onlyPayloadSize(uint size) { if (msg.data.length != size + 4) { throw; } _; } function HCToken() { owner = msg.sender; balances[owner] = totalSupply; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) { require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) returns (bool success) {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
contract HCToken { address public owner; string public constant name = "Hash Credit Token"; string public constant symbol = "HCT"; uint256 public constant decimals = 6; uint256 public constant totalSupply = 15 * 100 * 1000 * 1000 * 10 ** decimals; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; modifier onlyPayloadSize(uint size) { if (msg.data.length != size + 4) { throw; } _; } function HCToken() { owner = msg.sender; balances[owner] = totalSupply; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) { require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } <FILL_FUNCTION> function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) returns (bool success)
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) returns (bool success)
4871
ERCToken
null
contract ERCToken is ERC20 { constructor () public ERC20("Crypto User Base", "CUB") {<FILL_FUNCTION_BODY> } }
contract ERCToken is ERC20 { <FILL_FUNCTION> }
_setupDecimals(18); _mint(msg.sender, 1000000 * (10 ** uint256(decimals())));
constructor () public ERC20("Crypto User Base", "CUB")
constructor () public ERC20("Crypto User Base", "CUB")
27522
ERC721
setApprovalForAll
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; string public _baseURI; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory base = baseURI(); return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : ""; } function baseURI() internal view virtual returns (string memory) { return _baseURI; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override {<FILL_FUNCTION_BODY> } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; string public _baseURI; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory base = baseURI(); return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : ""; } function baseURI() internal view virtual returns (string memory) { return _baseURI; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } <FILL_FUNCTION> function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved);
function setApprovalForAll(address operator, bool approved) public virtual override
function setApprovalForAll(address operator, bool approved) public virtual override
56760
ERC721
_checkOnERC721Received
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get( tokenId, "ERC721: owner query for nonexistent token" ); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get( tokenId, "ERC721: owner query for nonexistent token" ); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } <FILL_FUNCTION> /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED);
function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool)
/** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool)
35850
ERC20
increaseAllowance
contract ERC20 is IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping(address => bool) internal locks; mapping (address => mapping (address => uint256)) private _allowed; uint256 public Max_supply = 10000000000 * (10 **18); uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); require(locks[msg.sender] == false); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {<FILL_FUNCTION_BODY> } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } function _mint(address account, uint256 value) internal { require(account != address(0)); require(Max_supply > _totalSupply); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function burn(address from, uint256 value) public { _burn(from, value); } function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function lock(address _owner) public onlyOwner returns (bool) { require(locks[_owner] == false); locks[_owner] = true; return true; } function unlock(address _owner) public onlyOwner returns (bool) { require(locks[_owner] == true); locks[_owner] = false; return true; } function showLockState(address _owner) public view returns (bool) { return locks[_owner]; } }
contract ERC20 is IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping(address => bool) internal locks; mapping (address => mapping (address => uint256)) private _allowed; uint256 public Max_supply = 10000000000 * (10 **18); uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); require(locks[msg.sender] == false); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } <FILL_FUNCTION> function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } function _mint(address account, uint256 value) internal { require(account != address(0)); require(Max_supply > _totalSupply); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function burn(address from, uint256 value) public { _burn(from, value); } function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function lock(address _owner) public onlyOwner returns (bool) { require(locks[_owner] == false); locks[_owner] = true; return true; } function unlock(address _owner) public onlyOwner returns (bool) { require(locks[_owner] == true); locks[_owner] = false; return true; } function showLockState(address _owner) public view returns (bool) { return locks[_owner]; } }
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true;
function increaseAllowance(address spender, uint256 addedValue) public returns (bool)
function increaseAllowance(address spender, uint256 addedValue) public returns (bool)
30924
antonCoin
approve
contract antonCoin { uint public decimals = 0; uint public totalSupply = 1000000; string public name = 'AntonCoin'; string public symbol = 'TONKA'; function antonCoin() { balances[msg.sender] = 1000000; } function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed from, address indexed to, uint256 value); mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
contract antonCoin { uint public decimals = 0; uint public totalSupply = 1000000; string public name = 'AntonCoin'; string public symbol = 'TONKA'; function antonCoin() { balances[msg.sender] = 1000000; } function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } <FILL_FUNCTION> function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed from, address indexed to, uint256 value); mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
allowed[msg.sender][_spender] = _value; return true;
function approve(address _spender, uint256 _value) returns (bool success)
function approve(address _spender, uint256 _value) returns (bool success)
67675
MSS
null
contract MSS is PausableToken { string public name; string public symbol; uint8 public decimals; /** * @dev Constructor that gives the founder all of the existing tokens. */ constructor() public {<FILL_FUNCTION_BODY> } /** @dev Fires on every freeze of tokens * @param _owner address The owner address of frozen tokens. * @param amount uint256 The amount of tokens frozen */ event TokenFreezeEvent(address indexed _owner, uint256 amount); /** @dev Fires on every unfreeze of tokens * @param _owner address The owner address of unfrozen tokens. * @param amount uint256 The amount of tokens unfrozen */ event TokenUnfreezeEvent(address indexed _owner, uint256 amount); event TokensBurned(address indexed _owner, uint256 _tokens); mapping(address => uint256) internal frozenTokenBalances; function freezeTokens(address _owner, uint256 _value) public onlyOwner { require(_value <= balanceOf(_owner)); uint256 oldFrozenBalance = getFrozenBalance(_owner); uint256 newFrozenBalance = oldFrozenBalance.add(_value); setFrozenBalance(_owner,newFrozenBalance); emit TokenFreezeEvent(_owner,_value); } function unfreezeTokens(address _owner, uint256 _value) public onlyOwner { require(_value <= getFrozenBalance(_owner)); uint256 oldFrozenBalance = getFrozenBalance(_owner); uint256 newFrozenBalance = oldFrozenBalance.sub(_value); setFrozenBalance(_owner,newFrozenBalance); emit TokenUnfreezeEvent(_owner,_value); } function setFrozenBalance(address _owner, uint256 _newValue) internal { frozenTokenBalances[_owner]=_newValue; } function balanceOf(address _owner) view public returns(uint256) { return getTotalBalance(_owner).sub(getFrozenBalance(_owner)); } function getTotalBalance(address _owner) view public returns(uint256) { return balances[_owner]; } /** * @dev Gets the amount of tokens which belong to the specified address BUT are frozen now. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount of frozen tokens owned by the passed address. */ function getFrozenBalance(address _owner) view public returns(uint256) { return frozenTokenBalances[_owner]; } /* * @dev Token burn function * @param _tokens uint256 amount of tokens to burn */ function burnTokens(uint256 _tokens) public onlyOwner { require(balanceOf(msg.sender) >= _tokens); balances[msg.sender] = balances[msg.sender].sub(_tokens); totalSupply = totalSupply.sub(_tokens); emit TokensBurned(msg.sender, _tokens); } function destroy(address payable _benefitiary) external onlyOwner{ selfdestruct(_benefitiary); } }
contract MSS is PausableToken { string public name; string public symbol; uint8 public decimals; <FILL_FUNCTION> /** @dev Fires on every freeze of tokens * @param _owner address The owner address of frozen tokens. * @param amount uint256 The amount of tokens frozen */ event TokenFreezeEvent(address indexed _owner, uint256 amount); /** @dev Fires on every unfreeze of tokens * @param _owner address The owner address of unfrozen tokens. * @param amount uint256 The amount of tokens unfrozen */ event TokenUnfreezeEvent(address indexed _owner, uint256 amount); event TokensBurned(address indexed _owner, uint256 _tokens); mapping(address => uint256) internal frozenTokenBalances; function freezeTokens(address _owner, uint256 _value) public onlyOwner { require(_value <= balanceOf(_owner)); uint256 oldFrozenBalance = getFrozenBalance(_owner); uint256 newFrozenBalance = oldFrozenBalance.add(_value); setFrozenBalance(_owner,newFrozenBalance); emit TokenFreezeEvent(_owner,_value); } function unfreezeTokens(address _owner, uint256 _value) public onlyOwner { require(_value <= getFrozenBalance(_owner)); uint256 oldFrozenBalance = getFrozenBalance(_owner); uint256 newFrozenBalance = oldFrozenBalance.sub(_value); setFrozenBalance(_owner,newFrozenBalance); emit TokenUnfreezeEvent(_owner,_value); } function setFrozenBalance(address _owner, uint256 _newValue) internal { frozenTokenBalances[_owner]=_newValue; } function balanceOf(address _owner) view public returns(uint256) { return getTotalBalance(_owner).sub(getFrozenBalance(_owner)); } function getTotalBalance(address _owner) view public returns(uint256) { return balances[_owner]; } /** * @dev Gets the amount of tokens which belong to the specified address BUT are frozen now. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount of frozen tokens owned by the passed address. */ function getFrozenBalance(address _owner) view public returns(uint256) { return frozenTokenBalances[_owner]; } /* * @dev Token burn function * @param _tokens uint256 amount of tokens to burn */ function burnTokens(uint256 _tokens) public onlyOwner { require(balanceOf(msg.sender) >= _tokens); balances[msg.sender] = balances[msg.sender].sub(_tokens); totalSupply = totalSupply.sub(_tokens); emit TokensBurned(msg.sender, _tokens); } function destroy(address payable _benefitiary) external onlyOwner{ selfdestruct(_benefitiary); } }
name = "Media Stream Service"; symbol = "MSS"; decimals = 18; totalSupply = 200000000*1000000000000000000; founder = msg.sender; balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply);
constructor() public
/** * @dev Constructor that gives the founder all of the existing tokens. */ constructor() public
66618
BurnableToken
burn
contract BurnableToken is StandardToken, Ownable { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public {<FILL_FUNCTION_BODY> } }
contract BurnableToken is StandardToken, Ownable { event Burn(address indexed burner, uint256 value); <FILL_FUNCTION> }
require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value);
function burn(uint256 _value) public
/** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public
17827
Transferable
disallowTransfersTo
contract Transferable is Ownable { bool public transfersAllowed = false; mapping(address => bool) allowedTransfersTo; function Transferable() { allowedTransfersTo[msg.sender] = true; } modifier onlyIfTransfersAllowed() { require(transfersAllowed == true || allowedTransfersTo[msg.sender] == true); _; } function allowTransfers() onlyOwner { transfersAllowed = true; } function disallowTransfers() onlyOwner { transfersAllowed = false; } function allowTransfersTo(address _owner) onlyOwner { allowedTransfersTo[_owner] = true; } function disallowTransfersTo(address _owner) onlyOwner {<FILL_FUNCTION_BODY> } function transfersAllowedTo(address _owner) constant returns (bool) { return (transfersAllowed == true || allowedTransfersTo[_owner] == true); } }
contract Transferable is Ownable { bool public transfersAllowed = false; mapping(address => bool) allowedTransfersTo; function Transferable() { allowedTransfersTo[msg.sender] = true; } modifier onlyIfTransfersAllowed() { require(transfersAllowed == true || allowedTransfersTo[msg.sender] == true); _; } function allowTransfers() onlyOwner { transfersAllowed = true; } function disallowTransfers() onlyOwner { transfersAllowed = false; } function allowTransfersTo(address _owner) onlyOwner { allowedTransfersTo[_owner] = true; } <FILL_FUNCTION> function transfersAllowedTo(address _owner) constant returns (bool) { return (transfersAllowed == true || allowedTransfersTo[_owner] == true); } }
allowedTransfersTo[_owner] = false;
function disallowTransfersTo(address _owner) onlyOwner
function disallowTransfersTo(address _owner) onlyOwner
2533
BoomOutCoin
transferFrom
contract BoomOutCoin is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { name = "BOOM OUT Coin"; symbol = "BOC"; decimals = 18; _totalSupply = 70000000 * (10 ** uint256(decimals)); balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); transfer(0xAcE29DB8441120DfF78f606AC9F7ae4A64D9c60D, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } }
contract BoomOutCoin is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { name = "BOOM OUT Coin"; symbol = "BOC"; decimals = 18; _totalSupply = 70000000 * (10 ** uint256(decimals)); balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); transfer(0xAcE29DB8441120DfF78f606AC9F7ae4A64D9c60D, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } <FILL_FUNCTION> }
balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public returns (bool success)
function transferFrom(address from, address to, uint tokens) public returns (bool success)
41337
Fee
takeFee
contract Fee { using Address for address; using SafeMath for uint256; address payable public feeAddress; uint32 public feePermill = 10; address public gov; constructor (address payable _feeAddress) { feeAddress = _feeAddress; gov = msg.sender; } modifier onlyGov() { require(msg.sender == gov, "!governance"); _; } function setFeePermill(uint32 _feePermill) public onlyGov { feePermill = _feePermill; } function setGovernance(address _gov) public onlyGov { gov = _gov; } function setFeeAddress(address payable _feeAddress) public onlyGov { feeAddress = _feeAddress; } function takeFee(address payable _to) public payable {<FILL_FUNCTION_BODY> } }
contract Fee { using Address for address; using SafeMath for uint256; address payable public feeAddress; uint32 public feePermill = 10; address public gov; constructor (address payable _feeAddress) { feeAddress = _feeAddress; gov = msg.sender; } modifier onlyGov() { require(msg.sender == gov, "!governance"); _; } function setFeePermill(uint32 _feePermill) public onlyGov { feePermill = _feePermill; } function setGovernance(address _gov) public onlyGov { gov = _gov; } function setFeeAddress(address payable _feeAddress) public onlyGov { feeAddress = _feeAddress; } <FILL_FUNCTION> }
require(msg.value > 0, "can't deposit 0"); uint256 amount = msg.value; uint256 feeAmount = amount.mul(feePermill).div(1000); uint256 realAmount = amount.sub(feeAmount); if (!feeAddress.send(feeAmount)) { feeAddress.transfer(feeAmount); } if (!_to.send(realAmount)) { _to.transfer(realAmount); }
function takeFee(address payable _to) public payable
function takeFee(address payable _to) public payable
65606
_0xCatetherToken
mint
contract _0xCatetherToken is ERC20Interface, EIP918Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount;//number of 'blocks' mined //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier ; just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**224; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; // a bunch of maps to know where this is going (pun intended) mapping(bytes32 => bytes32) public solutionForChallenge; mapping(uint => uint) public targetForEpoch; mapping(uint => uint) public timeStampForEpoch; mapping(address => uint) balances; mapping(address => address) donationsTo; mapping(address => mapping(address => uint)) allowed; event Donation(address donation); event DonationAddressOf(address donator, address donnationAddress); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public{ symbol = "0xCATE"; name = "0xCatether Token"; decimals = 4; epochCount = 0; _totalSupply = 1337000000*10**uint(decimals); targetForEpoch[epochCount] = _MAXIMUM_TARGET; challengeNumber = "GENESIS_BLOCK"; solutionForChallenge[challengeNumber] = "42"; // ahah yes timeStampForEpoch[epochCount] = block.timestamp; latestDifficultyPeriodStarted = block.number; epochCount = epochCount.add(1); targetForEpoch[epochCount] = _MAXIMUM_TARGET; miningTarget = _MAXIMUM_TARGET; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) {<FILL_FUNCTION_BODY> } //a new 'block' to be mined function _startNewMiningEpoch() internal { timeStampForEpoch[epochCount] = block.timestamp; epochCount = epochCount.add(1); //Difficulty adjustment following the DigiChieldv3 implementation (Tempered-SMA) // Allows more thorough protection against multi-pool hash attacks // https://github.com/zawy12/difficulty-algorithms/issues/9 miningTarget = _reAdjustDifficulty(epochCount); //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = blockhash(block.number.sub(1)); } //https://github.com/zawy12/difficulty-algorithms/issues/21 //readjust the target via a tempered EMA function _reAdjustDifficulty(uint epoch) internal returns (uint) { uint timeTarget = 300; // We want miners to spend 5 minutes to mine each 'block' uint N = 6180; //N = 1000*n, ratio between timeTarget and windowTime (31-ish minutes) // (Ethereum doesn't handle floating point numbers very well) uint elapsedTime = timeStampForEpoch[epoch.sub(1)].sub(timeStampForEpoch[epoch.sub(2)]); // will revert if current timestamp is smaller than the previous one targetForEpoch[epoch] = (targetForEpoch[epoch.sub(1)].mul(10000)).div( N.mul(3920).div(N.sub(1000).add(elapsedTime.mul(1042).div(timeTarget))).add(N)); // newTarget = Tampered EMA-retarget on the last 6 blocks (a bit more, it's an approximation) // Also, there's an adjust factor, in order to correct the delays induced by the time it takes for transactions to confirm // Difficulty is adjusted to the time it takes to produce a valid hash. Here, if we set it to take 300 seconds, it will actually take // 300 seconds + TxConfirmTime to validate that block. So, we wad a little % to correct that lag time. // Once Ethereum scales, it will actually make block times go a tad faster. There's no perfect answer to this problem at the moment latestDifficultyPeriodStarted = block.number; return targetForEpoch[epoch]; } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(targetForEpoch[epochCount]); } function getMiningTarget() public constant returns (uint) { return targetForEpoch[epochCount]; } //There's no limit to the coin supply //reward follows more or less the same emmission rate as Dogecoins'. 5 minutes per block / 105120 block in one year (roughly) function getMiningReward() public constant returns (uint) { bytes32 digest = solutionForChallenge[challengeNumber]; if(epochCount > 160000) return (50000 * 10**uint(decimals) ); // 14.4 M/day / ~ 1.0B Tokens in 20'000 blocks (coin supply @100'000th block ~ 150 Billions) if(epochCount > 140000) return (75000 * 10**uint(decimals) ); // 21.6 M/day / ~ 1.5B Tokens in 20'000 blocks (coin supply @100'000th block ~ 149 Billions) if(epochCount > 120000) return (125000 * 10**uint(decimals) ); // 36.0 M/day / ~ 2.5B Tokens in 20'000 blocks (coin supply @100'000th block ~ 146 Billions) if(epochCount > 100000) return (250000 * 10**uint(decimals) ); // 72.0 M/day / ~ 5.0B Tokens in 20'000 blocks (coin supply @100'000th block ~ 141 Billions) (~ 1 year elapsed) if(epochCount > 80000) return (500000 * 10**uint(decimals) ); // 144.0 M/day / ~10.0B Tokens in 20'000 blocks (coin supply @ 80'000th block ~ 131 Billions) if(epochCount > 60000) return (1000000 * 10**uint(decimals) ); // 288.0 M/day / ~20.0B Tokens in 20'000 blocks (coin supply @ 60'000th block ~ 111 Billions) if(epochCount > 40000) return ((uint256(keccak256(digest)) % 2500000) * 10**uint(decimals) ); // 360.0 M/day / ~25.0B Tokens in 20'000 blocks (coin supply @ 40'000th block ~ 86 Billions) if(epochCount > 20000) return ((uint256(keccak256(digest)) % 3500000) * 10**uint(decimals) ); // 504.0 M/day / ~35.0B Tokens in 20'000 blocks (coin supply @ 20'000th block ~ 51 Billions) return ((uint256(keccak256(digest)) % 5000000) * 10**uint(decimals) ); // 720.0 M/day / ~50.0B Tokens in 20'000 blocks } //help debug mining software (even though challenge_digest isn't used, this function is constant and helps troubleshooting mining issues) function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function donationTo(address tokenOwner) public constant returns (address donationAddress) { return donationsTo[tokenOwner]; } function changeDonation(address donationAddress) public returns (bool success) { donationsTo[msg.sender] = donationAddress; emit DonationAddressOf(msg.sender , donationAddress); return true; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { address donation = donationsTo[msg.sender]; balances[msg.sender] = (balances[msg.sender].sub(tokens)).add(5000); // 0.5 CATE for the sender balances[to] = balances[to].add(tokens); balances[donation] = balances[donation].add(5000); // 0.5 CATE for the sender's donation address emit Transfer(msg.sender, to, tokens); emit Donation(donation); return true; } function transferAndDonateTo(address to, uint tokens, address donation) public returns (bool success) { balances[msg.sender] = (balances[msg.sender].sub(tokens)).add(5000); // 0.5 CATE for the sender balances[to] = balances[to].add(tokens); balances[donation] = balances[donation].add(5000); // 0.5 CATE for the sender's specified donation address emit Transfer(msg.sender, to, tokens); emit Donation(donation); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); balances[donationsTo[from]] = balances[donationsTo[from]].add(5000); // 0.5 CATE for the sender's donation address balances[donationsTo[msg.sender]] = balances[donationsTo[msg.sender]].add(5000); // 0.5 CATE for the sender emit Transfer(from, to, tokens); emit Donation(donationsTo[from]); emit Donation(donationsTo[msg.sender]); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract _0xCatetherToken is ERC20Interface, EIP918Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount;//number of 'blocks' mined //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier ; just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**224; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; // a bunch of maps to know where this is going (pun intended) mapping(bytes32 => bytes32) public solutionForChallenge; mapping(uint => uint) public targetForEpoch; mapping(uint => uint) public timeStampForEpoch; mapping(address => uint) balances; mapping(address => address) donationsTo; mapping(address => mapping(address => uint)) allowed; event Donation(address donation); event DonationAddressOf(address donator, address donnationAddress); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public{ symbol = "0xCATE"; name = "0xCatether Token"; decimals = 4; epochCount = 0; _totalSupply = 1337000000*10**uint(decimals); targetForEpoch[epochCount] = _MAXIMUM_TARGET; challengeNumber = "GENESIS_BLOCK"; solutionForChallenge[challengeNumber] = "42"; // ahah yes timeStampForEpoch[epochCount] = block.timestamp; latestDifficultyPeriodStarted = block.number; epochCount = epochCount.add(1); targetForEpoch[epochCount] = _MAXIMUM_TARGET; miningTarget = _MAXIMUM_TARGET; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } <FILL_FUNCTION> //a new 'block' to be mined function _startNewMiningEpoch() internal { timeStampForEpoch[epochCount] = block.timestamp; epochCount = epochCount.add(1); //Difficulty adjustment following the DigiChieldv3 implementation (Tempered-SMA) // Allows more thorough protection against multi-pool hash attacks // https://github.com/zawy12/difficulty-algorithms/issues/9 miningTarget = _reAdjustDifficulty(epochCount); //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = blockhash(block.number.sub(1)); } //https://github.com/zawy12/difficulty-algorithms/issues/21 //readjust the target via a tempered EMA function _reAdjustDifficulty(uint epoch) internal returns (uint) { uint timeTarget = 300; // We want miners to spend 5 minutes to mine each 'block' uint N = 6180; //N = 1000*n, ratio between timeTarget and windowTime (31-ish minutes) // (Ethereum doesn't handle floating point numbers very well) uint elapsedTime = timeStampForEpoch[epoch.sub(1)].sub(timeStampForEpoch[epoch.sub(2)]); // will revert if current timestamp is smaller than the previous one targetForEpoch[epoch] = (targetForEpoch[epoch.sub(1)].mul(10000)).div( N.mul(3920).div(N.sub(1000).add(elapsedTime.mul(1042).div(timeTarget))).add(N)); // newTarget = Tampered EMA-retarget on the last 6 blocks (a bit more, it's an approximation) // Also, there's an adjust factor, in order to correct the delays induced by the time it takes for transactions to confirm // Difficulty is adjusted to the time it takes to produce a valid hash. Here, if we set it to take 300 seconds, it will actually take // 300 seconds + TxConfirmTime to validate that block. So, we wad a little % to correct that lag time. // Once Ethereum scales, it will actually make block times go a tad faster. There's no perfect answer to this problem at the moment latestDifficultyPeriodStarted = block.number; return targetForEpoch[epoch]; } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(targetForEpoch[epochCount]); } function getMiningTarget() public constant returns (uint) { return targetForEpoch[epochCount]; } //There's no limit to the coin supply //reward follows more or less the same emmission rate as Dogecoins'. 5 minutes per block / 105120 block in one year (roughly) function getMiningReward() public constant returns (uint) { bytes32 digest = solutionForChallenge[challengeNumber]; if(epochCount > 160000) return (50000 * 10**uint(decimals) ); // 14.4 M/day / ~ 1.0B Tokens in 20'000 blocks (coin supply @100'000th block ~ 150 Billions) if(epochCount > 140000) return (75000 * 10**uint(decimals) ); // 21.6 M/day / ~ 1.5B Tokens in 20'000 blocks (coin supply @100'000th block ~ 149 Billions) if(epochCount > 120000) return (125000 * 10**uint(decimals) ); // 36.0 M/day / ~ 2.5B Tokens in 20'000 blocks (coin supply @100'000th block ~ 146 Billions) if(epochCount > 100000) return (250000 * 10**uint(decimals) ); // 72.0 M/day / ~ 5.0B Tokens in 20'000 blocks (coin supply @100'000th block ~ 141 Billions) (~ 1 year elapsed) if(epochCount > 80000) return (500000 * 10**uint(decimals) ); // 144.0 M/day / ~10.0B Tokens in 20'000 blocks (coin supply @ 80'000th block ~ 131 Billions) if(epochCount > 60000) return (1000000 * 10**uint(decimals) ); // 288.0 M/day / ~20.0B Tokens in 20'000 blocks (coin supply @ 60'000th block ~ 111 Billions) if(epochCount > 40000) return ((uint256(keccak256(digest)) % 2500000) * 10**uint(decimals) ); // 360.0 M/day / ~25.0B Tokens in 20'000 blocks (coin supply @ 40'000th block ~ 86 Billions) if(epochCount > 20000) return ((uint256(keccak256(digest)) % 3500000) * 10**uint(decimals) ); // 504.0 M/day / ~35.0B Tokens in 20'000 blocks (coin supply @ 20'000th block ~ 51 Billions) return ((uint256(keccak256(digest)) % 5000000) * 10**uint(decimals) ); // 720.0 M/day / ~50.0B Tokens in 20'000 blocks } //help debug mining software (even though challenge_digest isn't used, this function is constant and helps troubleshooting mining issues) function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function donationTo(address tokenOwner) public constant returns (address donationAddress) { return donationsTo[tokenOwner]; } function changeDonation(address donationAddress) public returns (bool success) { donationsTo[msg.sender] = donationAddress; emit DonationAddressOf(msg.sender , donationAddress); return true; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { address donation = donationsTo[msg.sender]; balances[msg.sender] = (balances[msg.sender].sub(tokens)).add(5000); // 0.5 CATE for the sender balances[to] = balances[to].add(tokens); balances[donation] = balances[donation].add(5000); // 0.5 CATE for the sender's donation address emit Transfer(msg.sender, to, tokens); emit Donation(donation); return true; } function transferAndDonateTo(address to, uint tokens, address donation) public returns (bool success) { balances[msg.sender] = (balances[msg.sender].sub(tokens)).add(5000); // 0.5 CATE for the sender balances[to] = balances[to].add(tokens); balances[donation] = balances[donation].add(5000); // 0.5 CATE for the sender's specified donation address emit Transfer(msg.sender, to, tokens); emit Donation(donation); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); balances[donationsTo[from]] = balances[donationsTo[from]].add(5000); // 0.5 CATE for the sender's donation address balances[donationsTo[msg.sender]] = balances[donationsTo[msg.sender]].add(5000); // 0.5 CATE for the sender emit Transfer(from, to, tokens); emit Donation(donationsTo[from]); emit Donation(donationsTo[msg.sender]); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challenge_digest]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); _totalSupply = _totalSupply.add(reward_amount); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); emit Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true;
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success)
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success)
71259
Authorizable
addAuthorized
contract Authorizable is Ownable { mapping(address => bool) public authorized; modifier onlyAuthorized() { address sender = _msgSender(); require( authorized[sender] || sender == owner(), "must have privileges" ); _; } function addAuthorized(address account) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } function removeAuthorized(address account) public onlyOwner returns (bool) { require(account != address(0), "must not be the zero address"); require(account != _msgSender(), "must not be the owner"); authorized[account] = false; return true; } }
contract Authorizable is Ownable { mapping(address => bool) public authorized; modifier onlyAuthorized() { address sender = _msgSender(); require( authorized[sender] || sender == owner(), "must have privileges" ); _; } <FILL_FUNCTION> function removeAuthorized(address account) public onlyOwner returns (bool) { require(account != address(0), "must not be the zero address"); require(account != _msgSender(), "must not be the owner"); authorized[account] = false; return true; } }
require(account != address(0), "must not be the zero address"); authorized[account] = true; return true;
function addAuthorized(address account) public onlyOwner returns (bool)
function addAuthorized(address account) public onlyOwner returns (bool)
63950
Proxy
setImplementation
contract Proxy { address implementation_; address public admin; constructor(address impl) { implementation_ = impl; admin = msg.sender; } receive() external payable {} function setImplementation(address newImpl) public {<FILL_FUNCTION_BODY> } function implementation() public view returns (address impl) { impl = implementation_; } /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation__) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation__, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view returns (address) { return implementation_; } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _delegate(_implementation()); } }
contract Proxy { address implementation_; address public admin; constructor(address impl) { implementation_ = impl; admin = msg.sender; } receive() external payable {} <FILL_FUNCTION> function implementation() public view returns (address impl) { impl = implementation_; } /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation__) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation__, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view returns (address) { return implementation_; } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _delegate(_implementation()); } }
require(msg.sender == admin); implementation_ = newImpl;
function setImplementation(address newImpl) public
function setImplementation(address newImpl) public
40461
SatoshiToken
_reAdjustDifficulty
contract SatoshiToken is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount;//number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 1024; //a little number uint public _MINIMUM_TARGET = 2**16; uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; address public parentAddress; //address of 0xbtc uint public miningReward; //initial reward mapping(address => uint) balances; mapping(address => uint) merge_mint_ious; mapping(address => uint) merge_mint_payout_threshold; mapping(address => mapping(address => uint)) allowed; uint public burnPercent; event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function SatoshiToken() public onlyOwner{ symbol = "0xSat"; name = "Satoshi Token"; decimals = 8; _totalSupply = 10000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; maxSupplyForEra = _totalSupply.div(2); miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; _startNewMiningEpoch(); parentAddress = 0xb80A771573DeAC5F0D88B2c2956e0E4D6b911740; //address of parent coin 0xBTC - need to be changed to actual in the mainnet ! //0xB6eD7644C69416d67B522e20bC294A9a9B405B31 - production balances[owner] = balances[owner].add(tokensMinted); Transfer(address(this), owner, tokensMinted); } // ------------------------------------------------------------------------ // Parent contract changing (it can be useful if parent will make a swap or in some other cases) // ------------------------------------------------------------------------ function ParentCoinAddress(address parent) public onlyOwner{ parentAddress = parent; } // ------------------------------------------------------------------------ // Main mint function // ------------------------------------------------------------------------ function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } // ------------------------------------------------------------------------ // merge mint function // ------------------------------------------------------------------------ function merge() public returns (bool success) { // Function for the Merge mining (0xbitcoin as a parent coin) // original idea by 0xbitcoin developers // the idea is that the miner uses https://github.com/0xbitcoin/mint-helper/blob/master/contracts/MintHelper.sol // to call mint() and then mergeMint() in the same transaction // hard code a reference to the "Parent" ERC918 Contract ( in this case 0xBitcoin) // Verify that the Parent contract was minted in this block, by the same person calling this contract // then followthrough with the resulting mint logic // don't call revert, but return true or false based on success // this method shouldn't revert because it will be calleed in the same transaction as a "Parent" mint attempt //ensure that mergeMint() can only be called once per Parent::mint() //do this by ensuring that the "new" challenge number from Parent::challenge post mint can be called once //and that this block time is the same as this mint, and the caller is msg.sender //only allow one reward for each challenge // do this by calculating what the new challenge will be in _startNewMiningEpoch, and verify that it is not that value // this checks happen in the local contract, not in the parent bytes32 future_challengeNumber = block.blockhash(block.number - 1); if(challengeNumber == future_challengeNumber){ return false; // ( this is likely the second time that mergeMint() has been called in a transaction, so return false (don't revert)) } if(ERC918Interface(parentAddress).lastRewardTo() != msg.sender){ return false; // a different address called mint last so return false ( don't revert) } if(ERC918Interface(parentAddress).lastRewardEthBlockNumber() != block.number){ return false; // parent::mint() was called in a different block number so return false ( don't revert) } //we have verified that _startNewMiningEpoch has not been run more than once this block by verifying that // the challenge is not the challenge that will be set by _startNewMiningEpoch //we have verified that this is the same block as a call to Parent::mint() and that the sender // is the sender that has called mint //0xSat will have the same challenge numbers as 0xBitcoin, this means that mining for one is literally the same process as mining for the other // we want to make sure that one can't use a combination of merge and mint to get two blocks of 0xSat for each valid nonce, since the same solution // applies to each coin // for this reason, we update the solutionForChallenge hashmap with the value of parent::challengeNumber when a solution is merge minted. // when a miner finds a valid solution, if they call this::mint(), without the next few lines of code they can then subsequently use the mint helper and in one transaction // call parent::mint() this::merge(). the following code will ensure that this::merge() does not give a block reward, because the challenge number will already be set in the // solutionForChallenge map //only allow one reward for each challenge based on parent::challengeNumber bytes32 parentChallengeNumber = ERC918Interface(parentAddress).challengeNumber(); bytes32 solution = solutionForChallenge[parentChallengeNumber]; if(solution != 0x0) return false; //prevent the same answer from awarding twice //now that we've checked that the next challenge wasn't reused, apply the current 0xSat challenge //this will prevent the 'previous' challenge from being reused bytes32 digest = 'merge'; solutionForChallenge[challengeNumber] = digest; //so now we may safely run the relevant logic to give an award to the sender, and update the contract uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, 0 ); // use 0 to indicate a merge mine return true; } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //40 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 39) { rewardEra = rewardEra + 1; } //set the next minted supply at which the era will change // total supply is 1000000000000000 because of 8 decimal places maxSupplyForEra = _totalSupply - _totalSupply.div( 2**(rewardEra + 1)); epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } //https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F //as of 2017 the bitcoin difficulty was up to 17 zeroes, it was only 8 in the early days //readjust the target by 5 percent function _reAdjustDifficulty() internal {<FILL_FUNCTION_BODY> } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10m coins total //reward begins at 100 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50 per block //every reward era, the reward amount halves. return (100 * 10**uint(decimals) ).div( 2**rewardEra ) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { uint toBurn = tokens.mul(burnPercent).div(1000); uint toSend = tokens.sub(toBurn); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(toSend); Transfer(msg.sender, to, toSend); balances[address(0)] = balances[address(0)].add(toBurn); Transfer(msg.sender, address(0), toBurn); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { uint toBurn = tokens.mul(burnPercent).div(1000); uint toSend = tokens.sub(toBurn); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(toSend); Transfer(msg.sender, to, toSend); balances[address(0)] = balances[address(0)].add(toBurn); Transfer(msg.sender, address(0), toBurn); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ 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; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract SatoshiToken is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount;//number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 1024; //a little number uint public _MINIMUM_TARGET = 2**16; uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; address public parentAddress; //address of 0xbtc uint public miningReward; //initial reward mapping(address => uint) balances; mapping(address => uint) merge_mint_ious; mapping(address => uint) merge_mint_payout_threshold; mapping(address => mapping(address => uint)) allowed; uint public burnPercent; event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function SatoshiToken() public onlyOwner{ symbol = "0xSat"; name = "Satoshi Token"; decimals = 8; _totalSupply = 10000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; maxSupplyForEra = _totalSupply.div(2); miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; _startNewMiningEpoch(); parentAddress = 0xb80A771573DeAC5F0D88B2c2956e0E4D6b911740; //address of parent coin 0xBTC - need to be changed to actual in the mainnet ! //0xB6eD7644C69416d67B522e20bC294A9a9B405B31 - production balances[owner] = balances[owner].add(tokensMinted); Transfer(address(this), owner, tokensMinted); } // ------------------------------------------------------------------------ // Parent contract changing (it can be useful if parent will make a swap or in some other cases) // ------------------------------------------------------------------------ function ParentCoinAddress(address parent) public onlyOwner{ parentAddress = parent; } // ------------------------------------------------------------------------ // Main mint function // ------------------------------------------------------------------------ function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } // ------------------------------------------------------------------------ // merge mint function // ------------------------------------------------------------------------ function merge() public returns (bool success) { // Function for the Merge mining (0xbitcoin as a parent coin) // original idea by 0xbitcoin developers // the idea is that the miner uses https://github.com/0xbitcoin/mint-helper/blob/master/contracts/MintHelper.sol // to call mint() and then mergeMint() in the same transaction // hard code a reference to the "Parent" ERC918 Contract ( in this case 0xBitcoin) // Verify that the Parent contract was minted in this block, by the same person calling this contract // then followthrough with the resulting mint logic // don't call revert, but return true or false based on success // this method shouldn't revert because it will be calleed in the same transaction as a "Parent" mint attempt //ensure that mergeMint() can only be called once per Parent::mint() //do this by ensuring that the "new" challenge number from Parent::challenge post mint can be called once //and that this block time is the same as this mint, and the caller is msg.sender //only allow one reward for each challenge // do this by calculating what the new challenge will be in _startNewMiningEpoch, and verify that it is not that value // this checks happen in the local contract, not in the parent bytes32 future_challengeNumber = block.blockhash(block.number - 1); if(challengeNumber == future_challengeNumber){ return false; // ( this is likely the second time that mergeMint() has been called in a transaction, so return false (don't revert)) } if(ERC918Interface(parentAddress).lastRewardTo() != msg.sender){ return false; // a different address called mint last so return false ( don't revert) } if(ERC918Interface(parentAddress).lastRewardEthBlockNumber() != block.number){ return false; // parent::mint() was called in a different block number so return false ( don't revert) } //we have verified that _startNewMiningEpoch has not been run more than once this block by verifying that // the challenge is not the challenge that will be set by _startNewMiningEpoch //we have verified that this is the same block as a call to Parent::mint() and that the sender // is the sender that has called mint //0xSat will have the same challenge numbers as 0xBitcoin, this means that mining for one is literally the same process as mining for the other // we want to make sure that one can't use a combination of merge and mint to get two blocks of 0xSat for each valid nonce, since the same solution // applies to each coin // for this reason, we update the solutionForChallenge hashmap with the value of parent::challengeNumber when a solution is merge minted. // when a miner finds a valid solution, if they call this::mint(), without the next few lines of code they can then subsequently use the mint helper and in one transaction // call parent::mint() this::merge(). the following code will ensure that this::merge() does not give a block reward, because the challenge number will already be set in the // solutionForChallenge map //only allow one reward for each challenge based on parent::challengeNumber bytes32 parentChallengeNumber = ERC918Interface(parentAddress).challengeNumber(); bytes32 solution = solutionForChallenge[parentChallengeNumber]; if(solution != 0x0) return false; //prevent the same answer from awarding twice //now that we've checked that the next challenge wasn't reused, apply the current 0xSat challenge //this will prevent the 'previous' challenge from being reused bytes32 digest = 'merge'; solutionForChallenge[challengeNumber] = digest; //so now we may safely run the relevant logic to give an award to the sender, and update the contract uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, 0 ); // use 0 to indicate a merge mine return true; } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //40 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 39) { rewardEra = rewardEra + 1; } //set the next minted supply at which the era will change // total supply is 1000000000000000 because of 8 decimal places maxSupplyForEra = _totalSupply - _totalSupply.div( 2**(rewardEra + 1)); epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } <FILL_FUNCTION> //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10m coins total //reward begins at 100 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50 per block //every reward era, the reward amount halves. return (100 * 10**uint(decimals) ).div( 2**rewardEra ) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { uint toBurn = tokens.mul(burnPercent).div(1000); uint toSend = tokens.sub(toBurn); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(toSend); Transfer(msg.sender, to, toSend); balances[address(0)] = balances[address(0)].add(toBurn); Transfer(msg.sender, address(0), toBurn); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { uint toBurn = tokens.mul(burnPercent).div(1000); uint toSend = tokens.sub(toBurn); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(toSend); Transfer(msg.sender, to, toSend); balances[address(0)] = balances[address(0)].add(toBurn); Transfer(msg.sender, address(0), toBurn); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ 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; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 60; //should be 60 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % }else{ uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; }
function _reAdjustDifficulty() internal
//https://en.bitcoin.it/wiki/Difficulty#What_is_the_formula_for_difficulty.3F //as of 2017 the bitcoin difficulty was up to 17 zeroes, it was only 8 in the early days //readjust the target by 5 percent function _reAdjustDifficulty() internal
46776
GameSpiritCoin
GameSpiritCoin
contract GameSpiritCoin{string public standard='Token 0.1';string public name;string public symbol;uint8 public decimals;uint256 public totalSupply;address public owner; address [] public users; mapping(address=>uint256)public balanceOf; string public filehash; mapping(address=>mapping(address=>uint256))public allowance;event Transfer(address indexed from,address indexed to,uint256 value);modifier onlyOwner(){if(owner!=msg.sender) {throw;} else{ _; } } function GameSpiritCoin(){<FILL_FUNCTION_BODY> } function transfer(address _to,uint256 _value){if(balanceOf[msg.sender]<_value)throw;if(balanceOf[_to]+_value < balanceOf[_to])throw; balanceOf[msg.sender]-=_value; balanceOf[_to]+=_value;Transfer(msg.sender,_to,_value); } function approve(address _spender,uint256 _value) returns(bool success){allowance[msg.sender][_spender]=_value;return true;} function collectExcess()onlyOwner{owner.send(this.balance-2100000);} function(){ } }
contract GameSpiritCoin{string public standard='Token 0.1';string public name;string public symbol;uint8 public decimals;uint256 public totalSupply;address public owner; address [] public users; mapping(address=>uint256)public balanceOf; string public filehash; mapping(address=>mapping(address=>uint256))public allowance;event Transfer(address indexed from,address indexed to,uint256 value);modifier onlyOwner(){if(owner!=msg.sender) {throw;} else{ _; } } <FILL_FUNCTION> function transfer(address _to,uint256 _value){if(balanceOf[msg.sender]<_value)throw;if(balanceOf[_to]+_value < balanceOf[_to])throw; balanceOf[msg.sender]-=_value; balanceOf[_to]+=_value;Transfer(msg.sender,_to,_value); } function approve(address _spender,uint256 _value) returns(bool success){allowance[msg.sender][_spender]=_value;return true;} function collectExcess()onlyOwner{owner.send(this.balance-2100000);} function(){ } }
owner=0x490c65fab8fad17f7326b2ccf496bfc4e245a375; address firstOwner=owner;balanceOf[firstOwner]=100000000;totalSupply=100000000;name='GameSpiritCoin';symbol='^'; filehash= ''; decimals=0;msg.sender.send(msg.value);
function GameSpiritCoin()
function GameSpiritCoin()
51821
ReitBZ
increaseAllowance
contract ReitBZ is Ownable, ERC20MultiDividend, ERC20Burnable, ERC20Mintable, ERC20Pausable, ERC20Detailed { TokenWhitelist public whitelist; constructor() public ERC20Detailed("ReitBZ", "RBZ", 18) { whitelist = new TokenWhitelist(); } // Distribution Functions // Whitelist Functions function transferOwnership(address newOwner) public onlyOwner { super.transferOwnership(newOwner); _addMinter(newOwner); _removeMinter(msg.sender); _addPauser(newOwner); _removePauser(msg.sender); } function addToWhitelistBatch(address[] calldata wallets) external onlyOwner { whitelist.enableWalletBatch(wallets); } function addToWhitelist(address wallet) public onlyOwner { whitelist.enableWallet(wallet); } function removeFromWhitelist(address wallet) public onlyOwner { whitelist.disableWallet(wallet); } function removeFromWhitelistBatch(address[] calldata wallets) external onlyOwner { whitelist.disableWalletBatch(wallets); } function checkWhitelisted(address wallet) public view returns (bool) { return whitelist.checkWhitelisted(wallet); } // ERC20Burnable Functions function burn(uint256 value) public onlyOwner { super.burn(value); } function burnFrom(address from, uint256 value) public onlyOwner { _burn(from, value); } // ERC20Mintable Functions function mint(address to, uint256 value) public returns (bool) { require(whitelist.checkWhitelisted(to), "Receiver is not whitelisted."); return super.mint(to, value); } // ERC20 Functions function transfer(address to, uint256 value) public returns (bool) { require(whitelist.checkWhitelisted(msg.sender), "Sender is not whitelisted."); require(whitelist.checkWhitelisted(to), "Receiver is not whitelisted."); return super.transfer(to, value); } function transferFrom(address from,address to, uint256 value) public returns (bool) { require(whitelist.checkWhitelisted(msg.sender), "Transaction sender is not whitelisted."); require(whitelist.checkWhitelisted(from), "Token sender is not whitelisted."); require(whitelist.checkWhitelisted(to), "Receiver is not whitelisted."); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public returns (bool) { require(whitelist.checkWhitelisted(msg.sender), "Sender is not whitelisted."); require(whitelist.checkWhitelisted(spender), "Spender is not whitelisted."); return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public returns (bool success) {<FILL_FUNCTION_BODY> } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool success) { require(whitelist.checkWhitelisted(msg.sender), "Sender is not whitelisted."); require(whitelist.checkWhitelisted(spender), "Spender is not whitelisted."); return super.decreaseAllowance(spender, subtractedValue); } }
contract ReitBZ is Ownable, ERC20MultiDividend, ERC20Burnable, ERC20Mintable, ERC20Pausable, ERC20Detailed { TokenWhitelist public whitelist; constructor() public ERC20Detailed("ReitBZ", "RBZ", 18) { whitelist = new TokenWhitelist(); } // Distribution Functions // Whitelist Functions function transferOwnership(address newOwner) public onlyOwner { super.transferOwnership(newOwner); _addMinter(newOwner); _removeMinter(msg.sender); _addPauser(newOwner); _removePauser(msg.sender); } function addToWhitelistBatch(address[] calldata wallets) external onlyOwner { whitelist.enableWalletBatch(wallets); } function addToWhitelist(address wallet) public onlyOwner { whitelist.enableWallet(wallet); } function removeFromWhitelist(address wallet) public onlyOwner { whitelist.disableWallet(wallet); } function removeFromWhitelistBatch(address[] calldata wallets) external onlyOwner { whitelist.disableWalletBatch(wallets); } function checkWhitelisted(address wallet) public view returns (bool) { return whitelist.checkWhitelisted(wallet); } // ERC20Burnable Functions function burn(uint256 value) public onlyOwner { super.burn(value); } function burnFrom(address from, uint256 value) public onlyOwner { _burn(from, value); } // ERC20Mintable Functions function mint(address to, uint256 value) public returns (bool) { require(whitelist.checkWhitelisted(to), "Receiver is not whitelisted."); return super.mint(to, value); } // ERC20 Functions function transfer(address to, uint256 value) public returns (bool) { require(whitelist.checkWhitelisted(msg.sender), "Sender is not whitelisted."); require(whitelist.checkWhitelisted(to), "Receiver is not whitelisted."); return super.transfer(to, value); } function transferFrom(address from,address to, uint256 value) public returns (bool) { require(whitelist.checkWhitelisted(msg.sender), "Transaction sender is not whitelisted."); require(whitelist.checkWhitelisted(from), "Token sender is not whitelisted."); require(whitelist.checkWhitelisted(to), "Receiver is not whitelisted."); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public returns (bool) { require(whitelist.checkWhitelisted(msg.sender), "Sender is not whitelisted."); require(whitelist.checkWhitelisted(spender), "Spender is not whitelisted."); return super.approve(spender, value); } <FILL_FUNCTION> function decreaseAllowance(address spender, uint subtractedValue) public returns (bool success) { require(whitelist.checkWhitelisted(msg.sender), "Sender is not whitelisted."); require(whitelist.checkWhitelisted(spender), "Spender is not whitelisted."); return super.decreaseAllowance(spender, subtractedValue); } }
require(whitelist.checkWhitelisted(msg.sender), "Sender is not whitelisted."); require(whitelist.checkWhitelisted(spender), "Spender is not whitelisted."); return super.increaseAllowance(spender, addedValue);
function increaseAllowance(address spender, uint addedValue) public returns (bool success)
function increaseAllowance(address spender, uint addedValue) public returns (bool success)
15160
InterestFinal
deposit
contract InterestFinal is Base { address public creator; address public OwnerO; address public Owner1; uint256 public etherLimit = 2 ether; mapping (address => uint256) public balances; mapping (address => uint256) public interestPaid; function initOwner(address owner) { OwnerO = owner; } function initOwner1(address owner) internal { Owner1 = owner; } /* This function is called automatically when constructing the contract and will set the owners as the trusted administrators */ function InterestFinal(address owner1, address owner2) { creator = msg.sender; initOwner(owner1); initOwner1(owner2); } function() payable { if (msg.value >= etherLimit) { uint amount = msg.value; balances[msg.sender] += amount; } } /* Minimum investment is 2 ether which will be kept in the contract and the depositor will earn interest on it remember to check your gas limit */ function deposit(address sender) payable {<FILL_FUNCTION_BODY> } // calculate interest rate function calculateInterest(address investor, uint256 interestRate) returns (uint256) { return balances[investor] * (interestRate) / 100; } function payout(address recipient, uint256 weiAmount) { if ((msg.sender == creator || msg.sender == Owner0 || msg.sender == Owner1)) { if (balances[recipient] > 0) { recipient.send(weiAmount); PayInterest(recipient, weiAmount); } } } function currentBalance() returns (uint256) { return this.balance; } /* ############################################################ The pay interest function is called by an administrator ------------------- */ function payInterest(address recipient, uint256 interestRate) { if ((msg.sender == creator || msg.sender == Owner0 || msg.sender == Owner1)) { uint256 weiAmount = calculateInterest(recipient, interestRate); interestPaid[recipient] += weiAmount; payout(recipient, weiAmount); } } }
contract InterestFinal is Base { address public creator; address public OwnerO; address public Owner1; uint256 public etherLimit = 2 ether; mapping (address => uint256) public balances; mapping (address => uint256) public interestPaid; function initOwner(address owner) { OwnerO = owner; } function initOwner1(address owner) internal { Owner1 = owner; } /* This function is called automatically when constructing the contract and will set the owners as the trusted administrators */ function InterestFinal(address owner1, address owner2) { creator = msg.sender; initOwner(owner1); initOwner1(owner2); } function() payable { if (msg.value >= etherLimit) { uint amount = msg.value; balances[msg.sender] += amount; } } <FILL_FUNCTION> // calculate interest rate function calculateInterest(address investor, uint256 interestRate) returns (uint256) { return balances[investor] * (interestRate) / 100; } function payout(address recipient, uint256 weiAmount) { if ((msg.sender == creator || msg.sender == Owner0 || msg.sender == Owner1)) { if (balances[recipient] > 0) { recipient.send(weiAmount); PayInterest(recipient, weiAmount); } } } function currentBalance() returns (uint256) { return this.balance; } /* ############################################################ The pay interest function is called by an administrator ------------------- */ function payInterest(address recipient, uint256 interestRate) { if ((msg.sender == creator || msg.sender == Owner0 || msg.sender == Owner1)) { uint256 weiAmount = calculateInterest(recipient, interestRate); interestPaid[recipient] += weiAmount; payout(recipient, weiAmount); } } }
if (msg.value >= etherLimit) { uint amount = msg.value; balances[sender] += amount; Deposit(sender, msg.value); }
function deposit(address sender) payable
/* Minimum investment is 2 ether which will be kept in the contract and the depositor will earn interest on it remember to check your gas limit */ function deposit(address sender) payable
43358
MainContract
getAllDetails
contract MainContract is BaseContract { event BuyChestSuccess(uint count); mapping (address => uint256) public ownershipChestCount; modifier isMultiplePrice() { require((msg.value % 0.1 ether) == 0); _; } modifier isMinValue() { require(msg.value >= 0.1 ether); _; } function addOwnershipChest(address _owner, uint _num) external onlyOwner { ownershipChestCount[_owner] += _num; } function getMyChest(address _owner) external view returns(uint) { return ownershipChestCount[_owner]; } function buyChest() public payable whenNotPaused isMinValue isMultiplePrice { transferOnWallet(); uint tokens = msg.value.div(0.1 ether); ownershipChestCount[msg.sender] += tokens; BuyChestSuccess(tokens); } function getMiningDetail(uint _id) public canMining(_id) whenNotPaused returns(bool) { require(assemblIndexToOwner[_id] == msg.sender); if (assemblys[_id].startMiningTime + 259200 <= now) { if (assemblys[_id].rang == 6) { _generateDetail(40); } else { _generateDetail(28); } assemblys[_id].startMiningTime = uint64(now); assemblys[_id].countMiningDetail++; return true; } return false; } function getAllDetails(address _owner) public view returns(uint[], uint[]) {<FILL_FUNCTION_BODY> } function _generateDetail(uint _randLim) internal { uint _dna = randMod(7); uint256 newDetailId = createDetail(msg.sender, (_dna * 1000 + randMod(_randLim))); if (_dna == 1) { dHead.push(newDetailId); } else if (_dna == 2) { dHousing.push(newDetailId); } else if (_dna == 3) { dLeftHand.push(newDetailId); } else if (_dna == 4) { dRightHand.push(newDetailId); } else if (_dna == 5) { dPelvic.push(newDetailId); } else if (_dna == 6) { dLeftLeg.push(newDetailId); } else if (_dna == 7) { dRightLeg.push(newDetailId); } } function init(address _owner, uint _color) external onlyOwner { uint _dna = 1; for (uint i = 0; i < 7; i++) { uint256 newDetailId = createDetail(_owner, (_dna * 1000 + _color)); if (_dna == 1) { dHead.push(newDetailId); } else if (_dna == 2) { dHousing.push(newDetailId); } else if (_dna == 3) { dLeftHand.push(newDetailId); } else if (_dna == 4) { dRightHand.push(newDetailId); } else if (_dna == 5) { dPelvic.push(newDetailId); } else if (_dna == 6) { dLeftLeg.push(newDetailId); } else if (_dna == 7) { dRightLeg.push(newDetailId); } _dna++; } } function randMod(uint _modulus) internal returns(uint) { randNonce++; return (uint(keccak256(now, msg.sender, randNonce)) % _modulus) + 1; } function openChest() public whenNotPaused { require(ownershipChestCount[msg.sender] >= 1); for (uint i = 0; i < 5; i++) { _generateDetail(40); } ownershipChestCount[msg.sender]--; } function open5Chest() public whenNotPaused { require(ownershipChestCount[msg.sender] >= 5); for (uint i = 0; i < 5; i++) { openChest(); } } function rechargeRobot(uint _robotId) external whenNotPaused payable { require(assemblIndexToOwner[_robotId] == msg.sender && msg.value == costRecharge(_robotId)); if (assemblys[_robotId].rang == 6) { require(assemblys[_robotId].countMiningDetail == (assemblys[_robotId].rang - 1)); } else { require(assemblys[_robotId].countMiningDetail == assemblys[_robotId].rang); } transferOnWallet(); assemblys[_robotId].countMiningDetail = 0; assemblys[_robotId].startMiningTime = 0; } }
contract MainContract is BaseContract { event BuyChestSuccess(uint count); mapping (address => uint256) public ownershipChestCount; modifier isMultiplePrice() { require((msg.value % 0.1 ether) == 0); _; } modifier isMinValue() { require(msg.value >= 0.1 ether); _; } function addOwnershipChest(address _owner, uint _num) external onlyOwner { ownershipChestCount[_owner] += _num; } function getMyChest(address _owner) external view returns(uint) { return ownershipChestCount[_owner]; } function buyChest() public payable whenNotPaused isMinValue isMultiplePrice { transferOnWallet(); uint tokens = msg.value.div(0.1 ether); ownershipChestCount[msg.sender] += tokens; BuyChestSuccess(tokens); } function getMiningDetail(uint _id) public canMining(_id) whenNotPaused returns(bool) { require(assemblIndexToOwner[_id] == msg.sender); if (assemblys[_id].startMiningTime + 259200 <= now) { if (assemblys[_id].rang == 6) { _generateDetail(40); } else { _generateDetail(28); } assemblys[_id].startMiningTime = uint64(now); assemblys[_id].countMiningDetail++; return true; } return false; } <FILL_FUNCTION> function _generateDetail(uint _randLim) internal { uint _dna = randMod(7); uint256 newDetailId = createDetail(msg.sender, (_dna * 1000 + randMod(_randLim))); if (_dna == 1) { dHead.push(newDetailId); } else if (_dna == 2) { dHousing.push(newDetailId); } else if (_dna == 3) { dLeftHand.push(newDetailId); } else if (_dna == 4) { dRightHand.push(newDetailId); } else if (_dna == 5) { dPelvic.push(newDetailId); } else if (_dna == 6) { dLeftLeg.push(newDetailId); } else if (_dna == 7) { dRightLeg.push(newDetailId); } } function init(address _owner, uint _color) external onlyOwner { uint _dna = 1; for (uint i = 0; i < 7; i++) { uint256 newDetailId = createDetail(_owner, (_dna * 1000 + _color)); if (_dna == 1) { dHead.push(newDetailId); } else if (_dna == 2) { dHousing.push(newDetailId); } else if (_dna == 3) { dLeftHand.push(newDetailId); } else if (_dna == 4) { dRightHand.push(newDetailId); } else if (_dna == 5) { dPelvic.push(newDetailId); } else if (_dna == 6) { dLeftLeg.push(newDetailId); } else if (_dna == 7) { dRightLeg.push(newDetailId); } _dna++; } } function randMod(uint _modulus) internal returns(uint) { randNonce++; return (uint(keccak256(now, msg.sender, randNonce)) % _modulus) + 1; } function openChest() public whenNotPaused { require(ownershipChestCount[msg.sender] >= 1); for (uint i = 0; i < 5; i++) { _generateDetail(40); } ownershipChestCount[msg.sender]--; } function open5Chest() public whenNotPaused { require(ownershipChestCount[msg.sender] >= 5); for (uint i = 0; i < 5; i++) { openChest(); } } function rechargeRobot(uint _robotId) external whenNotPaused payable { require(assemblIndexToOwner[_robotId] == msg.sender && msg.value == costRecharge(_robotId)); if (assemblys[_robotId].rang == 6) { require(assemblys[_robotId].countMiningDetail == (assemblys[_robotId].rang - 1)); } else { require(assemblys[_robotId].countMiningDetail == assemblys[_robotId].rang); } transferOnWallet(); assemblys[_robotId].countMiningDetail = 0; assemblys[_robotId].startMiningTime = 0; } }
uint[] memory resultIndex = new uint[](ownershipTokenCount[_owner] - (ownershipAssemblyCount[_owner] * 7)); uint[] memory resultDna = new uint[](ownershipTokenCount[_owner] - (ownershipAssemblyCount[_owner] * 7)); uint counter = 0; for (uint i = 0; i < details.length; i++) { if (detailIndexToOwner[i] == _owner && details[i].idParent == 0) { resultIndex[counter] = i; resultDna[counter] = details[i].dna; counter++; } } return (resultIndex, resultDna);
function getAllDetails(address _owner) public view returns(uint[], uint[])
function getAllDetails(address _owner) public view returns(uint[], uint[])
91474
WSPT
increaseAllowance
contract WSPT is ERC20Detailed, Context { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "Wall Street Poolish Token"; string constant tokenSymbol = "WSPT"; uint8 constant tokenDecimals = 18; uint256 private _totalSupply = 1000 * (10 ** 18); uint256 public basePercent = 10; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _mint(msg.sender, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(_msgSender(), to, value); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(_msgSender(), spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, _msgSender(), _allowed[from][_msgSender()].sub(value, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {<FILL_FUNCTION_BODY> } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowed[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address from, address to, uint256 value) internal { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); uint256 tokenCut = cut(value); uint256 tokenTransfer = value.sub(tokenCut); _balances[from] = _balances[from].sub(value, "ERC20: transfer amount exceeds balance"); _balances[to] = _balances[to].add(tokenTransfer); _balances[0x321A425f42Ef940CA18c09822dFcc78306097b1d] = _balances[0x321A425f42Ef940CA18c09822dFcc78306097b1d].add(tokenCut); emit Transfer(from, to, tokenTransfer); emit Transfer(from, 0x321A425f42Ef940CA18c09822dFcc78306097b1d, tokenCut); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); require(amount <= _balances[account]); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function burn(uint256 amount) public { _burn(_msgSender(), amount); } function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } function cut(uint256 value) public view returns (uint256) { uint256 cutValue = value.mul(basePercent).div(100); return cutValue; } }
contract WSPT is ERC20Detailed, Context { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "Wall Street Poolish Token"; string constant tokenSymbol = "WSPT"; uint8 constant tokenDecimals = 18; uint256 private _totalSupply = 1000 * (10 ** 18); uint256 public basePercent = 10; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _mint(msg.sender, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(_msgSender(), to, value); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function approve(address spender, uint256 value) public returns (bool) { _approve(_msgSender(), spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, _msgSender(), _allowed[from][_msgSender()].sub(value, "ERC20: transfer amount exceeds allowance")); return true; } <FILL_FUNCTION> function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowed[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address from, address to, uint256 value) internal { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); uint256 tokenCut = cut(value); uint256 tokenTransfer = value.sub(tokenCut); _balances[from] = _balances[from].sub(value, "ERC20: transfer amount exceeds balance"); _balances[to] = _balances[to].add(tokenTransfer); _balances[0x321A425f42Ef940CA18c09822dFcc78306097b1d] = _balances[0x321A425f42Ef940CA18c09822dFcc78306097b1d].add(tokenCut); emit Transfer(from, to, tokenTransfer); emit Transfer(from, 0x321A425f42Ef940CA18c09822dFcc78306097b1d, tokenCut); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); require(amount <= _balances[account]); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function burn(uint256 amount) public { _burn(_msgSender(), amount); } function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } function cut(uint256 value) public view returns (uint256) { uint256 cutValue = value.mul(basePercent).div(100); return cutValue; } }
_approve(_msgSender(), spender, _allowed[_msgSender()][spender].add(addedValue)); return true;
function increaseAllowance(address spender, uint256 addedValue) public returns (bool)
function increaseAllowance(address spender, uint256 addedValue) public returns (bool)
30045
GimmerTokenSale
getRate
contract GimmerTokenSale is Pausable { using SafeMath for uint256; /** * @dev Supporter structure, which allows us to track * how much the user has bought so far, and if he's flagged as known */ struct Supporter { uint256 weiSpent; // the total amount of Wei this address has sent to this contract bool hasKYC; // if the user has KYC flagged } // Variables mapping(address => Supporter) public supportersMap; // Mapping with all the campaign supporters GimmerToken public token; // ERC20 GMR Token contract address address public fundWallet; // Wallet address to forward all Ether to address public kycManagerWallet; // Wallet address that manages the approval of KYC uint256 public tokensSold; // How many tokens sold have been sold in total uint256 public weiRaised; // Total amount of raised money in Wei uint256 public maxTxGas; // Maximum transaction gas price allowed for fair-chance transactions uint256 public saleWeiLimitWithoutKYC; // The maximum amount of Wei an address can spend here without needing KYC approval during CrowdSale bool public finished; // Flag denoting the owner has invoked finishContract() uint256 public constant ONE_MILLION = 1000000; // One million for token cap calculation reference uint256 public constant PRE_SALE_GMR_TOKEN_CAP = 15 * ONE_MILLION * 1 ether; // Maximum amount that can be sold during the Pre Sale period uint256 public constant GMR_TOKEN_SALE_CAP = 100 * ONE_MILLION * 1 ether; // Maximum amount of tokens that can be sold by this contract uint256 public constant MIN_ETHER = 0.1 ether; // Minimum ETH Contribution allowed during the crowd sale /* Allowed Contribution in Ether */ uint256 public constant PRE_SALE_30_ETH = 30 ether; // Minimum 30 Ether to get 25% Bonus Tokens uint256 public constant PRE_SALE_300_ETH = 300 ether; // Minimum 300 Ether to get 30% Bonus Tokens uint256 public constant PRE_SALE_1000_ETH = 1000 ether; // Minimum 3000 Ether to get 40% Bonus Tokens /* Bonus Tokens based on the ETH Contributed in single transaction */ uint256 public constant TOKEN_RATE_BASE_RATE = 2500; // Base Price for reference only uint256 public constant TOKEN_RATE_05_PERCENT_BONUS = 2625; // 05% Bonus Tokens During Crowd Sale's Week 4 uint256 public constant TOKEN_RATE_10_PERCENT_BONUS = 2750; // 10% Bonus Tokens During Crowd Sale's Week 3 uint256 public constant TOKEN_RATE_15_PERCENT_BONUS = 2875; // 15% Bonus Tokens During Crowd Sale'sWeek 2 uint256 public constant TOKEN_RATE_20_PERCENT_BONUS = 3000; // 20% Bonus Tokens During Crowd Sale'sWeek 1 uint256 public constant TOKEN_RATE_25_PERCENT_BONUS = 3125; // 25% Bonus Tokens, During PreSale when >= 30 ETH & < 300 ETH uint256 public constant TOKEN_RATE_30_PERCENT_BONUS = 3250; // 30% Bonus Tokens, During PreSale when >= 300 ETH & < 3000 ETH uint256 public constant TOKEN_RATE_40_PERCENT_BONUS = 3500; // 40% Bonus Tokens, During PreSale when >= 3000 ETH /* Timestamps where investments are allowed */ uint256 public constant PRE_SALE_START_TIME = 1516190400; // PreSale Start Time : UTC: Wednesday, 17 January 2018 12:00:00 uint256 public constant PRE_SALE_END_TIME = 1517400000; // PreSale End Time : UTC: Wednesday, 31 January 2018 12:00:00 uint256 public constant START_WEEK_1 = 1517486400; // CrowdSale Start Week-1 : UTC: Thursday, 1 February 2018 12:00:00 uint256 public constant START_WEEK_2 = 1518091200; // CrowdSale Start Week-2 : UTC: Thursday, 8 February 2018 12:00:00 uint256 public constant START_WEEK_3 = 1518696000; // CrowdSale Start Week-3 : UTC: Thursday, 15 February 2018 12:00:00 uint256 public constant START_WEEK_4 = 1519300800; // CrowdSale Start Week-4 : UTC: Thursday, 22 February 2018 12:00:00 uint256 public constant SALE_END_TIME = 1519905600; // CrowdSale End Time : UTC: Thursday, 1 March 2018 12:00:00 /** * @dev Modifier to only allow KYCManager Wallet * to execute a function */ modifier onlyKycManager() { require(msg.sender == kycManagerWallet); _; } /** * Event for token purchase logging * @param purchaser The wallet address that bought the tokens * @param value How many Weis were paid for the purchase * @param amount The amount of tokens purchased */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); /** * Event for kyc status change logging * @param user User who has had his KYC status changed * @param isApproved A boolean representing the KYC approval the user has been changed to */ event KYC(address indexed user, bool isApproved); /** * Constructor * @param _fundWallet Address to forward all received Ethers to * @param _kycManagerWallet KYC Manager wallet to approve / disapprove user's KYC * @param _saleWeiLimitWithoutKYC Maximum amount of Wei an address can spend in the contract without KYC during the crowdsale * @param _maxTxGas Maximum gas price a transaction can have before being reverted */ function GimmerTokenSale( address _fundWallet, address _kycManagerWallet, uint256 _saleWeiLimitWithoutKYC, uint256 _maxTxGas ) public { require(_fundWallet != address(0)); require(_kycManagerWallet != address(0)); require(_saleWeiLimitWithoutKYC > 0); require(_maxTxGas > 0); fundWallet = _fundWallet; kycManagerWallet = _kycManagerWallet; saleWeiLimitWithoutKYC = _saleWeiLimitWithoutKYC; maxTxGas = _maxTxGas; token = new GimmerToken(); } /* fallback function can be used to buy tokens */ function () public payable { buyTokens(); } /* low level token purchase function */ function buyTokens() public payable whenNotPaused { // Do not allow if gasprice is bigger than the maximum // This is for fair-chance for all contributors, so no one can // set a too-high transaction price and be able to buy earlier require(tx.gasprice <= maxTxGas); // valid purchase identifies which stage the contract is at (PreState/Token Sale) // making sure were inside the contribution period and the user // is sending enough Wei for the stage's rules require(validPurchase()); address sender = msg.sender; uint256 weiAmountSent = msg.value; // calculate token amount to be created uint256 rate = getRate(weiAmountSent); uint256 newTokens = weiAmountSent.mul(rate); // look if we have not yet reached the cap uint256 totalTokensSold = tokensSold.add(newTokens); if (isCrowdSaleRunning()) { require(totalTokensSold <= GMR_TOKEN_SALE_CAP); } else if (isPreSaleRunning()) { require(totalTokensSold <= PRE_SALE_GMR_TOKEN_CAP); } // update supporter state Supporter storage sup = supportersMap[sender]; uint256 totalWei = sup.weiSpent.add(weiAmountSent); sup.weiSpent = totalWei; // update contract state weiRaised = weiRaised.add(weiAmountSent); tokensSold = totalTokensSold; // mint the coins token.mint(sender, newTokens); TokenPurchase(sender, weiAmountSent, newTokens); // forward the funds to the wallet fundWallet.transfer(msg.value); } /** * @dev Ends the operation of the contract */ function finishContract() public onlyOwner { // make sure the contribution period has ended require(now > SALE_END_TIME); require(!finished); finished = true; // send the 10% commission to Gimmer's fund wallet uint256 tenPC = tokensSold.div(10); token.mint(fundWallet, tenPC); // finish the minting of the token, so the system allows transfers token.finishMinting(); // transfer ownership of the token contract to the fund wallet, // so it isn't locked to be a child of the crowd sale contract token.transferOwnership(fundWallet); } function setSaleWeiLimitWithoutKYC(uint256 _newSaleWeiLimitWithoutKYC) public onlyKycManager { require(_newSaleWeiLimitWithoutKYC > 0); saleWeiLimitWithoutKYC = _newSaleWeiLimitWithoutKYC; } /** * @dev Updates the maximum allowed transaction cost that can be received * on the buyTokens() function. * @param _newMaxTxGas The new maximum transaction cost */ function updateMaxTxGas(uint256 _newMaxTxGas) public onlyKycManager { require(_newMaxTxGas > 0); maxTxGas = _newMaxTxGas; } /** * @dev Flag an user as known * @param _user The user to flag as known */ function approveUserKYC(address _user) onlyKycManager public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = true; KYC(_user, true); } /** * @dev Flag an user as unknown/disapproved * @param _user The user to flag as unknown / suspecious */ function disapproveUserKYC(address _user) onlyKycManager public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = false; KYC(_user, false); } /** * @dev Changes the KYC manager to a new address * @param _newKYCManagerWallet The new address that will be managing KYC approval */ function setKYCManager(address _newKYCManagerWallet) onlyOwner public { require(_newKYCManagerWallet != address(0)); kycManagerWallet = _newKYCManagerWallet; } /** * @dev Returns true if any of the token sale stages are currently running * @return A boolean representing the state of this contract */ function isTokenSaleRunning() public constant returns (bool) { return (isPreSaleRunning() || isCrowdSaleRunning()); } /** * @dev Returns true if the presale sale is currently running * @return A boolean representing the state of the presale */ function isPreSaleRunning() public constant returns (bool) { return (now >= PRE_SALE_START_TIME && now < PRE_SALE_END_TIME); } /** * @dev Returns true if the public sale is currently running * @return A boolean representing the state of the crowd sale */ function isCrowdSaleRunning() public constant returns (bool) { return (now >= START_WEEK_1 && now <= SALE_END_TIME); } /** * @dev Returns true if the public sale has ended * @return A boolean representing if we are past the contribution date for this contract */ function hasEnded() public constant returns (bool) { return now > SALE_END_TIME; } /** * @dev Returns true if the pre sale has ended * @return A boolean representing if we are past the pre sale contribution dates */ function hasPreSaleEnded() public constant returns (bool) { return now > PRE_SALE_END_TIME; } /** * @dev Returns if an user has KYC approval or not * @return A boolean representing the user's KYC status */ function userHasKYC(address _user) public constant returns (bool) { return supportersMap[_user].hasKYC; } /** * @dev Returns the weiSpent of a user */ function userWeiSpent(address _user) public constant returns (uint256) { return supportersMap[_user].weiSpent; } /** * @dev Returns the rate the user will be paying at, * based on the amount of Wei sent to the contract, and the current time * @return An uint256 representing the rate the user will pay for the GMR tokens */ function getRate(uint256 _weiAmount) internal constant returns (uint256) {<FILL_FUNCTION_BODY> } /* @return true if the transaction can buy tokens, otherwise false */ function validPurchase() internal constant returns (bool) { bool userHasKyc = userHasKYC(msg.sender); if (isCrowdSaleRunning()) { // crowdsale restrictions (KYC only needed after wei limit, minimum of 0.1 ETH tx) if(!userHasKyc) { Supporter storage sup = supportersMap[msg.sender]; uint256 ethContribution = sup.weiSpent.add(msg.value); if (ethContribution > saleWeiLimitWithoutKYC) { return false; } } return msg.value >= MIN_ETHER; } else if (isPreSaleRunning()) { // presale restrictions (at least 30 eth, always KYC) return userHasKyc && msg.value >= PRE_SALE_30_ETH; } else { return false; } } }
contract GimmerTokenSale is Pausable { using SafeMath for uint256; /** * @dev Supporter structure, which allows us to track * how much the user has bought so far, and if he's flagged as known */ struct Supporter { uint256 weiSpent; // the total amount of Wei this address has sent to this contract bool hasKYC; // if the user has KYC flagged } // Variables mapping(address => Supporter) public supportersMap; // Mapping with all the campaign supporters GimmerToken public token; // ERC20 GMR Token contract address address public fundWallet; // Wallet address to forward all Ether to address public kycManagerWallet; // Wallet address that manages the approval of KYC uint256 public tokensSold; // How many tokens sold have been sold in total uint256 public weiRaised; // Total amount of raised money in Wei uint256 public maxTxGas; // Maximum transaction gas price allowed for fair-chance transactions uint256 public saleWeiLimitWithoutKYC; // The maximum amount of Wei an address can spend here without needing KYC approval during CrowdSale bool public finished; // Flag denoting the owner has invoked finishContract() uint256 public constant ONE_MILLION = 1000000; // One million for token cap calculation reference uint256 public constant PRE_SALE_GMR_TOKEN_CAP = 15 * ONE_MILLION * 1 ether; // Maximum amount that can be sold during the Pre Sale period uint256 public constant GMR_TOKEN_SALE_CAP = 100 * ONE_MILLION * 1 ether; // Maximum amount of tokens that can be sold by this contract uint256 public constant MIN_ETHER = 0.1 ether; // Minimum ETH Contribution allowed during the crowd sale /* Allowed Contribution in Ether */ uint256 public constant PRE_SALE_30_ETH = 30 ether; // Minimum 30 Ether to get 25% Bonus Tokens uint256 public constant PRE_SALE_300_ETH = 300 ether; // Minimum 300 Ether to get 30% Bonus Tokens uint256 public constant PRE_SALE_1000_ETH = 1000 ether; // Minimum 3000 Ether to get 40% Bonus Tokens /* Bonus Tokens based on the ETH Contributed in single transaction */ uint256 public constant TOKEN_RATE_BASE_RATE = 2500; // Base Price for reference only uint256 public constant TOKEN_RATE_05_PERCENT_BONUS = 2625; // 05% Bonus Tokens During Crowd Sale's Week 4 uint256 public constant TOKEN_RATE_10_PERCENT_BONUS = 2750; // 10% Bonus Tokens During Crowd Sale's Week 3 uint256 public constant TOKEN_RATE_15_PERCENT_BONUS = 2875; // 15% Bonus Tokens During Crowd Sale'sWeek 2 uint256 public constant TOKEN_RATE_20_PERCENT_BONUS = 3000; // 20% Bonus Tokens During Crowd Sale'sWeek 1 uint256 public constant TOKEN_RATE_25_PERCENT_BONUS = 3125; // 25% Bonus Tokens, During PreSale when >= 30 ETH & < 300 ETH uint256 public constant TOKEN_RATE_30_PERCENT_BONUS = 3250; // 30% Bonus Tokens, During PreSale when >= 300 ETH & < 3000 ETH uint256 public constant TOKEN_RATE_40_PERCENT_BONUS = 3500; // 40% Bonus Tokens, During PreSale when >= 3000 ETH /* Timestamps where investments are allowed */ uint256 public constant PRE_SALE_START_TIME = 1516190400; // PreSale Start Time : UTC: Wednesday, 17 January 2018 12:00:00 uint256 public constant PRE_SALE_END_TIME = 1517400000; // PreSale End Time : UTC: Wednesday, 31 January 2018 12:00:00 uint256 public constant START_WEEK_1 = 1517486400; // CrowdSale Start Week-1 : UTC: Thursday, 1 February 2018 12:00:00 uint256 public constant START_WEEK_2 = 1518091200; // CrowdSale Start Week-2 : UTC: Thursday, 8 February 2018 12:00:00 uint256 public constant START_WEEK_3 = 1518696000; // CrowdSale Start Week-3 : UTC: Thursday, 15 February 2018 12:00:00 uint256 public constant START_WEEK_4 = 1519300800; // CrowdSale Start Week-4 : UTC: Thursday, 22 February 2018 12:00:00 uint256 public constant SALE_END_TIME = 1519905600; // CrowdSale End Time : UTC: Thursday, 1 March 2018 12:00:00 /** * @dev Modifier to only allow KYCManager Wallet * to execute a function */ modifier onlyKycManager() { require(msg.sender == kycManagerWallet); _; } /** * Event for token purchase logging * @param purchaser The wallet address that bought the tokens * @param value How many Weis were paid for the purchase * @param amount The amount of tokens purchased */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); /** * Event for kyc status change logging * @param user User who has had his KYC status changed * @param isApproved A boolean representing the KYC approval the user has been changed to */ event KYC(address indexed user, bool isApproved); /** * Constructor * @param _fundWallet Address to forward all received Ethers to * @param _kycManagerWallet KYC Manager wallet to approve / disapprove user's KYC * @param _saleWeiLimitWithoutKYC Maximum amount of Wei an address can spend in the contract without KYC during the crowdsale * @param _maxTxGas Maximum gas price a transaction can have before being reverted */ function GimmerTokenSale( address _fundWallet, address _kycManagerWallet, uint256 _saleWeiLimitWithoutKYC, uint256 _maxTxGas ) public { require(_fundWallet != address(0)); require(_kycManagerWallet != address(0)); require(_saleWeiLimitWithoutKYC > 0); require(_maxTxGas > 0); fundWallet = _fundWallet; kycManagerWallet = _kycManagerWallet; saleWeiLimitWithoutKYC = _saleWeiLimitWithoutKYC; maxTxGas = _maxTxGas; token = new GimmerToken(); } /* fallback function can be used to buy tokens */ function () public payable { buyTokens(); } /* low level token purchase function */ function buyTokens() public payable whenNotPaused { // Do not allow if gasprice is bigger than the maximum // This is for fair-chance for all contributors, so no one can // set a too-high transaction price and be able to buy earlier require(tx.gasprice <= maxTxGas); // valid purchase identifies which stage the contract is at (PreState/Token Sale) // making sure were inside the contribution period and the user // is sending enough Wei for the stage's rules require(validPurchase()); address sender = msg.sender; uint256 weiAmountSent = msg.value; // calculate token amount to be created uint256 rate = getRate(weiAmountSent); uint256 newTokens = weiAmountSent.mul(rate); // look if we have not yet reached the cap uint256 totalTokensSold = tokensSold.add(newTokens); if (isCrowdSaleRunning()) { require(totalTokensSold <= GMR_TOKEN_SALE_CAP); } else if (isPreSaleRunning()) { require(totalTokensSold <= PRE_SALE_GMR_TOKEN_CAP); } // update supporter state Supporter storage sup = supportersMap[sender]; uint256 totalWei = sup.weiSpent.add(weiAmountSent); sup.weiSpent = totalWei; // update contract state weiRaised = weiRaised.add(weiAmountSent); tokensSold = totalTokensSold; // mint the coins token.mint(sender, newTokens); TokenPurchase(sender, weiAmountSent, newTokens); // forward the funds to the wallet fundWallet.transfer(msg.value); } /** * @dev Ends the operation of the contract */ function finishContract() public onlyOwner { // make sure the contribution period has ended require(now > SALE_END_TIME); require(!finished); finished = true; // send the 10% commission to Gimmer's fund wallet uint256 tenPC = tokensSold.div(10); token.mint(fundWallet, tenPC); // finish the minting of the token, so the system allows transfers token.finishMinting(); // transfer ownership of the token contract to the fund wallet, // so it isn't locked to be a child of the crowd sale contract token.transferOwnership(fundWallet); } function setSaleWeiLimitWithoutKYC(uint256 _newSaleWeiLimitWithoutKYC) public onlyKycManager { require(_newSaleWeiLimitWithoutKYC > 0); saleWeiLimitWithoutKYC = _newSaleWeiLimitWithoutKYC; } /** * @dev Updates the maximum allowed transaction cost that can be received * on the buyTokens() function. * @param _newMaxTxGas The new maximum transaction cost */ function updateMaxTxGas(uint256 _newMaxTxGas) public onlyKycManager { require(_newMaxTxGas > 0); maxTxGas = _newMaxTxGas; } /** * @dev Flag an user as known * @param _user The user to flag as known */ function approveUserKYC(address _user) onlyKycManager public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = true; KYC(_user, true); } /** * @dev Flag an user as unknown/disapproved * @param _user The user to flag as unknown / suspecious */ function disapproveUserKYC(address _user) onlyKycManager public { require(_user != address(0)); Supporter storage sup = supportersMap[_user]; sup.hasKYC = false; KYC(_user, false); } /** * @dev Changes the KYC manager to a new address * @param _newKYCManagerWallet The new address that will be managing KYC approval */ function setKYCManager(address _newKYCManagerWallet) onlyOwner public { require(_newKYCManagerWallet != address(0)); kycManagerWallet = _newKYCManagerWallet; } /** * @dev Returns true if any of the token sale stages are currently running * @return A boolean representing the state of this contract */ function isTokenSaleRunning() public constant returns (bool) { return (isPreSaleRunning() || isCrowdSaleRunning()); } /** * @dev Returns true if the presale sale is currently running * @return A boolean representing the state of the presale */ function isPreSaleRunning() public constant returns (bool) { return (now >= PRE_SALE_START_TIME && now < PRE_SALE_END_TIME); } /** * @dev Returns true if the public sale is currently running * @return A boolean representing the state of the crowd sale */ function isCrowdSaleRunning() public constant returns (bool) { return (now >= START_WEEK_1 && now <= SALE_END_TIME); } /** * @dev Returns true if the public sale has ended * @return A boolean representing if we are past the contribution date for this contract */ function hasEnded() public constant returns (bool) { return now > SALE_END_TIME; } /** * @dev Returns true if the pre sale has ended * @return A boolean representing if we are past the pre sale contribution dates */ function hasPreSaleEnded() public constant returns (bool) { return now > PRE_SALE_END_TIME; } /** * @dev Returns if an user has KYC approval or not * @return A boolean representing the user's KYC status */ function userHasKYC(address _user) public constant returns (bool) { return supportersMap[_user].hasKYC; } /** * @dev Returns the weiSpent of a user */ function userWeiSpent(address _user) public constant returns (uint256) { return supportersMap[_user].weiSpent; } <FILL_FUNCTION> /* @return true if the transaction can buy tokens, otherwise false */ function validPurchase() internal constant returns (bool) { bool userHasKyc = userHasKYC(msg.sender); if (isCrowdSaleRunning()) { // crowdsale restrictions (KYC only needed after wei limit, minimum of 0.1 ETH tx) if(!userHasKyc) { Supporter storage sup = supportersMap[msg.sender]; uint256 ethContribution = sup.weiSpent.add(msg.value); if (ethContribution > saleWeiLimitWithoutKYC) { return false; } } return msg.value >= MIN_ETHER; } else if (isPreSaleRunning()) { // presale restrictions (at least 30 eth, always KYC) return userHasKyc && msg.value >= PRE_SALE_30_ETH; } else { return false; } } }
if (isCrowdSaleRunning()) { if (now >= START_WEEK_4) { return TOKEN_RATE_05_PERCENT_BONUS; } else if (now >= START_WEEK_3) { return TOKEN_RATE_10_PERCENT_BONUS; } else if (now >= START_WEEK_2) { return TOKEN_RATE_15_PERCENT_BONUS; } else if (now >= START_WEEK_1) { return TOKEN_RATE_20_PERCENT_BONUS; } } else if (isPreSaleRunning()) { if (_weiAmount >= PRE_SALE_1000_ETH) { return TOKEN_RATE_40_PERCENT_BONUS; } else if (_weiAmount >= PRE_SALE_300_ETH) { return TOKEN_RATE_30_PERCENT_BONUS; } else if (_weiAmount >= PRE_SALE_30_ETH) { return TOKEN_RATE_25_PERCENT_BONUS; } }
function getRate(uint256 _weiAmount) internal constant returns (uint256)
/** * @dev Returns the rate the user will be paying at, * based on the amount of Wei sent to the contract, and the current time * @return An uint256 representing the rate the user will pay for the GMR tokens */ function getRate(uint256 _weiAmount) internal constant returns (uint256)
82269
CTSCoin
_transfer
contract CTSCoin is EIP20Interface,Ownable,SafeMath,Pausable{ //// Constant token specific fields string public constant name ="CTSCoin"; string public constant symbol = "CTSC"; uint8 public constant decimals = 18; string public version = 'v0.1'; uint256 public constant initialSupply = 500000000; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; //sum of buy mapping (address => uint) public jail; mapping (address => uint256) public updateTime; //Locked token mapping (address => uint256) public LockedToken; //set raise time uint256 public finaliseTime; //to receive eth from the contract address public walletOwnerAddress; //Tokens to 1 eth uint256 public rate; event WithDraw(address indexed _from, address indexed _to,uint256 _value); event BuyToken(address indexed _from, address indexed _to, uint256 _value); function CTSCoin() public { totalSupply = initialSupply*10**uint256(decimals); // total supply balances[msg.sender] = totalSupply; // Give the creator all initial tokens walletOwnerAddress = msg.sender; rate = 1500; } modifier notFinalised() { require(finaliseTime == 0); _; } function balanceOf(address _account) public view returns (uint) { return balances[_account]; } function _transfer(address _from, address _to, uint _value) internal whenNotPaused returns(bool) {<FILL_FUNCTION_BODY> } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success){ return _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(_value <= allowances[_from][msg.sender]); allowances[_from][msg.sender] = safeSub(allowances[_from][msg.sender],_value); return _transfer(_from, _to, _value); } function approve(address _spender, uint256 _value) public returns (bool success) { allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowances[msg.sender][_spender] = safeAdd(allowances[msg.sender][_spender],_addedValue); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowances[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowances[msg.sender][_spender] = 0; } else { allowances[msg.sender][_spender] = safeSub(oldValue,_subtractedValue); } emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowances[_owner][_spender]; } //close the raise function setFinaliseTime() onlyOwner notFinalised public returns(bool){ finaliseTime = now; rate = 0; return true; } //close the raise function Restart(uint256 newrate) onlyOwner public returns(bool){ finaliseTime = 0; rate = newrate; return true; } function setRate(uint256 newrate) onlyOwner notFinalised public returns(bool) { rate = newrate; return true; } function setWalletOwnerAddress(address _newaddress) onlyOwner public returns(bool) { walletOwnerAddress = _newaddress; return true; } //Withdraw eth form the contranct function withdraw(address _to) internal returns(bool){ require(_to.send(this.balance)); emit WithDraw(msg.sender,_to,this.balance); return true; } //Lock tokens function canTransfer(address _from, uint256 _value) internal view returns (bool success) { uint256 index; uint256 locked; index = safeSub(now, updateTime[_from]) / 1 days; if(index >= 200){ return true; } uint256 releasedtemp = safeMul(index,jail[_from])/200; if(releasedtemp >= LockedToken[_from]){ return true; } locked = safeSub(LockedToken[_from],releasedtemp); require(safeSub(balances[_from], _value) >= locked); return true; } function _buyToken(address _to,uint256 _value)internal notFinalised whenNotPaused{ require(_to != address(0x0)); uint256 index; uint256 locked; if(updateTime[_to] != 0){ index = safeSub(now,updateTime[_to])/1 days; uint256 releasedtemp = safeMul(index,jail[_to])/200; if(releasedtemp >= LockedToken[_to]){ LockedToken[_to] = 0; }else{ LockedToken[_to] = safeSub(LockedToken[_to],releasedtemp); } } locked = safeSub(_value,_value/200); LockedToken[_to] = safeAdd(LockedToken[_to],locked); balances[_to] = safeAdd(balances[_to], _value); jail[_to] = safeAdd(jail[_to], _value); balances[walletOwnerAddress] = safeSub(balances[walletOwnerAddress],_value); updateTime[_to] = now; withdraw(walletOwnerAddress); emit BuyToken(msg.sender, _to, _value); } function() public payable{ require(msg.value >= 0.001 ether); uint256 tokens = safeMul(msg.value,rate); _buyToken(msg.sender,tokens); } }
contract CTSCoin is EIP20Interface,Ownable,SafeMath,Pausable{ //// Constant token specific fields string public constant name ="CTSCoin"; string public constant symbol = "CTSC"; uint8 public constant decimals = 18; string public version = 'v0.1'; uint256 public constant initialSupply = 500000000; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; //sum of buy mapping (address => uint) public jail; mapping (address => uint256) public updateTime; //Locked token mapping (address => uint256) public LockedToken; //set raise time uint256 public finaliseTime; //to receive eth from the contract address public walletOwnerAddress; //Tokens to 1 eth uint256 public rate; event WithDraw(address indexed _from, address indexed _to,uint256 _value); event BuyToken(address indexed _from, address indexed _to, uint256 _value); function CTSCoin() public { totalSupply = initialSupply*10**uint256(decimals); // total supply balances[msg.sender] = totalSupply; // Give the creator all initial tokens walletOwnerAddress = msg.sender; rate = 1500; } modifier notFinalised() { require(finaliseTime == 0); _; } function balanceOf(address _account) public view returns (uint) { return balances[_account]; } <FILL_FUNCTION> function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success){ return _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(_value <= allowances[_from][msg.sender]); allowances[_from][msg.sender] = safeSub(allowances[_from][msg.sender],_value); return _transfer(_from, _to, _value); } function approve(address _spender, uint256 _value) public returns (bool success) { allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowances[msg.sender][_spender] = safeAdd(allowances[msg.sender][_spender],_addedValue); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowances[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowances[msg.sender][_spender] = 0; } else { allowances[msg.sender][_spender] = safeSub(oldValue,_subtractedValue); } emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowances[_owner][_spender]; } //close the raise function setFinaliseTime() onlyOwner notFinalised public returns(bool){ finaliseTime = now; rate = 0; return true; } //close the raise function Restart(uint256 newrate) onlyOwner public returns(bool){ finaliseTime = 0; rate = newrate; return true; } function setRate(uint256 newrate) onlyOwner notFinalised public returns(bool) { rate = newrate; return true; } function setWalletOwnerAddress(address _newaddress) onlyOwner public returns(bool) { walletOwnerAddress = _newaddress; return true; } //Withdraw eth form the contranct function withdraw(address _to) internal returns(bool){ require(_to.send(this.balance)); emit WithDraw(msg.sender,_to,this.balance); return true; } //Lock tokens function canTransfer(address _from, uint256 _value) internal view returns (bool success) { uint256 index; uint256 locked; index = safeSub(now, updateTime[_from]) / 1 days; if(index >= 200){ return true; } uint256 releasedtemp = safeMul(index,jail[_from])/200; if(releasedtemp >= LockedToken[_from]){ return true; } locked = safeSub(LockedToken[_from],releasedtemp); require(safeSub(balances[_from], _value) >= locked); return true; } function _buyToken(address _to,uint256 _value)internal notFinalised whenNotPaused{ require(_to != address(0x0)); uint256 index; uint256 locked; if(updateTime[_to] != 0){ index = safeSub(now,updateTime[_to])/1 days; uint256 releasedtemp = safeMul(index,jail[_to])/200; if(releasedtemp >= LockedToken[_to]){ LockedToken[_to] = 0; }else{ LockedToken[_to] = safeSub(LockedToken[_to],releasedtemp); } } locked = safeSub(_value,_value/200); LockedToken[_to] = safeAdd(LockedToken[_to],locked); balances[_to] = safeAdd(balances[_to], _value); jail[_to] = safeAdd(jail[_to], _value); balances[walletOwnerAddress] = safeSub(balances[walletOwnerAddress],_value); updateTime[_to] = now; withdraw(walletOwnerAddress); emit BuyToken(msg.sender, _to, _value); } function() public payable{ require(msg.value >= 0.001 ether); uint256 tokens = safeMul(msg.value,rate); _buyToken(msg.sender,tokens); } }
require(_to != address(0x0)&&_value>0); require (canTransfer(_from, _value)); require(balances[_from] >= _value); require(safeAdd(balances[_to],_value) > balances[_to]); uint previousBalances = safeAdd(balances[_from],balances[_to]); balances[_from] = safeSub(balances[_from],_value); balances[_to] = safeAdd(balances[_to],_value); emit Transfer(_from, _to, _value); assert(safeAdd(balances[_from],balances[_to]) == previousBalances); return true;
function _transfer(address _from, address _to, uint _value) internal whenNotPaused returns(bool)
function _transfer(address _from, address _to, uint _value) internal whenNotPaused returns(bool)
19428
TazitToken
transferFrom
contract TazitToken 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 TazitToken() public { symbol = "TZT"; name = "Tazit"; decimals = 6; _totalSupply = 1000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _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); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } 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; emit 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); } }
contract TazitToken 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 TazitToken() public { symbol = "TZT"; name = "Tazit"; decimals = 6; _totalSupply = 1000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _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); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } <FILL_FUNCTION> 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; emit 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); } }
balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public returns (bool success)
function transferFrom(address from, address to, uint tokens) public returns (bool success)
9566
BSHORT
pauseCrowdSale
contract BSHORT is ERC20Detailed { using SafeMath for uint256; bool public isPaused = false; uint256 private DEC = 1000000000000000000; address public tradeAddress; // how many ETH cost 1000 BSHORT. rate = 1000 BSHORT/ETH. It's always an integer! // formula for rate: rate = 1000 * (BSHORT in USD) / (ETH in USD) uint256 public rate = 10; uint public minimumSupply = 1; uint public hardCap = 9000000000 * DEC; event TokenPurchase(address purchaser, uint256 value, uint256 amount, uint integer_amount, uint256 tokensMinted); event TokenIssue(address purchaser, uint256 amount, uint integer_amount, uint256 tokensMinted); modifier onlyTrade() { require(msg.sender == tradeAddress); _; } function pauseCrowdSale() public onlyOwner {<FILL_FUNCTION_BODY> } function startCrowdSale() public onlyOwner { require(isPaused == true); isPaused = false; } function setRate(uint _rate) public onlyOwner { require(_rate > 0); require(_rate <= 1000); rate = _rate; } function buyTokens() public payable { require(!isPaused); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(1000).div(rate); require(tokens >= minimumSupply * DEC); require(totalSupply().add(tokens) <= hardCap); _mint(msg.sender, tokens); owner().transfer(msg.value); emit TokenPurchase(msg.sender, weiAmount, tokens, tokens.div(DEC), totalSupply().div(DEC)); } function IssueTokens(address account, uint256 value) public onlyOwner { uint tokens = value * DEC; require(totalSupply().add(tokens) <= hardCap); _mint(account, tokens); emit TokenIssue(account, tokens, value, totalSupply().div(DEC)); } function() external payable { buyTokens(); } function setTradeAddress(address _tradeAddress) public onlyOwner { require(_tradeAddress != address(0)); tradeAddress = _tradeAddress; } function transferTrade(address _from, address _to, uint256 _value) onlyTrade public returns (bool) { _transfer(_from, _to, _value); return true; } function transfer(address _to, uint256 _value) public returns (bool) { if (_to == tradeAddress) { ITrade(tradeAddress).contractBuyTokensFrom(msg.sender, _value); } else { _transfer(msg.sender, _to, _value); } return true; } }
contract BSHORT is ERC20Detailed { using SafeMath for uint256; bool public isPaused = false; uint256 private DEC = 1000000000000000000; address public tradeAddress; // how many ETH cost 1000 BSHORT. rate = 1000 BSHORT/ETH. It's always an integer! // formula for rate: rate = 1000 * (BSHORT in USD) / (ETH in USD) uint256 public rate = 10; uint public minimumSupply = 1; uint public hardCap = 9000000000 * DEC; event TokenPurchase(address purchaser, uint256 value, uint256 amount, uint integer_amount, uint256 tokensMinted); event TokenIssue(address purchaser, uint256 amount, uint integer_amount, uint256 tokensMinted); modifier onlyTrade() { require(msg.sender == tradeAddress); _; } <FILL_FUNCTION> function startCrowdSale() public onlyOwner { require(isPaused == true); isPaused = false; } function setRate(uint _rate) public onlyOwner { require(_rate > 0); require(_rate <= 1000); rate = _rate; } function buyTokens() public payable { require(!isPaused); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(1000).div(rate); require(tokens >= minimumSupply * DEC); require(totalSupply().add(tokens) <= hardCap); _mint(msg.sender, tokens); owner().transfer(msg.value); emit TokenPurchase(msg.sender, weiAmount, tokens, tokens.div(DEC), totalSupply().div(DEC)); } function IssueTokens(address account, uint256 value) public onlyOwner { uint tokens = value * DEC; require(totalSupply().add(tokens) <= hardCap); _mint(account, tokens); emit TokenIssue(account, tokens, value, totalSupply().div(DEC)); } function() external payable { buyTokens(); } function setTradeAddress(address _tradeAddress) public onlyOwner { require(_tradeAddress != address(0)); tradeAddress = _tradeAddress; } function transferTrade(address _from, address _to, uint256 _value) onlyTrade public returns (bool) { _transfer(_from, _to, _value); return true; } function transfer(address _to, uint256 _value) public returns (bool) { if (_to == tradeAddress) { ITrade(tradeAddress).contractBuyTokensFrom(msg.sender, _value); } else { _transfer(msg.sender, _to, _value); } return true; } }
require(isPaused == false); isPaused = true;
function pauseCrowdSale() public onlyOwner
function pauseCrowdSale() public onlyOwner
92007
StandardToken
transferFrom
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(0)); 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) { require(_spender != address(0)); 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) { require(_spender != address(0)); 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 StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; <FILL_FUNCTION> function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(0)); 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) { require(_spender != address(0)); 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) { require(_spender != address(0)); 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; } }
require(_to != address(0)); require(_from != 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 transferFrom(address _from, address _to, uint256 _value) public returns (bool)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
89461
UpgradeabilityProxy
null
contract UpgradeabilityProxy is Proxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable {<FILL_FUNCTION_BODY> } /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
contract UpgradeabilityProxy is Proxy { <FILL_FUNCTION> /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); }
constructor(address _logic, bytes memory _data) public payable
/** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable
46325
Controlled
Controlled
contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } //block for check//bool private initialed = false; address public controller; function Controlled() public {<FILL_FUNCTION_BODY> } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } }
contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } //block for check//bool private initialed = false; address public controller; <FILL_FUNCTION> /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } }
//block for check//require(!initialed); controller = msg.sender; //block for check//initialed = true;
function Controlled() public
function Controlled() public
9721
FieldCoin
addBlacklistAddress
contract FieldCoin is MintableToken, BurnableToken{ using SafeMath for uint256; //name of token string public name; //token symbol string public symbol; //decimals in token uint8 public decimals; //address of bounty wallet address public bountyWallet; //address of team wallet address public teamWallet; //flag to set token release true=> token is ready for transfer bool public transferEnabled; //token available for offering uint256 public TOKEN_OFFERING_ALLOWANCE = 770e6 * 10 **18;//770 million(sale+bonus) // Address of token offering address public tokenOfferingAddr; //address to collect tokens when land is transferred address public landCollectorAddr; mapping(address => bool) public transferAgents; //mapping for blacklisted address mapping(address => bool) private blacklist; /** * Check if transfer is allowed * * Permissions: * Owner OffeirngContract Others * transfer (before transferEnabled is true) y n n * transferFrom (before transferEnabled is true) y y y * transfer/transferFrom after transferEnabled is true y n y */ modifier canTransfer(address sender) { require(transferEnabled || transferAgents[sender], "transfer is not enabled or sender is not allowed"); _; } /** * Check if token offering address is set or not */ modifier onlyTokenOfferingAddrNotSet() { require(tokenOfferingAddr == address(0x0), "token offering address is already set"); _; } /** * Check if land collector address is set or not */ modifier onlyWhenLandCollectporAddressIsSet() { require(landCollectorAddr != address(0x0), "land collector address is not set"); _; } /** * Check if address is a valid destination to transfer tokens to * - must not be zero address * - must not be the token address * - must not be the owner's address * - must not be the token offering contract address */ modifier validDestination(address to) { require(to != address(0x0), "receiver can't be zero address"); require(to != address(this), "receiver can't be token address"); require(to != owner, "receiver can't be owner"); require(to != address(tokenOfferingAddr), "receiver can't be token offering address"); _; } /** * @dev Constuctor of the contract * */ constructor () public { name = "Fieldcoin"; symbol = "FLC"; decimals = 18; totalSupply_ = 1000e6 * 10 ** uint256(decimals); //1000 million owner = msg.sender; balances[owner] = totalSupply_; } /** * @dev set bounty wallet * @param _bountyWallet address of bounty wallet. * */ function setBountyWallet (address _bountyWallet) public onlyOwner returns (bool) { require(_bountyWallet != address(0x0), "bounty address can't be zero"); if(bountyWallet == address(0x0)){ bountyWallet = _bountyWallet; balances[bountyWallet] = 20e6 * 10 ** uint256(decimals); //20 million balances[owner] = balances[owner].sub(20e6 * 10 ** uint256(decimals)); }else{ address oldBountyWallet = bountyWallet; bountyWallet = _bountyWallet; balances[bountyWallet] = balances[oldBountyWallet]; } return true; } /** * @dev set team wallet * @param _teamWallet address of bounty wallet. * */ function setTeamWallet (address _teamWallet) public onlyOwner returns (bool) { require(_teamWallet != address(0x0), "team address can't be zero"); if(teamWallet == address(0x0)){ teamWallet = _teamWallet; balances[teamWallet] = 90e6 * 10 ** uint256(decimals); //90 million balances[owner] = balances[owner].sub(90e6 * 10 ** uint256(decimals)); }else{ address oldTeamWallet = teamWallet; teamWallet = _teamWallet; balances[teamWallet] = balances[oldTeamWallet]; } return true; } /** * @dev transfer token to a specified address (written due to backward compatibility) * @param to address to which token is transferred * @param value amount of tokens to transfer * return bool true=> transfer is succesful */ function transfer(address to, uint256 value) canTransfer(msg.sender) validDestination(to) public returns (bool) { return super.transfer(to, value); } /** * @dev Transfer tokens from one address to another * @param from address from which token is transferred * @param to address to which token is transferred * @param value amount of tokens to transfer * @return bool true=> transfer is succesful */ function transferFrom(address from, address to, uint256 value) canTransfer(msg.sender) validDestination(to) public returns (bool) { return super.transferFrom(from, to, value); } /** * @dev add addresses to the blacklist * @return true if address was added to the blacklist, * false if address were already in the blacklist */ function addBlacklistAddress(address addr) public onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Set token offering to approve allowance for offering contract to distribute tokens * * @param offeringAddr Address of token offerng contract i.e., fieldcoinsale contract * @param amountForSale Amount of tokens for sale, set 0 to max out */ function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet { require (offeringAddr != address(0x0), "offering address can't be zero"); require(!transferEnabled, "transfer should be diabled"); uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale; require(amount <= TOKEN_OFFERING_ALLOWANCE); approve(offeringAddr, amount); tokenOfferingAddr = offeringAddr; //start the transfer for offeringAddr setTransferAgent(tokenOfferingAddr, true); } /** * @dev set land collector address * */ function setLandCollector(address collectorAddr) public onlyOwner { require (collectorAddr != address(0x0), "land collecting address can't be set to zero"); require(!transferEnabled, "transfer should be diabled"); landCollectorAddr = collectorAddr; } /** * @dev release tokens for transfer * */ function enableTransfer() public onlyOwner { transferEnabled = true; // End the offering approve(tokenOfferingAddr, 0); //stop the transfer for offeringAddr setTransferAgent(tokenOfferingAddr, false); } /** * @dev Set transfer agent to true for transfer tokens for private investor and exchange * @param _addr who will be allowd for transfer * @param _allowTransfer true=>allowed * */ function setTransferAgent(address _addr, bool _allowTransfer) public onlyOwner { transferAgents[_addr] = _allowTransfer; } /** * @dev withdraw if KYC not verified * @param _investor investor whose tokens are to be withdrawn * @param _tokens amount of tokens to be withdrawn */ function _withdraw(address _investor, uint256 _tokens) external{ require (msg.sender == tokenOfferingAddr, "sender must be offering address"); require (isBlacklisted(_investor), "address is not whitelisted"); balances[owner] = balances[owner].add(_tokens); balances[_investor] = balances[_investor].sub(_tokens); balances[_investor] = 0; } /** * @dev buy land during ICO * @param _investor investor whose tokens are to be transferred * @param _tokens amount of tokens to be transferred */ function _buyLand(address _investor, uint256 _tokens) external onlyWhenLandCollectporAddressIsSet{ require (!transferEnabled, "transfer should be diabled"); require (msg.sender == tokenOfferingAddr, "sender must be offering address"); balances[landCollectorAddr] = balances[landCollectorAddr].add(_tokens); balances[_investor] = balances[_investor].sub(_tokens); } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(transferEnabled || msg.sender == owner, "transfer is not enabled or sender is not owner"); super.burn(_value); } /** * @dev check address is blacklisted or not * @param _addr who will be checked * @return true=> if blacklisted, false=> if not * */ function isBlacklisted(address _addr) public view returns(bool){ return blacklist[_addr]; } }
contract FieldCoin is MintableToken, BurnableToken{ using SafeMath for uint256; //name of token string public name; //token symbol string public symbol; //decimals in token uint8 public decimals; //address of bounty wallet address public bountyWallet; //address of team wallet address public teamWallet; //flag to set token release true=> token is ready for transfer bool public transferEnabled; //token available for offering uint256 public TOKEN_OFFERING_ALLOWANCE = 770e6 * 10 **18;//770 million(sale+bonus) // Address of token offering address public tokenOfferingAddr; //address to collect tokens when land is transferred address public landCollectorAddr; mapping(address => bool) public transferAgents; //mapping for blacklisted address mapping(address => bool) private blacklist; /** * Check if transfer is allowed * * Permissions: * Owner OffeirngContract Others * transfer (before transferEnabled is true) y n n * transferFrom (before transferEnabled is true) y y y * transfer/transferFrom after transferEnabled is true y n y */ modifier canTransfer(address sender) { require(transferEnabled || transferAgents[sender], "transfer is not enabled or sender is not allowed"); _; } /** * Check if token offering address is set or not */ modifier onlyTokenOfferingAddrNotSet() { require(tokenOfferingAddr == address(0x0), "token offering address is already set"); _; } /** * Check if land collector address is set or not */ modifier onlyWhenLandCollectporAddressIsSet() { require(landCollectorAddr != address(0x0), "land collector address is not set"); _; } /** * Check if address is a valid destination to transfer tokens to * - must not be zero address * - must not be the token address * - must not be the owner's address * - must not be the token offering contract address */ modifier validDestination(address to) { require(to != address(0x0), "receiver can't be zero address"); require(to != address(this), "receiver can't be token address"); require(to != owner, "receiver can't be owner"); require(to != address(tokenOfferingAddr), "receiver can't be token offering address"); _; } /** * @dev Constuctor of the contract * */ constructor () public { name = "Fieldcoin"; symbol = "FLC"; decimals = 18; totalSupply_ = 1000e6 * 10 ** uint256(decimals); //1000 million owner = msg.sender; balances[owner] = totalSupply_; } /** * @dev set bounty wallet * @param _bountyWallet address of bounty wallet. * */ function setBountyWallet (address _bountyWallet) public onlyOwner returns (bool) { require(_bountyWallet != address(0x0), "bounty address can't be zero"); if(bountyWallet == address(0x0)){ bountyWallet = _bountyWallet; balances[bountyWallet] = 20e6 * 10 ** uint256(decimals); //20 million balances[owner] = balances[owner].sub(20e6 * 10 ** uint256(decimals)); }else{ address oldBountyWallet = bountyWallet; bountyWallet = _bountyWallet; balances[bountyWallet] = balances[oldBountyWallet]; } return true; } /** * @dev set team wallet * @param _teamWallet address of bounty wallet. * */ function setTeamWallet (address _teamWallet) public onlyOwner returns (bool) { require(_teamWallet != address(0x0), "team address can't be zero"); if(teamWallet == address(0x0)){ teamWallet = _teamWallet; balances[teamWallet] = 90e6 * 10 ** uint256(decimals); //90 million balances[owner] = balances[owner].sub(90e6 * 10 ** uint256(decimals)); }else{ address oldTeamWallet = teamWallet; teamWallet = _teamWallet; balances[teamWallet] = balances[oldTeamWallet]; } return true; } /** * @dev transfer token to a specified address (written due to backward compatibility) * @param to address to which token is transferred * @param value amount of tokens to transfer * return bool true=> transfer is succesful */ function transfer(address to, uint256 value) canTransfer(msg.sender) validDestination(to) public returns (bool) { return super.transfer(to, value); } /** * @dev Transfer tokens from one address to another * @param from address from which token is transferred * @param to address to which token is transferred * @param value amount of tokens to transfer * @return bool true=> transfer is succesful */ function transferFrom(address from, address to, uint256 value) canTransfer(msg.sender) validDestination(to) public returns (bool) { return super.transferFrom(from, to, value); } <FILL_FUNCTION> /** * @dev Set token offering to approve allowance for offering contract to distribute tokens * * @param offeringAddr Address of token offerng contract i.e., fieldcoinsale contract * @param amountForSale Amount of tokens for sale, set 0 to max out */ function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet { require (offeringAddr != address(0x0), "offering address can't be zero"); require(!transferEnabled, "transfer should be diabled"); uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale; require(amount <= TOKEN_OFFERING_ALLOWANCE); approve(offeringAddr, amount); tokenOfferingAddr = offeringAddr; //start the transfer for offeringAddr setTransferAgent(tokenOfferingAddr, true); } /** * @dev set land collector address * */ function setLandCollector(address collectorAddr) public onlyOwner { require (collectorAddr != address(0x0), "land collecting address can't be set to zero"); require(!transferEnabled, "transfer should be diabled"); landCollectorAddr = collectorAddr; } /** * @dev release tokens for transfer * */ function enableTransfer() public onlyOwner { transferEnabled = true; // End the offering approve(tokenOfferingAddr, 0); //stop the transfer for offeringAddr setTransferAgent(tokenOfferingAddr, false); } /** * @dev Set transfer agent to true for transfer tokens for private investor and exchange * @param _addr who will be allowd for transfer * @param _allowTransfer true=>allowed * */ function setTransferAgent(address _addr, bool _allowTransfer) public onlyOwner { transferAgents[_addr] = _allowTransfer; } /** * @dev withdraw if KYC not verified * @param _investor investor whose tokens are to be withdrawn * @param _tokens amount of tokens to be withdrawn */ function _withdraw(address _investor, uint256 _tokens) external{ require (msg.sender == tokenOfferingAddr, "sender must be offering address"); require (isBlacklisted(_investor), "address is not whitelisted"); balances[owner] = balances[owner].add(_tokens); balances[_investor] = balances[_investor].sub(_tokens); balances[_investor] = 0; } /** * @dev buy land during ICO * @param _investor investor whose tokens are to be transferred * @param _tokens amount of tokens to be transferred */ function _buyLand(address _investor, uint256 _tokens) external onlyWhenLandCollectporAddressIsSet{ require (!transferEnabled, "transfer should be diabled"); require (msg.sender == tokenOfferingAddr, "sender must be offering address"); balances[landCollectorAddr] = balances[landCollectorAddr].add(_tokens); balances[_investor] = balances[_investor].sub(_tokens); } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(transferEnabled || msg.sender == owner, "transfer is not enabled or sender is not owner"); super.burn(_value); } /** * @dev check address is blacklisted or not * @param _addr who will be checked * @return true=> if blacklisted, false=> if not * */ function isBlacklisted(address _addr) public view returns(bool){ return blacklist[_addr]; } }
require(!isBlacklisted(addr), "address is already blacklisted"); require(addr != address(0x0), "blacklisting address can't be zero"); // blacklisted so they can withdraw blacklist[addr] = true;
function addBlacklistAddress(address addr) public onlyOwner
/** * @dev add addresses to the blacklist * @return true if address was added to the blacklist, * false if address were already in the blacklist */ function addBlacklistAddress(address addr) public onlyOwner
62471
SamsungSale
SamsungSale
contract SamsungSale is Ownable { using SafeMath for uint; address multisig; uint restrictedPercent; address restricted; SamsungToken public token = new SamsungToken(); uint start; uint period; uint hardcap; uint public rate; function SamsungSale() {<FILL_FUNCTION_BODY> } // modifier saleIsOn() { require(now > start && now < start + period * 1 days); _; } // modifier isUnderHardCap() { require(token.totalSupply() <= hardcap); _; } // function setRate(uint _rate) onlyOwner { rate = _rate; } // function finishMinting() onlyOwner { uint issuedTokenSupply = token.totalSupply(); uint restrictedTokens = issuedTokenSupply.mul(restrictedPercent).div(100 - restrictedPercent); token.mint(restricted, restrictedTokens); token.finishMinting(); } // function createTokens() isUnderHardCap saleIsOn payable { multisig.transfer(msg.value); uint tokens = rate.mul(msg.value).div(1 ether); token.mint(msg.sender, tokens); } function() external payable { createTokens(); } }
contract SamsungSale is Ownable { using SafeMath for uint; address multisig; uint restrictedPercent; address restricted; SamsungToken public token = new SamsungToken(); uint start; uint period; uint hardcap; uint public rate; <FILL_FUNCTION> // modifier saleIsOn() { require(now > start && now < start + period * 1 days); _; } // modifier isUnderHardCap() { require(token.totalSupply() <= hardcap); _; } // function setRate(uint _rate) onlyOwner { rate = _rate; } // function finishMinting() onlyOwner { uint issuedTokenSupply = token.totalSupply(); uint restrictedTokens = issuedTokenSupply.mul(restrictedPercent).div(100 - restrictedPercent); token.mint(restricted, restrictedTokens); token.finishMinting(); } // function createTokens() isUnderHardCap saleIsOn payable { multisig.transfer(msg.value); uint tokens = rate.mul(msg.value).div(1 ether); token.mint(msg.sender, tokens); } function() external payable { createTokens(); } }
// multisig = 0x1916615552a7AF269E7e78CBA94244BfEfA199c8; // restricted = 0x1916615552a7AF269E7e78CBA94244BfEfA199c8; // restrictedPercent = 0; // rate = 100000000*(1000000000000000000); // start = 1506399914; //09/26/2017 period = 64; // hardcap = 9500000*(1000000000000000000);
function SamsungSale()
function SamsungSale()
1120
NUTScoin
approveAndCall
contract NUTScoin is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function NUTScoin() { balances[msg.sender] = 115000000000000000000000000000000000000000000000000000000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 115000000000000000000000000000000000000000000000000000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "NUTScoin"; // Set the name for display purposes (CHANGE THIS) decimals = 0; // Amount of decimals for display purposes (CHANGE THIS) symbol = "NUTS"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 1000000000000000000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract NUTScoin is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function NUTScoin() { balances[msg.sender] = 115000000000000000000000000000000000000000000000000000000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 115000000000000000000000000000000000000000000000000000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "NUTScoin"; // Set the name for display purposes (CHANGE THIS) decimals = 0; // Amount of decimals for display purposes (CHANGE THIS) symbol = "NUTS"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 1000000000000000000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } <FILL_FUNCTION> }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
/* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
11865
EthereumPot
__callback
contract EthereumPot is usingOraclize { address public owner; address[] public addresses; address public winnerAddress; mapping(address => uint) public balances; uint[] public slots; uint minBetSize = 0.01 ether; uint public potSize = 0; uint public amountWon; uint public potTime = 300; uint public endTime = now + potTime; uint public totalBet = 0; uint public random_number; bool public locked = false; event debug(string msg); event debugInt(uint random); event potSizeChanged( uint _potSize ); event winnerAnnounced( address winner, uint amount ); event timeLeft(uint left); function EthereumPot() public { oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof in the constructor owner = msg.sender; } function getBalance(address addr) constant returns(uint balance) { return balances[addr]; } //allows users to withdraw balance function withdrawBalance() payable public { if(balances[msg.sender] > 0) { uint balance = balances[msg.sender]; balances[msg.sender] = 0; if(!msg.sender.send(balance)) { balances[msg.sender] += balance; } } } function __callback(bytes32 _queryId, string _result, bytes _proof) oraclize_randomDS_proofVerify(_queryId, _result, _proof) {<FILL_FUNCTION_BODY> } function update() internal{ uint delay = 0; // number of seconds to wait before the execution takes place bytes32 queryId = oraclize_newRandomDSQuery(delay, 10, 400000); queryId = queryId;// this function internally generates the correct oraclize_query and returns its queryId } function findWinner(uint random) constant returns (address winner) { for(uint i = 0; i < slots.length; i++) { if(random <= slots[i]) { return addresses[i]; } } } function joinPot() public payable { if(now > endTime) throw; if(locked) throw; uint tickets = 0; for(uint i = msg.value; i >= minBetSize; i-= minBetSize) { tickets++; } if(tickets > 0) { addresses.push(msg.sender); slots.push(potSize += tickets); totalBet+= tickets; potSizeChanged(potSize); timeLeft(endTime - now); } } function getPlayers() constant public returns(address[]) { return addresses; } function getSlots() constant public returns(uint[]) { return slots; } function getEndTime() constant public returns (uint) { return endTime; } function openPot() internal { potSize = 0; endTime = now + potTime; timeLeft(endTime - now); delete slots; delete addresses; locked = false; } function rewardWinner() public payable { //assert time & locked state if(now < endTime) throw; //allow for a retry after potTime seconds if(locked && now < (endTime + potTime)) throw; locked = true; if(potSize > 0) { //if only 1 person bet, wait until they've been challenged if(addresses.length == 1) { endTime = now + potTime; timeLeft(endTime - now); locked = false; } else { update(); } } else { winnerAnnounced(0x0000000000000000000000000000000000000000, 0); openPot(); } } }
contract EthereumPot is usingOraclize { address public owner; address[] public addresses; address public winnerAddress; mapping(address => uint) public balances; uint[] public slots; uint minBetSize = 0.01 ether; uint public potSize = 0; uint public amountWon; uint public potTime = 300; uint public endTime = now + potTime; uint public totalBet = 0; uint public random_number; bool public locked = false; event debug(string msg); event debugInt(uint random); event potSizeChanged( uint _potSize ); event winnerAnnounced( address winner, uint amount ); event timeLeft(uint left); function EthereumPot() public { oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof in the constructor owner = msg.sender; } function getBalance(address addr) constant returns(uint balance) { return balances[addr]; } //allows users to withdraw balance function withdrawBalance() payable public { if(balances[msg.sender] > 0) { uint balance = balances[msg.sender]; balances[msg.sender] = 0; if(!msg.sender.send(balance)) { balances[msg.sender] += balance; } } } <FILL_FUNCTION> function update() internal{ uint delay = 0; // number of seconds to wait before the execution takes place bytes32 queryId = oraclize_newRandomDSQuery(delay, 10, 400000); queryId = queryId;// this function internally generates the correct oraclize_query and returns its queryId } function findWinner(uint random) constant returns (address winner) { for(uint i = 0; i < slots.length; i++) { if(random <= slots[i]) { return addresses[i]; } } } function joinPot() public payable { if(now > endTime) throw; if(locked) throw; uint tickets = 0; for(uint i = msg.value; i >= minBetSize; i-= minBetSize) { tickets++; } if(tickets > 0) { addresses.push(msg.sender); slots.push(potSize += tickets); totalBet+= tickets; potSizeChanged(potSize); timeLeft(endTime - now); } } function getPlayers() constant public returns(address[]) { return addresses; } function getSlots() constant public returns(uint[]) { return slots; } function getEndTime() constant public returns (uint) { return endTime; } function openPot() internal { potSize = 0; endTime = now + potTime; timeLeft(endTime - now); delete slots; delete addresses; locked = false; } function rewardWinner() public payable { //assert time & locked state if(now < endTime) throw; //allow for a retry after potTime seconds if(locked && now < (endTime + potTime)) throw; locked = true; if(potSize > 0) { //if only 1 person bet, wait until they've been challenged if(addresses.length == 1) { endTime = now + potTime; timeLeft(endTime - now); locked = false; } else { update(); } } else { winnerAnnounced(0x0000000000000000000000000000000000000000, 0); openPot(); } } }
// if we reach this point successfully, it means that the attached authenticity proof has passed! if(msg.sender != oraclize_cbAddress()) throw; // generate a random number between potSize(number of tickets sold) and 1 random_number = uint(sha3(_result))%potSize + 1; // find that winner based on the random number generated winnerAddress = findWinner(random_number); // winner wins 98% of the remaining balance after oraclize fees uint total = potSize * minBetSize - 400000;//less oraclize fee amountWon = total * 98 / 100 ; uint fee = total - amountWon; balances[winnerAddress] += amountWon; balances[owner] += fee; // announce winner winnerAnnounced(winnerAddress, amountWon); openPot();
function __callback(bytes32 _queryId, string _result, bytes _proof) oraclize_randomDS_proofVerify(_queryId, _result, _proof)
function __callback(bytes32 _queryId, string _result, bytes _proof) oraclize_randomDS_proofVerify(_queryId, _result, _proof)
23783
SafeMath
mulSafe
contract SafeMath { function mulSafe(uint256 a, uint256 b) internal pure returns (uint256) {<FILL_FUNCTION_BODY> } function divSafe(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function subSafe(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function addSafe(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
contract SafeMath { <FILL_FUNCTION> function divSafe(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function subSafe(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function addSafe(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c;
function mulSafe(uint256 a, uint256 b) internal pure returns (uint256)
function mulSafe(uint256 a, uint256 b) internal pure returns (uint256)
52660
ChainLinkFeedsRegistry
getPriceETH
contract ChainLinkFeedsRegistry { using SafeMath for uint; mapping(address => address) public assetsUSD; mapping(address => address) public assetsETH; address constant public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public governance; constructor () public { governance = msg.sender; assetsUSD[weth] = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; // WETH assetsUSD[0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599] = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; // wBTC assetsUSD[0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D] = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; // renBTC assetsUSD[0x6B175474E89094C44Da98b954EedeAC495271d0F] = 0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9; // DAI assetsUSD[0x514910771AF9Ca656af840dff83E8264EcF986CA] = 0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c; // LINK assetsUSD[0x408e41876cCCDC0F92210600ef50372656052a38] = 0x0f59666EDE214281e956cb3b2D0d69415AfF4A01; // REN assetsUSD[0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F] = 0xDC3EA94CD0AC27d9A86C180091e7f78C683d3699; // SNX assetsETH[0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599] = 0xdeb288F737066589598e9214E782fa5A8eD689e8; // wBTC assetsETH[0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D] = 0xdeb288F737066589598e9214E782fa5A8eD689e8; // renBTC assetsETH[0x6B175474E89094C44Da98b954EedeAC495271d0F] = 0x773616E4d11A78F511299002da57A0a94577F1f4; // DAI assetsETH[0x514910771AF9Ca656af840dff83E8264EcF986CA] = 0xDC530D9457755926550b59e8ECcdaE7624181557; // LINK assetsETH[0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2] = 0x24551a8Fb2A7211A25a17B1481f043A8a8adC7f2; // MKR assetsETH[0x408e41876cCCDC0F92210600ef50372656052a38] = 0x3147D7203354Dc06D9fd350c7a2437bcA92387a4; // REN assetsETH[0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F] = 0x79291A9d692Df95334B1a0B3B4AE6bC606782f8c; // SNX assetsETH[0x57Ab1ec28D129707052df4dF418D58a2D46d5f51] = 0x8e0b7e6062272B5eF4524250bFFF8e5Bd3497757; // SUSD assetsETH[0x0000000000085d4780B73119b644AE5ecd22b376] = 0x3886BA987236181D98F2401c507Fb8BeA7871dF2; // TUSD assetsETH[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48] = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4; // USDC assetsETH[0xdAC17F958D2ee523a2206206994597C13D831ec7] = 0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46; // USDT assetsETH[0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e] = 0xB7B1C8F4095D819BDAE25e7a63393CDF21fd02Ea; // YFI } // Returns 1e8 function getPriceUSD(address _asset) external view returns(uint256) { uint256 _price = 0; if (assetsUSD[_asset] != address(0)) { _price = Oracle(assetsUSD[_asset]).latestAnswer(); } else if (assetsETH[_asset] != address(0)) { _price = Oracle(assetsETH[_asset]).latestAnswer(); _price = _price.mul(Oracle(assetsUSD[weth]).latestAnswer()).div(1e18); } return _price; } // Returns 1e18 function getPriceETH(address _asset) external view returns(uint256) {<FILL_FUNCTION_BODY> } function addFeedETH(address _asset, address _feed) external { require(msg.sender == governance, "!governance"); assetsETH[_asset] = _feed; } function addFeedUSD(address _asset, address _feed) external { require(msg.sender == governance, "!governance"); assetsUSD[_asset] = _feed; } function removeFeedETH(address _asset) external { require(msg.sender == governance, "!governance"); assetsETH[_asset] = address(0); } function removeFeedUSD(address _asset) external { require(msg.sender == governance, "!governance"); assetsUSD[_asset] = address(0); } }
contract ChainLinkFeedsRegistry { using SafeMath for uint; mapping(address => address) public assetsUSD; mapping(address => address) public assetsETH; address constant public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public governance; constructor () public { governance = msg.sender; assetsUSD[weth] = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; // WETH assetsUSD[0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599] = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; // wBTC assetsUSD[0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D] = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; // renBTC assetsUSD[0x6B175474E89094C44Da98b954EedeAC495271d0F] = 0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9; // DAI assetsUSD[0x514910771AF9Ca656af840dff83E8264EcF986CA] = 0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c; // LINK assetsUSD[0x408e41876cCCDC0F92210600ef50372656052a38] = 0x0f59666EDE214281e956cb3b2D0d69415AfF4A01; // REN assetsUSD[0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F] = 0xDC3EA94CD0AC27d9A86C180091e7f78C683d3699; // SNX assetsETH[0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599] = 0xdeb288F737066589598e9214E782fa5A8eD689e8; // wBTC assetsETH[0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D] = 0xdeb288F737066589598e9214E782fa5A8eD689e8; // renBTC assetsETH[0x6B175474E89094C44Da98b954EedeAC495271d0F] = 0x773616E4d11A78F511299002da57A0a94577F1f4; // DAI assetsETH[0x514910771AF9Ca656af840dff83E8264EcF986CA] = 0xDC530D9457755926550b59e8ECcdaE7624181557; // LINK assetsETH[0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2] = 0x24551a8Fb2A7211A25a17B1481f043A8a8adC7f2; // MKR assetsETH[0x408e41876cCCDC0F92210600ef50372656052a38] = 0x3147D7203354Dc06D9fd350c7a2437bcA92387a4; // REN assetsETH[0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F] = 0x79291A9d692Df95334B1a0B3B4AE6bC606782f8c; // SNX assetsETH[0x57Ab1ec28D129707052df4dF418D58a2D46d5f51] = 0x8e0b7e6062272B5eF4524250bFFF8e5Bd3497757; // SUSD assetsETH[0x0000000000085d4780B73119b644AE5ecd22b376] = 0x3886BA987236181D98F2401c507Fb8BeA7871dF2; // TUSD assetsETH[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48] = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4; // USDC assetsETH[0xdAC17F958D2ee523a2206206994597C13D831ec7] = 0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46; // USDT assetsETH[0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e] = 0xB7B1C8F4095D819BDAE25e7a63393CDF21fd02Ea; // YFI } // Returns 1e8 function getPriceUSD(address _asset) external view returns(uint256) { uint256 _price = 0; if (assetsUSD[_asset] != address(0)) { _price = Oracle(assetsUSD[_asset]).latestAnswer(); } else if (assetsETH[_asset] != address(0)) { _price = Oracle(assetsETH[_asset]).latestAnswer(); _price = _price.mul(Oracle(assetsUSD[weth]).latestAnswer()).div(1e18); } return _price; } <FILL_FUNCTION> function addFeedETH(address _asset, address _feed) external { require(msg.sender == governance, "!governance"); assetsETH[_asset] = _feed; } function addFeedUSD(address _asset, address _feed) external { require(msg.sender == governance, "!governance"); assetsUSD[_asset] = _feed; } function removeFeedETH(address _asset) external { require(msg.sender == governance, "!governance"); assetsETH[_asset] = address(0); } function removeFeedUSD(address _asset) external { require(msg.sender == governance, "!governance"); assetsUSD[_asset] = address(0); } }
uint256 _price = 0; if (assetsETH[_asset] != address(0)) { _price = Oracle(assetsETH[_asset]).latestAnswer(); } return _price;
function getPriceETH(address _asset) external view returns(uint256)
// Returns 1e18 function getPriceETH(address _asset) external view returns(uint256)
14179
P2PG
null
contract P2PG is ERC20, ERC20Detailed, ERC20Burnable { constructor() public ERC20Detailed("P2PG", "P2PG0", 8) {<FILL_FUNCTION_BODY> } }
contract P2PG is ERC20, ERC20Detailed, ERC20Burnable { <FILL_FUNCTION> }
_mint(msg.sender, 600_000_000 * 10**8);
constructor() public ERC20Detailed("P2PG", "P2PG0", 8)
constructor() public ERC20Detailed("P2PG", "P2PG0", 8)
17701
SamsungPayNetwork
burn
contract SamsungPayNetwork is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public Claimed; string public constant name = "Samsung Pay Network"; string public constant symbol = "SPN"; uint public constant decimals = 8; uint public deadline = now + 80 * 1 days; uint public round2 = now + 35 * 1 days; uint public round1 = now + 45 * 1 days; uint256 public totalSupply = 800000000e8; uint256 public totalDistributed; uint256 public constant requestMinimum = 1 ether / 100; // 0.01 Ether uint256 public tokensPerEth = 100000e8; uint public target0drop = 1; uint public progress0drop = 0; //here u will write your ether address address multisig = 0x746c17F698bcB1150588a3cc7CA7b6C62EE877ed; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); event Add(uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { uint256 teamFund = 80000000e8; owner = msg.sender; distr(owner, teamFund); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function Distribute(address _participant, uint _amount) onlyOwner internal { require( _amount > 0 ); require( totalDistributed < totalSupply ); balances[_participant] = balances[_participant].add(_amount); totalDistributed = totalDistributed.add(_amount); if (totalDistributed >= totalSupply) { distributionFinished = true; } // log emit Airdrop(_participant, _amount, balances[_participant]); emit Transfer(address(0), _participant, _amount); } function DistributeAirdrop(address _participant, uint _amount) onlyOwner external { Distribute(_participant, _amount); } function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external { for (uint i = 0; i < _addresses.length; i++) Distribute(_addresses[i], _amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; uint256 bonus = 0; uint256 countbonus = 0; uint256 bonusCond1 = 5 ether / 100; uint256 bonusCond2 = 1 ether / 10; uint256 bonusCond3 = 5 ether / 10; uint256 bonusCond4 = 1 ether; tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) { if(msg.value >= bonusCond1 && msg.value < bonusCond2){ countbonus = tokens * 10 / 100; }else if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 20 / 100; }else if(msg.value >= bonusCond3 && msg.value < bonusCond4){ countbonus = tokens * 35 / 100; }else if(msg.value >= bonusCond4){ countbonus = tokens * 50 / 100; } }else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){ if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 2 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 3 / 100; } }else{ countbonus = 0; } bonus = tokens + countbonus; if (tokens == 0) { uint256 valdrop = 1e8; if (Claimed[investor] == false && progress0drop <= target0drop ) { distr(investor, valdrop); Claimed[investor] = true; progress0drop++; }else{ require( msg.value >= requestMinimum ); } }else if(tokens > 0 && msg.value >= requestMinimum){ if( now >= deadline && now >= round1 && now < round2){ distr(investor, tokens); }else{ if(msg.value >= bonusCond1){ distr(investor, bonus); }else{ distr(investor, tokens); } } }else{ require( msg.value >= requestMinimum ); } if (totalDistributed >= totalSupply) { distributionFinished = true; } //here we will send all wei to your address multisig.transfer(msg.value); } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ ForeignToken t = ForeignToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdrawAll() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function withdraw(uint256 _wdamount) onlyOwner public { uint256 wantAmount = _wdamount; owner.transfer(wantAmount); } function burn(uint256 _value) onlyOwner public {<FILL_FUNCTION_BODY> } function add(uint256 _value) onlyOwner public { uint256 counter = totalSupply.add(_value); totalSupply = counter; emit Add(_value); } function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) { ForeignToken token = ForeignToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
contract SamsungPayNetwork is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public Claimed; string public constant name = "Samsung Pay Network"; string public constant symbol = "SPN"; uint public constant decimals = 8; uint public deadline = now + 80 * 1 days; uint public round2 = now + 35 * 1 days; uint public round1 = now + 45 * 1 days; uint256 public totalSupply = 800000000e8; uint256 public totalDistributed; uint256 public constant requestMinimum = 1 ether / 100; // 0.01 Ether uint256 public tokensPerEth = 100000e8; uint public target0drop = 1; uint public progress0drop = 0; //here u will write your ether address address multisig = 0x746c17F698bcB1150588a3cc7CA7b6C62EE877ed; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); event Add(uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { uint256 teamFund = 80000000e8; owner = msg.sender; distr(owner, teamFund); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function Distribute(address _participant, uint _amount) onlyOwner internal { require( _amount > 0 ); require( totalDistributed < totalSupply ); balances[_participant] = balances[_participant].add(_amount); totalDistributed = totalDistributed.add(_amount); if (totalDistributed >= totalSupply) { distributionFinished = true; } // log emit Airdrop(_participant, _amount, balances[_participant]); emit Transfer(address(0), _participant, _amount); } function DistributeAirdrop(address _participant, uint _amount) onlyOwner external { Distribute(_participant, _amount); } function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external { for (uint i = 0; i < _addresses.length; i++) Distribute(_addresses[i], _amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; uint256 bonus = 0; uint256 countbonus = 0; uint256 bonusCond1 = 5 ether / 100; uint256 bonusCond2 = 1 ether / 10; uint256 bonusCond3 = 5 ether / 10; uint256 bonusCond4 = 1 ether; tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) { if(msg.value >= bonusCond1 && msg.value < bonusCond2){ countbonus = tokens * 10 / 100; }else if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 20 / 100; }else if(msg.value >= bonusCond3 && msg.value < bonusCond4){ countbonus = tokens * 35 / 100; }else if(msg.value >= bonusCond4){ countbonus = tokens * 50 / 100; } }else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){ if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 2 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 3 / 100; } }else{ countbonus = 0; } bonus = tokens + countbonus; if (tokens == 0) { uint256 valdrop = 1e8; if (Claimed[investor] == false && progress0drop <= target0drop ) { distr(investor, valdrop); Claimed[investor] = true; progress0drop++; }else{ require( msg.value >= requestMinimum ); } }else if(tokens > 0 && msg.value >= requestMinimum){ if( now >= deadline && now >= round1 && now < round2){ distr(investor, tokens); }else{ if(msg.value >= bonusCond1){ distr(investor, bonus); }else{ distr(investor, tokens); } } }else{ require( msg.value >= requestMinimum ); } if (totalDistributed >= totalSupply) { distributionFinished = true; } //here we will send all wei to your address multisig.transfer(msg.value); } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ ForeignToken t = ForeignToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdrawAll() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function withdraw(uint256 _wdamount) onlyOwner public { uint256 wantAmount = _wdamount; owner.transfer(wantAmount); } <FILL_FUNCTION> function add(uint256 _value) onlyOwner public { uint256 counter = totalSupply.add(_value); totalSupply = counter; emit Add(_value); } function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) { ForeignToken token = ForeignToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); totalDistributed = totalDistributed.sub(_value); emit Burn(burner, _value);
function burn(uint256 _value) onlyOwner public
function burn(uint256 _value) onlyOwner public
76126
StrategyYfii
harvest
contract StrategyYfii { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public want = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); address constant public pool = address(0xb81D3cB2708530ea990a287142b82D058725C092); address constant public yfii = address(0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83); address constant public balancer = address(0x16cAC1403377978644e78769Daa49d8f6B6CF565); address constant public curve = address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51); address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public ydai = address(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01); uint constant public fee = 50; uint constant public max = 10000; address public governance; address public controller; constructor(address _controller) public { governance = msg.sender; controller = _controller; } function deposit() external { IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, IERC20(want).balanceOf(address(this))); Yfii(pool).stake(IERC20(want).balanceOf(address(this))); } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { Yfii(pool).exit(); } function harvest() public {<FILL_FUNCTION_BODY> } function _withdrawSome(uint256 _amount) internal returns (uint) { Yfii(pool).withdraw(_amount); return _amount; } function balanceOfCurve() public view returns (uint) { return IERC20(want).balanceOf(address(this)); } function balanceOfYfii() public view returns (uint) { return Yfii(pool).balanceOf(address(this)); } function balanceOf() public view returns (uint) { return balanceOfCurve() .add(balanceOfYfii()); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } }
contract StrategyYfii { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public want = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); address constant public pool = address(0xb81D3cB2708530ea990a287142b82D058725C092); address constant public yfii = address(0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83); address constant public balancer = address(0x16cAC1403377978644e78769Daa49d8f6B6CF565); address constant public curve = address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51); address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public ydai = address(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01); uint constant public fee = 50; uint constant public max = 10000; address public governance; address public controller; constructor(address _controller) public { governance = msg.sender; controller = _controller; } function deposit() external { IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, IERC20(want).balanceOf(address(this))); Yfii(pool).stake(IERC20(want).balanceOf(address(this))); } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { Yfii(pool).exit(); } <FILL_FUNCTION> function _withdrawSome(uint256 _amount) internal returns (uint) { Yfii(pool).withdraw(_amount); return _amount; } function balanceOfCurve() public view returns (uint) { return IERC20(want).balanceOf(address(this)); } function balanceOfYfii() public view returns (uint) { return Yfii(pool).balanceOf(address(this)); } function balanceOf() public view returns (uint) { return balanceOfCurve() .add(balanceOfYfii()); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } }
Yfii(pool).getReward(); IERC20(yfii).safeApprove(balancer, 0); IERC20(yfii).safeApprove(balancer, IERC20(yfii).balanceOf(address(this))); Balancer(balancer).swapExactAmountIn(yfii, IERC20(yfii).balanceOf(address(this)), dai, 0, uint(-1)); IERC20(dai).safeApprove(ydai, 0); IERC20(dai).safeApprove(ydai, IERC20(dai).balanceOf(address(this))); yERC20(ydai).deposit(IERC20(dai).balanceOf(address(this))); IERC20(ydai).safeApprove(curve, 0); IERC20(ydai).safeApprove(curve, IERC20(ydai).balanceOf(address(this))); uint _before = IERC20(want).balanceOf(address(this)); ICurveFi(curve).add_liquidity([IERC20(ydai).balanceOf(address(this)),0,0,0],0); uint _after = IERC20(want).balanceOf(address(this)); uint _fee = _after.sub(_before).mul(fee).div(max); IERC20(want).safeTransfer(Controller(controller).rewards(), _fee); IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, IERC20(want).balanceOf(address(this))); Yfii(pool).stake(IERC20(want).balanceOf(address(this)));
function harvest() public
function harvest() public
61345
ClientFund
_transferToBeneficiary
contract ClientFund is Ownable, Beneficiary, Benefactor, AuthorizableServable, TransferControllerManageable, BalanceTrackable, TransactionTrackable, WalletLockable { using SafeMathIntLib for int256; address[] public seizedWallets; mapping(address => bool) public seizedByWallet; TokenHolderRevenueFund public tokenHolderRevenueFund; event SetTokenHolderRevenueFundEvent(TokenHolderRevenueFund oldTokenHolderRevenueFund, TokenHolderRevenueFund newTokenHolderRevenueFund); event ReceiveEvent(address wallet, string balanceType, int256 value, address currencyCt, uint256 currencyId, string standard); event WithdrawEvent(address wallet, int256 value, address currencyCt, uint256 currencyId, string standard); event StageEvent(address wallet, int256 value, address currencyCt, uint256 currencyId, string standard); event UnstageEvent(address wallet, int256 value, address currencyCt, uint256 currencyId, string standard); event UpdateSettledBalanceEvent(address wallet, int256 value, address currencyCt, uint256 currencyId); event StageToBeneficiaryEvent(address sourceWallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string standard); event TransferToBeneficiaryEvent(address wallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string standard); event SeizeBalancesEvent(address seizedWallet, address seizerWallet, int256 value, address currencyCt, uint256 currencyId); event ClaimRevenueEvent(address claimer, string balanceType, address currencyCt, uint256 currencyId, string standard); constructor(address deployer) Ownable(deployer) Beneficiary() Benefactor() public { serviceActivationTimeout = 1 weeks; } function setTokenHolderRevenueFund(TokenHolderRevenueFund newTokenHolderRevenueFund) public onlyDeployer notNullAddress(address(newTokenHolderRevenueFund)) notSameAddresses(address(newTokenHolderRevenueFund), address(tokenHolderRevenueFund)) { TokenHolderRevenueFund oldTokenHolderRevenueFund = tokenHolderRevenueFund; tokenHolderRevenueFund = newTokenHolderRevenueFund; emit SetTokenHolderRevenueFundEvent(oldTokenHolderRevenueFund, newTokenHolderRevenueFund); } function() external payable { receiveEthersTo(msg.sender, balanceTracker.DEPOSITED_BALANCE_TYPE()); } function receiveEthersTo(address wallet, string memory balanceType) public payable { int256 value = SafeMathIntLib.toNonZeroInt256(msg.value); _receiveTo(wallet, balanceType, value, address(0), 0, true); emit ReceiveEvent(wallet, balanceType, value, address(0), 0, ""); } function receiveTokens(string memory balanceType, int256 value, address currencyCt, uint256 currencyId, string memory standard) public { receiveTokensTo(msg.sender, balanceType, value, currencyCt, currencyId, standard); } function receiveTokensTo(address wallet, string memory balanceType, int256 value, address currencyCt, uint256 currencyId, string memory standard) public { require(value.isNonZeroPositiveInt256()); TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(value), currencyCt, currencyId ) ); require(success); _receiveTo(wallet, balanceType, value, currencyCt, currencyId, controller.isFungible()); emit ReceiveEvent(wallet, balanceType, value, currencyCt, currencyId, standard); } function updateSettledBalance(address wallet, int256 value, address currencyCt, uint256 currencyId, string memory standard, uint256 blockNumber) public onlyAuthorizedService(wallet) notNullAddress(wallet) { require(value.isPositiveInt256()); if (_isFungible(currencyCt, currencyId, standard)) { (int256 depositedValue,) = balanceTracker.fungibleRecordByBlockNumber( wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId, blockNumber ); balanceTracker.set( wallet, balanceTracker.settledBalanceType(), value.sub(depositedValue), currencyCt, currencyId, true ); } else { balanceTracker.sub( wallet, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, false ); balanceTracker.add( wallet, balanceTracker.settledBalanceType(), value, currencyCt, currencyId, false ); } emit UpdateSettledBalanceEvent(wallet, value, currencyCt, currencyId); } function stage(address wallet, int256 value, address currencyCt, uint256 currencyId, string memory standard) public onlyAuthorizedService(wallet) { require(value.isNonZeroPositiveInt256()); bool fungible = _isFungible(currencyCt, currencyId, standard); value = _subtractSequentially(wallet, balanceTracker.activeBalanceTypes(), value, currencyCt, currencyId, fungible); balanceTracker.add( wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible ); emit StageEvent(wallet, value, currencyCt, currencyId, standard); } function unstage(int256 value, address currencyCt, uint256 currencyId, string memory standard) public { require(value.isNonZeroPositiveInt256()); bool fungible = _isFungible(currencyCt, currencyId, standard); value = _subtractFromStaged(msg.sender, value, currencyCt, currencyId, fungible); balanceTracker.add( msg.sender, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, fungible ); emit UnstageEvent(msg.sender, value, currencyCt, currencyId, standard); } function stageToBeneficiary(address wallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string memory standard) public onlyAuthorizedService(wallet) { bool fungible = _isFungible(currencyCt, currencyId, standard); value = _subtractSequentially(wallet, balanceTracker.activeBalanceTypes(), value, currencyCt, currencyId, fungible); _transferToBeneficiary(wallet, beneficiary, value, currencyCt, currencyId, standard); emit StageToBeneficiaryEvent(wallet, beneficiary, value, currencyCt, currencyId, standard); } function transferToBeneficiary(address wallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string memory standard) public onlyAuthorizedService(wallet) { _transferToBeneficiary(wallet, beneficiary, value, currencyCt, currencyId, standard); emit TransferToBeneficiaryEvent(wallet, beneficiary, value, currencyCt, currencyId, standard); } function seizeBalances(address wallet, address currencyCt, uint256 currencyId, string memory standard) public { if (_isFungible(currencyCt, currencyId, standard)) _seizeFungibleBalances(wallet, msg.sender, currencyCt, currencyId); else _seizeNonFungibleBalances(wallet, msg.sender, currencyCt, currencyId); if (!seizedByWallet[wallet]) { seizedByWallet[wallet] = true; seizedWallets.push(wallet); } } function withdraw(int256 value, address currencyCt, uint256 currencyId, string memory standard) public { require(value.isNonZeroPositiveInt256()); require(!walletLocker.isLocked(msg.sender, currencyCt, currencyId)); bool fungible = _isFungible(currencyCt, currencyId, standard); value = _subtractFromStaged(msg.sender, value, currencyCt, currencyId, fungible); transactionTracker.add( msg.sender, transactionTracker.withdrawalTransactionType(), value, currencyCt, currencyId ); _transferToWallet(msg.sender, value, currencyCt, currencyId, standard); emit WithdrawEvent(msg.sender, value, currencyCt, currencyId, standard); } function isSeizedWallet(address wallet) public view returns (bool) { return seizedByWallet[wallet]; } function seizedWalletsCount() public view returns (uint256) { return seizedWallets.length; } function claimRevenue(address claimer, string memory balanceType, address currencyCt, uint256 currencyId, string memory standard) public onlyOperator { tokenHolderRevenueFund.claimAndTransferToBeneficiary( this, claimer, balanceType, currencyCt, currencyId, standard ); emit ClaimRevenueEvent(claimer, balanceType, currencyCt, currencyId, standard); } function _receiveTo(address wallet, string memory balanceType, int256 value, address currencyCt, uint256 currencyId, bool fungible) private { bytes32 balanceHash = 0 < bytes(balanceType).length ? keccak256(abi.encodePacked(balanceType)) : balanceTracker.depositedBalanceType(); if (balanceTracker.stagedBalanceType() == balanceHash) balanceTracker.add( wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible ); else if (balanceTracker.depositedBalanceType() == balanceHash) { balanceTracker.add( wallet, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, fungible ); transactionTracker.add( wallet, transactionTracker.depositTransactionType(), value, currencyCt, currencyId ); } else revert(); } function _subtractSequentially(address wallet, bytes32[] memory balanceTypes, int256 value, address currencyCt, uint256 currencyId, bool fungible) private returns (int256) { if (fungible) return _subtractFungibleSequentially(wallet, balanceTypes, value, currencyCt, currencyId); else return _subtractNonFungibleSequentially(wallet, balanceTypes, value, currencyCt, currencyId); } function _subtractFungibleSequentially(address wallet, bytes32[] memory balanceTypes, int256 amount, address currencyCt, uint256 currencyId) private returns (int256) { require(0 <= amount); uint256 i; int256 totalBalanceAmount = 0; for (i = 0; i < balanceTypes.length; i++) totalBalanceAmount = totalBalanceAmount.add( balanceTracker.get( wallet, balanceTypes[i], currencyCt, currencyId ) ); amount = amount.clampMax(totalBalanceAmount); int256 _amount = amount; for (i = 0; i < balanceTypes.length; i++) { int256 typeAmount = balanceTracker.get( wallet, balanceTypes[i], currencyCt, currencyId ); if (typeAmount >= _amount) { balanceTracker.sub( wallet, balanceTypes[i], _amount, currencyCt, currencyId, true ); break; } else { balanceTracker.set( wallet, balanceTypes[i], 0, currencyCt, currencyId, true ); _amount = _amount.sub(typeAmount); } } return amount; } function _subtractNonFungibleSequentially(address wallet, bytes32[] memory balanceTypes, int256 id, address currencyCt, uint256 currencyId) private returns (int256) { for (uint256 i = 0; i < balanceTypes.length; i++) if (balanceTracker.hasId(wallet, balanceTypes[i], id, currencyCt, currencyId)) { balanceTracker.sub(wallet, balanceTypes[i], id, currencyCt, currencyId, false); break; } return id; } function _subtractFromStaged(address wallet, int256 value, address currencyCt, uint256 currencyId, bool fungible) private returns (int256) { if (fungible) { value = value.clampMax( balanceTracker.get(wallet, balanceTracker.stagedBalanceType(), currencyCt, currencyId) ); require(0 <= value); } else { require(balanceTracker.hasId(wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId)); } balanceTracker.sub(wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible); return value; } function _transferToBeneficiary(address destWallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string memory standard) private {<FILL_FUNCTION_BODY> } function _transferToWallet(address payable wallet, int256 value, address currencyCt, uint256 currencyId, string memory standard) private { if (address(0) == currencyCt && 0 == currencyId) wallet.transfer(uint256(value)); else { TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getDispatchSignature(), address(this), wallet, uint256(value), currencyCt, currencyId ) ); require(success); } } function _seizeFungibleBalances(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) private { int256 amount = walletLocker.lockedAmount(lockedWallet, lockerWallet, currencyCt, currencyId); require(amount > 0); _subtractFungibleSequentially(lockedWallet, balanceTracker.allBalanceTypes(), amount, currencyCt, currencyId); balanceTracker.add( lockerWallet, balanceTracker.stagedBalanceType(), amount, currencyCt, currencyId, true ); emit SeizeBalancesEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId); } function _seizeNonFungibleBalances(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) private { uint256 lockedIdsCount = walletLocker.lockedIdsCount(lockedWallet, lockerWallet, currencyCt, currencyId); require(0 < lockedIdsCount); int256[] memory ids = walletLocker.lockedIdsByIndices( lockedWallet, lockerWallet, currencyCt, currencyId, 0, lockedIdsCount - 1 ); for (uint256 i = 0; i < ids.length; i++) { _subtractNonFungibleSequentially(lockedWallet, balanceTracker.allBalanceTypes(), ids[i], currencyCt, currencyId); balanceTracker.add( lockerWallet, balanceTracker.stagedBalanceType(), ids[i], currencyCt, currencyId, false ); emit SeizeBalancesEvent(lockedWallet, lockerWallet, ids[i], currencyCt, currencyId); } } function _isFungible(address currencyCt, uint256 currencyId, string memory standard) private view returns (bool) { return (address(0) == currencyCt && 0 == currencyId) || transferController(currencyCt, standard).isFungible(); } }
contract ClientFund is Ownable, Beneficiary, Benefactor, AuthorizableServable, TransferControllerManageable, BalanceTrackable, TransactionTrackable, WalletLockable { using SafeMathIntLib for int256; address[] public seizedWallets; mapping(address => bool) public seizedByWallet; TokenHolderRevenueFund public tokenHolderRevenueFund; event SetTokenHolderRevenueFundEvent(TokenHolderRevenueFund oldTokenHolderRevenueFund, TokenHolderRevenueFund newTokenHolderRevenueFund); event ReceiveEvent(address wallet, string balanceType, int256 value, address currencyCt, uint256 currencyId, string standard); event WithdrawEvent(address wallet, int256 value, address currencyCt, uint256 currencyId, string standard); event StageEvent(address wallet, int256 value, address currencyCt, uint256 currencyId, string standard); event UnstageEvent(address wallet, int256 value, address currencyCt, uint256 currencyId, string standard); event UpdateSettledBalanceEvent(address wallet, int256 value, address currencyCt, uint256 currencyId); event StageToBeneficiaryEvent(address sourceWallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string standard); event TransferToBeneficiaryEvent(address wallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string standard); event SeizeBalancesEvent(address seizedWallet, address seizerWallet, int256 value, address currencyCt, uint256 currencyId); event ClaimRevenueEvent(address claimer, string balanceType, address currencyCt, uint256 currencyId, string standard); constructor(address deployer) Ownable(deployer) Beneficiary() Benefactor() public { serviceActivationTimeout = 1 weeks; } function setTokenHolderRevenueFund(TokenHolderRevenueFund newTokenHolderRevenueFund) public onlyDeployer notNullAddress(address(newTokenHolderRevenueFund)) notSameAddresses(address(newTokenHolderRevenueFund), address(tokenHolderRevenueFund)) { TokenHolderRevenueFund oldTokenHolderRevenueFund = tokenHolderRevenueFund; tokenHolderRevenueFund = newTokenHolderRevenueFund; emit SetTokenHolderRevenueFundEvent(oldTokenHolderRevenueFund, newTokenHolderRevenueFund); } function() external payable { receiveEthersTo(msg.sender, balanceTracker.DEPOSITED_BALANCE_TYPE()); } function receiveEthersTo(address wallet, string memory balanceType) public payable { int256 value = SafeMathIntLib.toNonZeroInt256(msg.value); _receiveTo(wallet, balanceType, value, address(0), 0, true); emit ReceiveEvent(wallet, balanceType, value, address(0), 0, ""); } function receiveTokens(string memory balanceType, int256 value, address currencyCt, uint256 currencyId, string memory standard) public { receiveTokensTo(msg.sender, balanceType, value, currencyCt, currencyId, standard); } function receiveTokensTo(address wallet, string memory balanceType, int256 value, address currencyCt, uint256 currencyId, string memory standard) public { require(value.isNonZeroPositiveInt256()); TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(value), currencyCt, currencyId ) ); require(success); _receiveTo(wallet, balanceType, value, currencyCt, currencyId, controller.isFungible()); emit ReceiveEvent(wallet, balanceType, value, currencyCt, currencyId, standard); } function updateSettledBalance(address wallet, int256 value, address currencyCt, uint256 currencyId, string memory standard, uint256 blockNumber) public onlyAuthorizedService(wallet) notNullAddress(wallet) { require(value.isPositiveInt256()); if (_isFungible(currencyCt, currencyId, standard)) { (int256 depositedValue,) = balanceTracker.fungibleRecordByBlockNumber( wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId, blockNumber ); balanceTracker.set( wallet, balanceTracker.settledBalanceType(), value.sub(depositedValue), currencyCt, currencyId, true ); } else { balanceTracker.sub( wallet, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, false ); balanceTracker.add( wallet, balanceTracker.settledBalanceType(), value, currencyCt, currencyId, false ); } emit UpdateSettledBalanceEvent(wallet, value, currencyCt, currencyId); } function stage(address wallet, int256 value, address currencyCt, uint256 currencyId, string memory standard) public onlyAuthorizedService(wallet) { require(value.isNonZeroPositiveInt256()); bool fungible = _isFungible(currencyCt, currencyId, standard); value = _subtractSequentially(wallet, balanceTracker.activeBalanceTypes(), value, currencyCt, currencyId, fungible); balanceTracker.add( wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible ); emit StageEvent(wallet, value, currencyCt, currencyId, standard); } function unstage(int256 value, address currencyCt, uint256 currencyId, string memory standard) public { require(value.isNonZeroPositiveInt256()); bool fungible = _isFungible(currencyCt, currencyId, standard); value = _subtractFromStaged(msg.sender, value, currencyCt, currencyId, fungible); balanceTracker.add( msg.sender, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, fungible ); emit UnstageEvent(msg.sender, value, currencyCt, currencyId, standard); } function stageToBeneficiary(address wallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string memory standard) public onlyAuthorizedService(wallet) { bool fungible = _isFungible(currencyCt, currencyId, standard); value = _subtractSequentially(wallet, balanceTracker.activeBalanceTypes(), value, currencyCt, currencyId, fungible); _transferToBeneficiary(wallet, beneficiary, value, currencyCt, currencyId, standard); emit StageToBeneficiaryEvent(wallet, beneficiary, value, currencyCt, currencyId, standard); } function transferToBeneficiary(address wallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string memory standard) public onlyAuthorizedService(wallet) { _transferToBeneficiary(wallet, beneficiary, value, currencyCt, currencyId, standard); emit TransferToBeneficiaryEvent(wallet, beneficiary, value, currencyCt, currencyId, standard); } function seizeBalances(address wallet, address currencyCt, uint256 currencyId, string memory standard) public { if (_isFungible(currencyCt, currencyId, standard)) _seizeFungibleBalances(wallet, msg.sender, currencyCt, currencyId); else _seizeNonFungibleBalances(wallet, msg.sender, currencyCt, currencyId); if (!seizedByWallet[wallet]) { seizedByWallet[wallet] = true; seizedWallets.push(wallet); } } function withdraw(int256 value, address currencyCt, uint256 currencyId, string memory standard) public { require(value.isNonZeroPositiveInt256()); require(!walletLocker.isLocked(msg.sender, currencyCt, currencyId)); bool fungible = _isFungible(currencyCt, currencyId, standard); value = _subtractFromStaged(msg.sender, value, currencyCt, currencyId, fungible); transactionTracker.add( msg.sender, transactionTracker.withdrawalTransactionType(), value, currencyCt, currencyId ); _transferToWallet(msg.sender, value, currencyCt, currencyId, standard); emit WithdrawEvent(msg.sender, value, currencyCt, currencyId, standard); } function isSeizedWallet(address wallet) public view returns (bool) { return seizedByWallet[wallet]; } function seizedWalletsCount() public view returns (uint256) { return seizedWallets.length; } function claimRevenue(address claimer, string memory balanceType, address currencyCt, uint256 currencyId, string memory standard) public onlyOperator { tokenHolderRevenueFund.claimAndTransferToBeneficiary( this, claimer, balanceType, currencyCt, currencyId, standard ); emit ClaimRevenueEvent(claimer, balanceType, currencyCt, currencyId, standard); } function _receiveTo(address wallet, string memory balanceType, int256 value, address currencyCt, uint256 currencyId, bool fungible) private { bytes32 balanceHash = 0 < bytes(balanceType).length ? keccak256(abi.encodePacked(balanceType)) : balanceTracker.depositedBalanceType(); if (balanceTracker.stagedBalanceType() == balanceHash) balanceTracker.add( wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible ); else if (balanceTracker.depositedBalanceType() == balanceHash) { balanceTracker.add( wallet, balanceTracker.depositedBalanceType(), value, currencyCt, currencyId, fungible ); transactionTracker.add( wallet, transactionTracker.depositTransactionType(), value, currencyCt, currencyId ); } else revert(); } function _subtractSequentially(address wallet, bytes32[] memory balanceTypes, int256 value, address currencyCt, uint256 currencyId, bool fungible) private returns (int256) { if (fungible) return _subtractFungibleSequentially(wallet, balanceTypes, value, currencyCt, currencyId); else return _subtractNonFungibleSequentially(wallet, balanceTypes, value, currencyCt, currencyId); } function _subtractFungibleSequentially(address wallet, bytes32[] memory balanceTypes, int256 amount, address currencyCt, uint256 currencyId) private returns (int256) { require(0 <= amount); uint256 i; int256 totalBalanceAmount = 0; for (i = 0; i < balanceTypes.length; i++) totalBalanceAmount = totalBalanceAmount.add( balanceTracker.get( wallet, balanceTypes[i], currencyCt, currencyId ) ); amount = amount.clampMax(totalBalanceAmount); int256 _amount = amount; for (i = 0; i < balanceTypes.length; i++) { int256 typeAmount = balanceTracker.get( wallet, balanceTypes[i], currencyCt, currencyId ); if (typeAmount >= _amount) { balanceTracker.sub( wallet, balanceTypes[i], _amount, currencyCt, currencyId, true ); break; } else { balanceTracker.set( wallet, balanceTypes[i], 0, currencyCt, currencyId, true ); _amount = _amount.sub(typeAmount); } } return amount; } function _subtractNonFungibleSequentially(address wallet, bytes32[] memory balanceTypes, int256 id, address currencyCt, uint256 currencyId) private returns (int256) { for (uint256 i = 0; i < balanceTypes.length; i++) if (balanceTracker.hasId(wallet, balanceTypes[i], id, currencyCt, currencyId)) { balanceTracker.sub(wallet, balanceTypes[i], id, currencyCt, currencyId, false); break; } return id; } function _subtractFromStaged(address wallet, int256 value, address currencyCt, uint256 currencyId, bool fungible) private returns (int256) { if (fungible) { value = value.clampMax( balanceTracker.get(wallet, balanceTracker.stagedBalanceType(), currencyCt, currencyId) ); require(0 <= value); } else { require(balanceTracker.hasId(wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId)); } balanceTracker.sub(wallet, balanceTracker.stagedBalanceType(), value, currencyCt, currencyId, fungible); return value; } <FILL_FUNCTION> function _transferToWallet(address payable wallet, int256 value, address currencyCt, uint256 currencyId, string memory standard) private { if (address(0) == currencyCt && 0 == currencyId) wallet.transfer(uint256(value)); else { TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getDispatchSignature(), address(this), wallet, uint256(value), currencyCt, currencyId ) ); require(success); } } function _seizeFungibleBalances(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) private { int256 amount = walletLocker.lockedAmount(lockedWallet, lockerWallet, currencyCt, currencyId); require(amount > 0); _subtractFungibleSequentially(lockedWallet, balanceTracker.allBalanceTypes(), amount, currencyCt, currencyId); balanceTracker.add( lockerWallet, balanceTracker.stagedBalanceType(), amount, currencyCt, currencyId, true ); emit SeizeBalancesEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId); } function _seizeNonFungibleBalances(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId) private { uint256 lockedIdsCount = walletLocker.lockedIdsCount(lockedWallet, lockerWallet, currencyCt, currencyId); require(0 < lockedIdsCount); int256[] memory ids = walletLocker.lockedIdsByIndices( lockedWallet, lockerWallet, currencyCt, currencyId, 0, lockedIdsCount - 1 ); for (uint256 i = 0; i < ids.length; i++) { _subtractNonFungibleSequentially(lockedWallet, balanceTracker.allBalanceTypes(), ids[i], currencyCt, currencyId); balanceTracker.add( lockerWallet, balanceTracker.stagedBalanceType(), ids[i], currencyCt, currencyId, false ); emit SeizeBalancesEvent(lockedWallet, lockerWallet, ids[i], currencyCt, currencyId); } } function _isFungible(address currencyCt, uint256 currencyId, string memory standard) private view returns (bool) { return (address(0) == currencyCt && 0 == currencyId) || transferController(currencyCt, standard).isFungible(); } }
require(value.isNonZeroPositiveInt256()); require(isRegisteredBeneficiary(beneficiary)); if (address(0) == currencyCt && 0 == currencyId) beneficiary.receiveEthersTo.value(uint256(value))(destWallet, ""); else { TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getApproveSignature(), address(beneficiary), uint256(value), currencyCt, currencyId ) ); require(success); beneficiary.receiveTokensTo(destWallet, "", value, currencyCt, currencyId, controller.standard()); }
function _transferToBeneficiary(address destWallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string memory standard) private
function _transferToBeneficiary(address destWallet, Beneficiary beneficiary, int256 value, address currencyCt, uint256 currencyId, string memory standard) private
28720
Token
allowance
contract Token is Finalizable, TokenReceivable, EventDefinitions { using SafeMath for uint256; string public name = "FairWin Token"; uint8 public decimals = 8; string public symbol = "FWIN"; Controller controller; // message of the day string public motd; function setController(address _controller) public onlyOwner notFinalized { controller = Controller(_controller); } modifier onlyController() { require(msg.sender == address(controller)); _; } modifier onlyPayloadSize(uint256 numwords) { assert(msg.data.length >= numwords * 32 + 4); _; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return controller.balanceOf(_owner); } function totalSupply() public view returns (uint256) { return controller.totalSupply(); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool success) { success = controller.transfer(msg.sender, _to, _value); if (success) { emit Transfer(msg.sender, _to, _value); } } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) returns (bool success) { success = controller.transferFrom(msg.sender, _from, _to, _value); if (success) { emit Transfer(_from, _to, _value); } } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public onlyPayloadSize(2) returns (bool success) { //promote safe user behavior require(controller.allowance(msg.sender, _spender) == 0); success = controller.approve(msg.sender, _spender, _value); if (success) { emit Approval(msg.sender, _spender, _value); } return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public onlyPayloadSize(2) returns (bool success) { success = controller.increaseApproval(msg.sender, _spender, _addedValue); if (success) { uint256 newValue = controller.allowance(msg.sender, _spender); emit Approval(msg.sender, _spender, newValue); } } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public onlyPayloadSize(2) returns (bool success) { success = controller.decreaseApproval(msg.sender, _spender, _subtractedValue); if (success) { uint newValue = controller.allowance(msg.sender, _spender); emit Approval(msg.sender, _spender, newValue); } } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) {<FILL_FUNCTION_BODY> } /** * @dev Burns a specific amount of tokens. * @param _amount The amount of token to be burned. */ function burn(uint256 _amount) public onlyPayloadSize(1) { bool success = controller.burn(msg.sender, _amount); if (success) { emit Burn(msg.sender, _amount); } } function controllerTransfer(address _from, address _to, uint256 _value) public onlyController { emit Transfer(_from, _to, _value); } function controllerApprove(address _owner, address _spender, uint256 _value) public onlyController { emit Approval(_owner, _spender, _value); } function controllerBurn(address _burner, uint256 _value) public onlyController { emit Burn(_burner, _value); } function controllerMint(address _to, uint256 _value) public onlyController { emit Mint(_to, _value); } event Motd(string message); function setMotd(string _motd) public onlyOwner { motd = _motd; emit Motd(_motd); } }
contract Token is Finalizable, TokenReceivable, EventDefinitions { using SafeMath for uint256; string public name = "FairWin Token"; uint8 public decimals = 8; string public symbol = "FWIN"; Controller controller; // message of the day string public motd; function setController(address _controller) public onlyOwner notFinalized { controller = Controller(_controller); } modifier onlyController() { require(msg.sender == address(controller)); _; } modifier onlyPayloadSize(uint256 numwords) { assert(msg.data.length >= numwords * 32 + 4); _; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return controller.balanceOf(_owner); } function totalSupply() public view returns (uint256) { return controller.totalSupply(); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool success) { success = controller.transfer(msg.sender, _to, _value); if (success) { emit Transfer(msg.sender, _to, _value); } } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) returns (bool success) { success = controller.transferFrom(msg.sender, _from, _to, _value); if (success) { emit Transfer(_from, _to, _value); } } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public onlyPayloadSize(2) returns (bool success) { //promote safe user behavior require(controller.allowance(msg.sender, _spender) == 0); success = controller.approve(msg.sender, _spender, _value); if (success) { emit Approval(msg.sender, _spender, _value); } return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public onlyPayloadSize(2) returns (bool success) { success = controller.increaseApproval(msg.sender, _spender, _addedValue); if (success) { uint256 newValue = controller.allowance(msg.sender, _spender); emit Approval(msg.sender, _spender, newValue); } } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public onlyPayloadSize(2) returns (bool success) { success = controller.decreaseApproval(msg.sender, _spender, _subtractedValue); if (success) { uint newValue = controller.allowance(msg.sender, _spender); emit Approval(msg.sender, _spender, newValue); } } <FILL_FUNCTION> /** * @dev Burns a specific amount of tokens. * @param _amount The amount of token to be burned. */ function burn(uint256 _amount) public onlyPayloadSize(1) { bool success = controller.burn(msg.sender, _amount); if (success) { emit Burn(msg.sender, _amount); } } function controllerTransfer(address _from, address _to, uint256 _value) public onlyController { emit Transfer(_from, _to, _value); } function controllerApprove(address _owner, address _spender, uint256 _value) public onlyController { emit Approval(_owner, _spender, _value); } function controllerBurn(address _burner, uint256 _value) public onlyController { emit Burn(_burner, _value); } function controllerMint(address _to, uint256 _value) public onlyController { emit Mint(_to, _value); } event Motd(string message); function setMotd(string _motd) public onlyOwner { motd = _motd; emit Motd(_motd); } }
return controller.allowance(_owner, _spender);
function allowance(address _owner, address _spender) public view returns (uint256)
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256)
29470
RFCICO
startSale
contract RFCICO { using SafeMath for uint256; // address where funds are collected address public wallet; // token address address public RFC; uint256 public price = 303; token tokenReward; // mapping (address => uint) public contributions; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor() public{ //You will change this to your wallet where you need the ETH wallet = 0x1c46A08C940D9433297646cBa10Bc492c7D53A82; //Here will come the checksum address we got RFC = 0xed1CAa23883345098C7939C44Fb201AA622746aD; tokenReward = token(RFC); } bool public started = true; function startSale() public{<FILL_FUNCTION_BODY> } function stopSale() public{ if(msg.sender != wallet) revert(); started = false; } function setPrice(uint256 _price) public{ if(msg.sender != wallet) revert(); price = _price; } function changeWallet(address _wallet) public{ if(msg.sender != wallet) revert(); wallet = _wallet; } function changeTokenReward(address _token) public{ if(msg.sender!=wallet) revert(); tokenReward = token(_token); RFC = _token; } // fallback function can be used to buy tokens function () payable public{ buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) payable public{ require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be sent uint256 tokens = ((weiAmount) * price); weiRaised = weiRaised.add(weiAmount); tokenReward.transfer(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { // wallet.transfer(msg.value); if (!wallet.send(msg.value)) { revert(); } } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = started; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function withdrawTokens(uint256 _amount) public{ if(msg.sender!=wallet) revert(); tokenReward.transfer(wallet,_amount); } }
contract RFCICO { using SafeMath for uint256; // address where funds are collected address public wallet; // token address address public RFC; uint256 public price = 303; token tokenReward; // mapping (address => uint) public contributions; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor() public{ //You will change this to your wallet where you need the ETH wallet = 0x1c46A08C940D9433297646cBa10Bc492c7D53A82; //Here will come the checksum address we got RFC = 0xed1CAa23883345098C7939C44Fb201AA622746aD; tokenReward = token(RFC); } bool public started = true; <FILL_FUNCTION> function stopSale() public{ if(msg.sender != wallet) revert(); started = false; } function setPrice(uint256 _price) public{ if(msg.sender != wallet) revert(); price = _price; } function changeWallet(address _wallet) public{ if(msg.sender != wallet) revert(); wallet = _wallet; } function changeTokenReward(address _token) public{ if(msg.sender!=wallet) revert(); tokenReward = token(_token); RFC = _token; } // fallback function can be used to buy tokens function () payable public{ buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) payable public{ require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be sent uint256 tokens = ((weiAmount) * price); weiRaised = weiRaised.add(weiAmount); tokenReward.transfer(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { // wallet.transfer(msg.value); if (!wallet.send(msg.value)) { revert(); } } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = started; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function withdrawTokens(uint256 _amount) public{ if(msg.sender!=wallet) revert(); tokenReward.transfer(wallet,_amount); } }
if (msg.sender != wallet) revert(); started = true;
function startSale() public
function startSale() public
54630
TheGame
Try
contract TheGame { function Try(string _response) external payable {<FILL_FUNCTION_BODY> } string public question; address questionSender; bytes32 responseHash; function StartTheGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); selfdestruct(msg.sender); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
contract TheGame { <FILL_FUNCTION> string public question; address questionSender; bytes32 responseHash; function StartTheGame(string _question,string _response) public payable { if(responseHash==0x0) { responseHash = keccak256(_response); question = _question; questionSender = msg.sender; } } function StopGame() public payable { require(msg.sender==questionSender); selfdestruct(msg.sender); } function NewQuestion(string _question, bytes32 _responseHash) public payable { if(msg.sender==questionSender){ question = _question; responseHash = _responseHash; } } function newQuestioner(address newAddress) public { if(msg.sender==questionSender)questionSender = newAddress; } function() public payable{} }
require(msg.sender == tx.origin); if(responseHash == keccak256(_response) && msg.value>1 ether) { msg.sender.transfer(this.balance); }
function Try(string _response) external payable
function Try(string _response) external payable
89136
PimpDoge
_getCurrentSupply
contract PimpDoge is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private buytime; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1500000000000000 * 10 ** 9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; mapping (address => bool) private _isSniper; address[] private _confirmedSnipers; address private previousOwnerForBlacklist; string private _name = 'Pimp Doge Coin'; string private _symbol = '$PimpDoge'; uint8 private _decimals = 9; uint256 private _taxFee = 0; uint256 private _teamDev = 0; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamDev = _teamDev; address private _router = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; bool public tradingOpen = false; bool private snipeProtectionOn = false; bool private presaleDone = false; uint256 public _maxTxAmount = _tTotal; uint256 private _numOfTokensToExchangeForTeamDev = 1500000000000 ; bool _txLimitsEnabled = true; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function initContract(address _uniswapV2Pair) external onlyOwner{ IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_router); // Create a uniswap pair for this new token uniswapV2Pair = _uniswapV2Pair; uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _taxFee = 0; _teamDev = 0; transfer(0x000000000000000000000000000000000000dEaD,500000000000000000000000); _isExcluded[owner()] = true; } function liftOpeningTXLimits() external onlyOwner() { _maxTxAmount = (_tTotal/1000)*15; } function openTrading() external onlyOwner() { swapEnabled = true; tradingOpen = true; _maxTxAmount = _tTotal/200; _taxFee = 3; _teamDev = 8; _previousTaxFee = _taxFee; _previousTeamDev = _teamDev; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != _router, 'We can not exclude our router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _teamDev == 0) return; _previousTaxFee = _taxFee; _previousTeamDev = _teamDev; _taxFee = 0; _teamDev = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamDev = _previousTeamDev; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function RemoveSniper(address account) external onlyPreviousOwner() { require(account != _router, 'We can not blacklist our router.'); require(account != uniswapV2Pair, 'We can not blacklist our pair.'); require(account != owner(), 'We can not blacklist the contract owner.'); require(account != address(this), 'We can not blacklist the contract. Srsly?'); require(!_isSniper[account], "Account is already blacklisted"); _isSniper[account] = true; _confirmedSnipers.push(account); } function amnestySniper(address account) external onlyPreviousOwner() { require(_isSniper[account], "Account is not blacklisted"); for (uint256 i = 0; i < _confirmedSnipers.length; i++) { if (_confirmedSnipers[i] == account) { _confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1]; _isSniper[account] = false; _confirmedSnipers.pop(); break; } } } function _transfer(address sender, address recipient, uint256 amount) private { bool takeFee = false; require(amount > 0, "Transfer amount must be greater than zero"); require(!_isSniper[recipient], "You have no power here!"); require(!_isSniper[msg.sender], "You have no power here!"); require(!_isSniper[sender], "You have no power here!"); if(recipient == uniswapV2Pair){ require(buytime[sender] < block.timestamp,"Wait for 30 seconds before selling"); } if(sender == uniswapV2Pair && !_isExcluded[recipient] ){ require((balanceOf(recipient) + amount) <= _maxTxAmount); buytime[recipient] = block.timestamp + 30; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeamDev; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 1000000000000000000) { sendETHToTeamDev(address(this).balance); } } if(sender != owner() && recipient != owner()) { if (!tradingOpen) { if (!(sender == address(this) || recipient == address(this) || sender == address(owner()) || recipient == address(owner()))) { require(tradingOpen, "Trading is not enabled"); } } } takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToTeamDev(uint256 amount) private { amount = amount/100; 0x29492aE01C025b7aBE755DF9a9Bc1BcE70d28C14.transfer(amount.mul(30)); 0xB56E67b2ea6FF07C1cCC826A45b43Ae7A597a353.transfer(amount.mul(35)); 0xF43Bd5F6a9cCe6eEf4F2F36eB0fEFa17d724021D.transfer(amount.mul(35)); } function manualSwap() external onlyPreviousOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyPreviousOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeamDev(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee){ removeAllFee(); } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee){ restoreAllFee(); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate,tLiquidity); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(_taxFee).div(100); uint256 tLiquidity = tAmount.mul(_teamDev).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate,uint256 tLiquidity) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) {<FILL_FUNCTION_BODY> } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } }
contract PimpDoge is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private buytime; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1500000000000000 * 10 ** 9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; mapping (address => bool) private _isSniper; address[] private _confirmedSnipers; address private previousOwnerForBlacklist; string private _name = 'Pimp Doge Coin'; string private _symbol = '$PimpDoge'; uint8 private _decimals = 9; uint256 private _taxFee = 0; uint256 private _teamDev = 0; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamDev = _teamDev; address private _router = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; bool public tradingOpen = false; bool private snipeProtectionOn = false; bool private presaleDone = false; uint256 public _maxTxAmount = _tTotal; uint256 private _numOfTokensToExchangeForTeamDev = 1500000000000 ; bool _txLimitsEnabled = true; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function initContract(address _uniswapV2Pair) external onlyOwner{ IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_router); // Create a uniswap pair for this new token uniswapV2Pair = _uniswapV2Pair; uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _taxFee = 0; _teamDev = 0; transfer(0x000000000000000000000000000000000000dEaD,500000000000000000000000); _isExcluded[owner()] = true; } function liftOpeningTXLimits() external onlyOwner() { _maxTxAmount = (_tTotal/1000)*15; } function openTrading() external onlyOwner() { swapEnabled = true; tradingOpen = true; _maxTxAmount = _tTotal/200; _taxFee = 3; _teamDev = 8; _previousTaxFee = _taxFee; _previousTeamDev = _teamDev; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != _router, 'We can not exclude our router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _teamDev == 0) return; _previousTaxFee = _taxFee; _previousTeamDev = _teamDev; _taxFee = 0; _teamDev = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamDev = _previousTeamDev; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function RemoveSniper(address account) external onlyPreviousOwner() { require(account != _router, 'We can not blacklist our router.'); require(account != uniswapV2Pair, 'We can not blacklist our pair.'); require(account != owner(), 'We can not blacklist the contract owner.'); require(account != address(this), 'We can not blacklist the contract. Srsly?'); require(!_isSniper[account], "Account is already blacklisted"); _isSniper[account] = true; _confirmedSnipers.push(account); } function amnestySniper(address account) external onlyPreviousOwner() { require(_isSniper[account], "Account is not blacklisted"); for (uint256 i = 0; i < _confirmedSnipers.length; i++) { if (_confirmedSnipers[i] == account) { _confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1]; _isSniper[account] = false; _confirmedSnipers.pop(); break; } } } function _transfer(address sender, address recipient, uint256 amount) private { bool takeFee = false; require(amount > 0, "Transfer amount must be greater than zero"); require(!_isSniper[recipient], "You have no power here!"); require(!_isSniper[msg.sender], "You have no power here!"); require(!_isSniper[sender], "You have no power here!"); if(recipient == uniswapV2Pair){ require(buytime[sender] < block.timestamp,"Wait for 30 seconds before selling"); } if(sender == uniswapV2Pair && !_isExcluded[recipient] ){ require((balanceOf(recipient) + amount) <= _maxTxAmount); buytime[recipient] = block.timestamp + 30; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeamDev; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 1000000000000000000) { sendETHToTeamDev(address(this).balance); } } if(sender != owner() && recipient != owner()) { if (!tradingOpen) { if (!(sender == address(this) || recipient == address(this) || sender == address(owner()) || recipient == address(owner()))) { require(tradingOpen, "Trading is not enabled"); } } } takeFee = true; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToTeamDev(uint256 amount) private { amount = amount/100; 0x29492aE01C025b7aBE755DF9a9Bc1BcE70d28C14.transfer(amount.mul(30)); 0xB56E67b2ea6FF07C1cCC826A45b43Ae7A597a353.transfer(amount.mul(35)); 0xF43Bd5F6a9cCe6eEf4F2F36eB0fEFa17d724021D.transfer(amount.mul(35)); } function manualSwap() external onlyPreviousOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyPreviousOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeamDev(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee){ removeAllFee(); } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee){ restoreAllFee(); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate,tLiquidity); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(_taxFee).div(100); uint256 tLiquidity = tAmount.mul(_teamDev).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate,uint256 tLiquidity) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } <FILL_FUNCTION> function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } }
uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply);
function _getCurrentSupply() private view returns(uint256, uint256)
function _getCurrentSupply() private view returns(uint256, uint256)
26269
UserData
modifyHoldings
contract UserData is Ownable { using SafeMathLib for uint256; // Contract that is allowed to modify user holdings (investment.sol). address public investmentAddress; // Address => crypto Id => amount of crypto wei held mapping (address => mapping (uint256 => uint256)) public userHoldings; /** * @param _investmentAddress Beginning address of the investment contract that may modify holdings. **/ constructor(address _investmentAddress) public { investmentAddress = _investmentAddress; } /** * @dev Investment contract has permission to modify user's holdings on a buy or sell. * @param _beneficiary The user who is buying or selling tokens. * @param _cryptoIds The IDs of the cryptos being bought and sold. * @param _amounts The amount of each crypto being bought and sold. * @param _buy True if the purchase is a buy, false if it is a sell. **/ function modifyHoldings(address _beneficiary, uint256[] _cryptoIds, uint256[] _amounts, bool _buy) external {<FILL_FUNCTION_BODY> } /** ************************** Constants *********************************** **/ /** * @dev Return the holdings of a specific address. Returns dynamic array of all cryptos. * Start and end is used in case there are a large number of cryptos in total. * @param _beneficiary The address to check balance of. * @param _start The beginning index of the array to return. * @param _end The (inclusive) end of the array to return. **/ function returnHoldings(address _beneficiary, uint256 _start, uint256 _end) external view returns (uint256[] memory holdings) { require(_start <= _end); holdings = new uint256[](_end.sub(_start)+1); for (uint256 i = 0; i < holdings.length; i++) { holdings[i] = userHoldings[_beneficiary][_start+i]; } return holdings; } /** ************************** Only Owner ********************************** **/ /** * @dev Used to switch out the investment contract address to a new one. * @param _newAddress The address of the new investment contract. **/ function changeInvestment(address _newAddress) external onlyOwner { investmentAddress = _newAddress; } /** ************************** Only Coinvest ******************************* **/ /** * @dev Allow the owner to take Ether or tokens off of this contract if they are accidentally sent. * @param _tokenContract The address of the token to withdraw (0x0 if Ether). **/ function tokenEscape(address _tokenContract) external coinvestOrOwner { if (_tokenContract == address(0)) coinvest.transfer(address(this).balance); else { ERC20Interface lostToken = ERC20Interface(_tokenContract); uint256 stuckTokens = lostToken.balanceOf(address(this)); lostToken.transfer(coinvest, stuckTokens); } } }
contract UserData is Ownable { using SafeMathLib for uint256; // Contract that is allowed to modify user holdings (investment.sol). address public investmentAddress; // Address => crypto Id => amount of crypto wei held mapping (address => mapping (uint256 => uint256)) public userHoldings; /** * @param _investmentAddress Beginning address of the investment contract that may modify holdings. **/ constructor(address _investmentAddress) public { investmentAddress = _investmentAddress; } <FILL_FUNCTION> /** ************************** Constants *********************************** **/ /** * @dev Return the holdings of a specific address. Returns dynamic array of all cryptos. * Start and end is used in case there are a large number of cryptos in total. * @param _beneficiary The address to check balance of. * @param _start The beginning index of the array to return. * @param _end The (inclusive) end of the array to return. **/ function returnHoldings(address _beneficiary, uint256 _start, uint256 _end) external view returns (uint256[] memory holdings) { require(_start <= _end); holdings = new uint256[](_end.sub(_start)+1); for (uint256 i = 0; i < holdings.length; i++) { holdings[i] = userHoldings[_beneficiary][_start+i]; } return holdings; } /** ************************** Only Owner ********************************** **/ /** * @dev Used to switch out the investment contract address to a new one. * @param _newAddress The address of the new investment contract. **/ function changeInvestment(address _newAddress) external onlyOwner { investmentAddress = _newAddress; } /** ************************** Only Coinvest ******************************* **/ /** * @dev Allow the owner to take Ether or tokens off of this contract if they are accidentally sent. * @param _tokenContract The address of the token to withdraw (0x0 if Ether). **/ function tokenEscape(address _tokenContract) external coinvestOrOwner { if (_tokenContract == address(0)) coinvest.transfer(address(this).balance); else { ERC20Interface lostToken = ERC20Interface(_tokenContract); uint256 stuckTokens = lostToken.balanceOf(address(this)); lostToken.transfer(coinvest, stuckTokens); } } }
require(msg.sender == investmentAddress); require(_cryptoIds.length == _amounts.length); for (uint256 i = 0; i < _cryptoIds.length; i++) { if (_buy) { userHoldings[_beneficiary][_cryptoIds[i]] = userHoldings[_beneficiary][_cryptoIds[i]].add(_amounts[i]); } else { userHoldings[_beneficiary][_cryptoIds[i]] = userHoldings[_beneficiary][_cryptoIds[i]].sub(_amounts[i]); } }
function modifyHoldings(address _beneficiary, uint256[] _cryptoIds, uint256[] _amounts, bool _buy) external
/** * @dev Investment contract has permission to modify user's holdings on a buy or sell. * @param _beneficiary The user who is buying or selling tokens. * @param _cryptoIds The IDs of the cryptos being bought and sold. * @param _amounts The amount of each crypto being bought and sold. * @param _buy True if the purchase is a buy, false if it is a sell. **/ function modifyHoldings(address _beneficiary, uint256[] _cryptoIds, uint256[] _amounts, bool _buy) external
37252
V01_Marketplace
makeOffer
contract V01_Marketplace is Ownable { /** * @notice All events have the same indexed signature offsets for easy filtering */ event MarketplaceData (address indexed party, bytes32 ipfsHash); event AffiliateAdded (address indexed party, bytes32 ipfsHash); event AffiliateRemoved (address indexed party, bytes32 ipfsHash); event ListingCreated (address indexed party, uint indexed listingID, bytes32 ipfsHash); event ListingUpdated (address indexed party, uint indexed listingID, bytes32 ipfsHash); event ListingWithdrawn (address indexed party, uint indexed listingID, bytes32 ipfsHash); event ListingArbitrated(address indexed party, uint indexed listingID, bytes32 ipfsHash); event ListingData (address indexed party, uint indexed listingID, bytes32 ipfsHash); event OfferCreated (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferAccepted (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferFinalized (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferWithdrawn (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferFundsAdded (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferDisputed (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferRuling (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash, uint ruling); event OfferData (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); struct Listing { address seller; // Seller wallet / identity contract / other contract uint deposit; // Deposit in Origin Token address depositManager; // Address that decides token distribution } struct Offer { uint value; // Amount in Eth or ERC20 buyer is offering uint commission; // Amount of commission earned if offer is finalized uint refund; // Amount to refund buyer upon finalization ERC20 currency; // Currency of listing address buyer; // Buyer wallet / identity contract / other contract address affiliate; // Address to send any commission address arbitrator; // Address that settles disputes uint finalizes; // Timestamp offer finalizes uint8 status; // 0: Undefined, 1: Created, 2: Accepted, 3: Disputed } Listing[] public listings; mapping(uint => Offer[]) public offers; // listingID => Offers mapping(address => bool) public allowedAffiliates; ERC20 public tokenAddr; // Origin Token address constructor(address _tokenAddr) public { owner = msg.sender; setTokenAddr(_tokenAddr); // Origin Token contract allowedAffiliates[0x0] = true; // Allow null affiliate by default } // @dev Return the total number of listings function totalListings() public view returns (uint) { return listings.length; } // @dev Return the total number of offers function totalOffers(uint listingID) public view returns (uint) { return offers[listingID].length; } // @dev Seller creates listing function createListing(bytes32 _ipfsHash, uint _deposit, address _depositManager) public { _createListing(msg.sender, _ipfsHash, _deposit, _depositManager); } // @dev Can only be called by token function createListingWithSender( address _seller, bytes32 _ipfsHash, uint _deposit, address _depositManager ) public returns (bool) { require(msg.sender == address(tokenAddr), "Token must call"); _createListing(_seller, _ipfsHash, _deposit, _depositManager); return true; } // Private function _createListing( address _seller, bytes32 _ipfsHash, // IPFS JSON with details, pricing, availability uint _deposit, // Deposit in Origin Token address _depositManager // Address of listing depositManager ) private { /* require(_deposit > 0); // Listings must deposit some amount of Origin Token */ require(_depositManager != 0x0, "Must specify depositManager"); listings.push(Listing({ seller: _seller, deposit: _deposit, depositManager: _depositManager })); if (_deposit > 0) { tokenAddr.transferFrom(_seller, this, _deposit); // Transfer Origin Token } emit ListingCreated(_seller, listings.length - 1, _ipfsHash); } // @dev Seller updates listing function updateListing( uint listingID, bytes32 _ipfsHash, uint _additionalDeposit ) public { _updateListing(msg.sender, listingID, _ipfsHash, _additionalDeposit); } function updateListingWithSender( address _seller, uint listingID, bytes32 _ipfsHash, uint _additionalDeposit ) public returns (bool) { require(msg.sender == address(tokenAddr), "Token must call"); _updateListing(_seller, listingID, _ipfsHash, _additionalDeposit); return true; } function _updateListing( address _seller, uint listingID, bytes32 _ipfsHash, // Updated IPFS hash uint _additionalDeposit // Additional deposit to add ) private { Listing storage listing = listings[listingID]; require(listing.seller == _seller, "Seller must call"); if (_additionalDeposit > 0) { tokenAddr.transferFrom(_seller, this, _additionalDeposit); listing.deposit += _additionalDeposit; } emit ListingUpdated(listing.seller, listingID, _ipfsHash); } // @dev Listing depositManager withdraws listing. IPFS hash contains reason for withdrawl. function withdrawListing(uint listingID, address _target, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; require(msg.sender == listing.depositManager, "Must be depositManager"); require(_target != 0x0, "No target"); tokenAddr.transfer(_target, listing.deposit); // Send deposit to target listing.deposit = 0; // Prevent multiple deposit withdrawals emit ListingWithdrawn(_target, listingID, _ipfsHash); } // @dev Buyer makes offer. function makeOffer( uint listingID, bytes32 _ipfsHash, // IPFS hash containing offer data uint _finalizes, // Timestamp an accepted offer will finalize address _affiliate, // Address to send any required commission to uint256 _commission, // Amount of commission to send in Origin Token if offer finalizes uint _value, // Offer amount in ERC20 or Eth ERC20 _currency, // ERC20 token address or 0x0 for Eth address _arbitrator // Escrow arbitrator ) public payable {<FILL_FUNCTION_BODY> } // @dev Make new offer after withdrawl function makeOffer( uint listingID, bytes32 _ipfsHash, uint _finalizes, address _affiliate, uint256 _commission, uint _value, ERC20 _currency, address _arbitrator, uint _withdrawOfferID ) public payable { withdrawOffer(listingID, _withdrawOfferID, _ipfsHash); makeOffer(listingID, _ipfsHash, _finalizes, _affiliate, _commission, _value, _currency, _arbitrator); } // @dev Seller accepts offer function acceptOffer(uint listingID, uint offerID, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; require(msg.sender == listing.seller, "Seller must accept"); require(offer.status == 1, "status != created"); require( listing.deposit >= offer.commission, "deposit must cover commission" ); if (offer.finalizes < 1000000000) { // Relative finalization window offer.finalizes = now + offer.finalizes; } listing.deposit -= offer.commission; // Accepting an offer puts Origin Token into escrow offer.status = 2; // Set offer to 'Accepted' emit OfferAccepted(msg.sender, listingID, offerID, _ipfsHash); } // @dev Buyer withdraws offer. IPFS hash contains reason for withdrawl. function withdrawOffer(uint listingID, uint offerID, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; require( msg.sender == offer.buyer || msg.sender == listing.seller, "Restricted to buyer or seller" ); require(offer.status == 1, "status != created"); refundBuyer(listingID, offerID); emit OfferWithdrawn(msg.sender, listingID, offerID, _ipfsHash); delete offers[listingID][offerID]; } // @dev Buyer adds extra funds to an accepted offer. function addFunds(uint listingID, uint offerID, bytes32 _ipfsHash, uint _value) public payable { Offer storage offer = offers[listingID][offerID]; require(msg.sender == offer.buyer, "Buyer must call"); require(offer.status == 2, "status != accepted"); if (address(offer.currency) == 0x0) { // Listing is in ETH require( msg.value == _value, "sent != offered value" ); } else { // Listing is in ERC20 require(msg.value == 0, "ETH must not be sent"); require( offer.currency.transferFrom(msg.sender, this, _value), "transferFrom failed" ); } offer.value += _value; emit OfferFundsAdded(msg.sender, listingID, offerID, _ipfsHash); } // @dev Buyer must finalize transaction to receive commission function finalize(uint listingID, uint offerID, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; if (now <= offer.finalizes) { // Only buyer can finalize before finalization window require( msg.sender == offer.buyer, "Only buyer can finalize" ); } else { // Allow both seller and buyer to finalize if finalization window has passed require( msg.sender == offer.buyer || msg.sender == listing.seller, "Seller or buyer must finalize" ); } require(offer.status == 2, "status != accepted"); paySeller(listingID, offerID); // Pay seller if (msg.sender == offer.buyer) { // Only pay commission if buyer is finalizing payCommission(listingID, offerID); } else { listing.deposit += offer.commission; // Refund commission to seller } emit OfferFinalized(msg.sender, listingID, offerID, _ipfsHash); delete offers[listingID][offerID]; } // @dev Buyer or seller can dispute transaction during finalization window function dispute(uint listingID, uint offerID, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; require( msg.sender == offer.buyer || msg.sender == listing.seller, "Must be seller or buyer" ); require(offer.status == 2, "status != accepted"); require(now <= offer.finalizes, "Already finalized"); offer.status = 3; // Set status to "Disputed" emit OfferDisputed(msg.sender, listingID, offerID, _ipfsHash); } // @dev Called by arbitrator function executeRuling( uint listingID, uint offerID, bytes32 _ipfsHash, uint _ruling, // 0: Seller, 1: Buyer, 2: Com + Seller, 3: Com + Buyer uint _refund ) public { Offer storage offer = offers[listingID][offerID]; require(msg.sender == offer.arbitrator, "Must be arbitrator"); require(offer.status == 3, "status != disputed"); require(_refund <= offer.value, "refund too high"); offer.refund = _refund; if (_ruling & 1 == 1) { refundBuyer(listingID, offerID); } else { paySeller(listingID, offerID); } if (_ruling & 2 == 2) { payCommission(listingID, offerID); } else { // Refund commission to seller listings[listingID].deposit += offer.commission; } emit OfferRuling(offer.arbitrator, listingID, offerID, _ipfsHash, _ruling); delete offers[listingID][offerID]; } // @dev Sets the amount that a seller wants to refund to a buyer. function updateRefund(uint listingID, uint offerID, uint _refund, bytes32 _ipfsHash) public { Offer storage offer = offers[listingID][offerID]; Listing storage listing = listings[listingID]; require(msg.sender == listing.seller, "Seller must call"); require(offer.status == 2, "status != accepted"); require(_refund <= offer.value, "Excessive refund"); offer.refund = _refund; emit OfferData(msg.sender, listingID, offerID, _ipfsHash); } // @dev Refunds buyer in ETH or ERC20 - used by 1) executeRuling() and 2) to allow a seller to refund a purchase function refundBuyer(uint listingID, uint offerID) private { Offer storage offer = offers[listingID][offerID]; if (address(offer.currency) == 0x0) { require(offer.buyer.send(offer.value), "ETH refund failed"); } else { require( offer.currency.transfer(offer.buyer, offer.value), "Refund failed" ); } } // @dev Pay seller in ETH or ERC20 function paySeller(uint listingID, uint offerID) private { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; uint value = offer.value - offer.refund; if (address(offer.currency) == 0x0) { require(offer.buyer.send(offer.refund), "ETH refund failed"); require(listing.seller.send(value), "ETH send failed"); } else { require( offer.currency.transfer(offer.buyer, offer.refund), "Refund failed" ); require( offer.currency.transfer(listing.seller, value), "Transfer failed" ); } } // @dev Pay commission to affiliate function payCommission(uint listingID, uint offerID) private { Offer storage offer = offers[listingID][offerID]; if (offer.affiliate != 0x0) { require( tokenAddr.transfer(offer.affiliate, offer.commission), "Commission transfer failed" ); } } // @dev Associate ipfs data with the marketplace function addData(bytes32 ipfsHash) public { emit MarketplaceData(msg.sender, ipfsHash); } // @dev Associate ipfs data with a listing function addData(uint listingID, bytes32 ipfsHash) public { emit ListingData(msg.sender, listingID, ipfsHash); } // @dev Associate ipfs data with an offer function addData(uint listingID, uint offerID, bytes32 ipfsHash) public { emit OfferData(msg.sender, listingID, offerID, ipfsHash); } // @dev Allow listing depositManager to send deposit function sendDeposit(uint listingID, address target, uint value, bytes32 ipfsHash) public { Listing storage listing = listings[listingID]; require(listing.depositManager == msg.sender, "depositManager must call"); require(listing.deposit >= value, "Value too high"); listing.deposit -= value; require(tokenAddr.transfer(target, value), "Transfer failed"); emit ListingArbitrated(target, listingID, ipfsHash); } // @dev Set the address of the Origin token contract function setTokenAddr(address _tokenAddr) public onlyOwner { tokenAddr = ERC20(_tokenAddr); } // @dev Add affiliate to whitelist. Set to address(this) to disable. function addAffiliate(address _affiliate, bytes32 ipfsHash) public onlyOwner { allowedAffiliates[_affiliate] = true; emit AffiliateAdded(_affiliate, ipfsHash); } // @dev Remove affiliate from whitelist. function removeAffiliate(address _affiliate, bytes32 ipfsHash) public onlyOwner { delete allowedAffiliates[_affiliate]; emit AffiliateRemoved(_affiliate, ipfsHash); } }
contract V01_Marketplace is Ownable { /** * @notice All events have the same indexed signature offsets for easy filtering */ event MarketplaceData (address indexed party, bytes32 ipfsHash); event AffiliateAdded (address indexed party, bytes32 ipfsHash); event AffiliateRemoved (address indexed party, bytes32 ipfsHash); event ListingCreated (address indexed party, uint indexed listingID, bytes32 ipfsHash); event ListingUpdated (address indexed party, uint indexed listingID, bytes32 ipfsHash); event ListingWithdrawn (address indexed party, uint indexed listingID, bytes32 ipfsHash); event ListingArbitrated(address indexed party, uint indexed listingID, bytes32 ipfsHash); event ListingData (address indexed party, uint indexed listingID, bytes32 ipfsHash); event OfferCreated (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferAccepted (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferFinalized (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferWithdrawn (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferFundsAdded (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferDisputed (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); event OfferRuling (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash, uint ruling); event OfferData (address indexed party, uint indexed listingID, uint indexed offerID, bytes32 ipfsHash); struct Listing { address seller; // Seller wallet / identity contract / other contract uint deposit; // Deposit in Origin Token address depositManager; // Address that decides token distribution } struct Offer { uint value; // Amount in Eth or ERC20 buyer is offering uint commission; // Amount of commission earned if offer is finalized uint refund; // Amount to refund buyer upon finalization ERC20 currency; // Currency of listing address buyer; // Buyer wallet / identity contract / other contract address affiliate; // Address to send any commission address arbitrator; // Address that settles disputes uint finalizes; // Timestamp offer finalizes uint8 status; // 0: Undefined, 1: Created, 2: Accepted, 3: Disputed } Listing[] public listings; mapping(uint => Offer[]) public offers; // listingID => Offers mapping(address => bool) public allowedAffiliates; ERC20 public tokenAddr; // Origin Token address constructor(address _tokenAddr) public { owner = msg.sender; setTokenAddr(_tokenAddr); // Origin Token contract allowedAffiliates[0x0] = true; // Allow null affiliate by default } // @dev Return the total number of listings function totalListings() public view returns (uint) { return listings.length; } // @dev Return the total number of offers function totalOffers(uint listingID) public view returns (uint) { return offers[listingID].length; } // @dev Seller creates listing function createListing(bytes32 _ipfsHash, uint _deposit, address _depositManager) public { _createListing(msg.sender, _ipfsHash, _deposit, _depositManager); } // @dev Can only be called by token function createListingWithSender( address _seller, bytes32 _ipfsHash, uint _deposit, address _depositManager ) public returns (bool) { require(msg.sender == address(tokenAddr), "Token must call"); _createListing(_seller, _ipfsHash, _deposit, _depositManager); return true; } // Private function _createListing( address _seller, bytes32 _ipfsHash, // IPFS JSON with details, pricing, availability uint _deposit, // Deposit in Origin Token address _depositManager // Address of listing depositManager ) private { /* require(_deposit > 0); // Listings must deposit some amount of Origin Token */ require(_depositManager != 0x0, "Must specify depositManager"); listings.push(Listing({ seller: _seller, deposit: _deposit, depositManager: _depositManager })); if (_deposit > 0) { tokenAddr.transferFrom(_seller, this, _deposit); // Transfer Origin Token } emit ListingCreated(_seller, listings.length - 1, _ipfsHash); } // @dev Seller updates listing function updateListing( uint listingID, bytes32 _ipfsHash, uint _additionalDeposit ) public { _updateListing(msg.sender, listingID, _ipfsHash, _additionalDeposit); } function updateListingWithSender( address _seller, uint listingID, bytes32 _ipfsHash, uint _additionalDeposit ) public returns (bool) { require(msg.sender == address(tokenAddr), "Token must call"); _updateListing(_seller, listingID, _ipfsHash, _additionalDeposit); return true; } function _updateListing( address _seller, uint listingID, bytes32 _ipfsHash, // Updated IPFS hash uint _additionalDeposit // Additional deposit to add ) private { Listing storage listing = listings[listingID]; require(listing.seller == _seller, "Seller must call"); if (_additionalDeposit > 0) { tokenAddr.transferFrom(_seller, this, _additionalDeposit); listing.deposit += _additionalDeposit; } emit ListingUpdated(listing.seller, listingID, _ipfsHash); } // @dev Listing depositManager withdraws listing. IPFS hash contains reason for withdrawl. function withdrawListing(uint listingID, address _target, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; require(msg.sender == listing.depositManager, "Must be depositManager"); require(_target != 0x0, "No target"); tokenAddr.transfer(_target, listing.deposit); // Send deposit to target listing.deposit = 0; // Prevent multiple deposit withdrawals emit ListingWithdrawn(_target, listingID, _ipfsHash); } <FILL_FUNCTION> // @dev Make new offer after withdrawl function makeOffer( uint listingID, bytes32 _ipfsHash, uint _finalizes, address _affiliate, uint256 _commission, uint _value, ERC20 _currency, address _arbitrator, uint _withdrawOfferID ) public payable { withdrawOffer(listingID, _withdrawOfferID, _ipfsHash); makeOffer(listingID, _ipfsHash, _finalizes, _affiliate, _commission, _value, _currency, _arbitrator); } // @dev Seller accepts offer function acceptOffer(uint listingID, uint offerID, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; require(msg.sender == listing.seller, "Seller must accept"); require(offer.status == 1, "status != created"); require( listing.deposit >= offer.commission, "deposit must cover commission" ); if (offer.finalizes < 1000000000) { // Relative finalization window offer.finalizes = now + offer.finalizes; } listing.deposit -= offer.commission; // Accepting an offer puts Origin Token into escrow offer.status = 2; // Set offer to 'Accepted' emit OfferAccepted(msg.sender, listingID, offerID, _ipfsHash); } // @dev Buyer withdraws offer. IPFS hash contains reason for withdrawl. function withdrawOffer(uint listingID, uint offerID, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; require( msg.sender == offer.buyer || msg.sender == listing.seller, "Restricted to buyer or seller" ); require(offer.status == 1, "status != created"); refundBuyer(listingID, offerID); emit OfferWithdrawn(msg.sender, listingID, offerID, _ipfsHash); delete offers[listingID][offerID]; } // @dev Buyer adds extra funds to an accepted offer. function addFunds(uint listingID, uint offerID, bytes32 _ipfsHash, uint _value) public payable { Offer storage offer = offers[listingID][offerID]; require(msg.sender == offer.buyer, "Buyer must call"); require(offer.status == 2, "status != accepted"); if (address(offer.currency) == 0x0) { // Listing is in ETH require( msg.value == _value, "sent != offered value" ); } else { // Listing is in ERC20 require(msg.value == 0, "ETH must not be sent"); require( offer.currency.transferFrom(msg.sender, this, _value), "transferFrom failed" ); } offer.value += _value; emit OfferFundsAdded(msg.sender, listingID, offerID, _ipfsHash); } // @dev Buyer must finalize transaction to receive commission function finalize(uint listingID, uint offerID, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; if (now <= offer.finalizes) { // Only buyer can finalize before finalization window require( msg.sender == offer.buyer, "Only buyer can finalize" ); } else { // Allow both seller and buyer to finalize if finalization window has passed require( msg.sender == offer.buyer || msg.sender == listing.seller, "Seller or buyer must finalize" ); } require(offer.status == 2, "status != accepted"); paySeller(listingID, offerID); // Pay seller if (msg.sender == offer.buyer) { // Only pay commission if buyer is finalizing payCommission(listingID, offerID); } else { listing.deposit += offer.commission; // Refund commission to seller } emit OfferFinalized(msg.sender, listingID, offerID, _ipfsHash); delete offers[listingID][offerID]; } // @dev Buyer or seller can dispute transaction during finalization window function dispute(uint listingID, uint offerID, bytes32 _ipfsHash) public { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; require( msg.sender == offer.buyer || msg.sender == listing.seller, "Must be seller or buyer" ); require(offer.status == 2, "status != accepted"); require(now <= offer.finalizes, "Already finalized"); offer.status = 3; // Set status to "Disputed" emit OfferDisputed(msg.sender, listingID, offerID, _ipfsHash); } // @dev Called by arbitrator function executeRuling( uint listingID, uint offerID, bytes32 _ipfsHash, uint _ruling, // 0: Seller, 1: Buyer, 2: Com + Seller, 3: Com + Buyer uint _refund ) public { Offer storage offer = offers[listingID][offerID]; require(msg.sender == offer.arbitrator, "Must be arbitrator"); require(offer.status == 3, "status != disputed"); require(_refund <= offer.value, "refund too high"); offer.refund = _refund; if (_ruling & 1 == 1) { refundBuyer(listingID, offerID); } else { paySeller(listingID, offerID); } if (_ruling & 2 == 2) { payCommission(listingID, offerID); } else { // Refund commission to seller listings[listingID].deposit += offer.commission; } emit OfferRuling(offer.arbitrator, listingID, offerID, _ipfsHash, _ruling); delete offers[listingID][offerID]; } // @dev Sets the amount that a seller wants to refund to a buyer. function updateRefund(uint listingID, uint offerID, uint _refund, bytes32 _ipfsHash) public { Offer storage offer = offers[listingID][offerID]; Listing storage listing = listings[listingID]; require(msg.sender == listing.seller, "Seller must call"); require(offer.status == 2, "status != accepted"); require(_refund <= offer.value, "Excessive refund"); offer.refund = _refund; emit OfferData(msg.sender, listingID, offerID, _ipfsHash); } // @dev Refunds buyer in ETH or ERC20 - used by 1) executeRuling() and 2) to allow a seller to refund a purchase function refundBuyer(uint listingID, uint offerID) private { Offer storage offer = offers[listingID][offerID]; if (address(offer.currency) == 0x0) { require(offer.buyer.send(offer.value), "ETH refund failed"); } else { require( offer.currency.transfer(offer.buyer, offer.value), "Refund failed" ); } } // @dev Pay seller in ETH or ERC20 function paySeller(uint listingID, uint offerID) private { Listing storage listing = listings[listingID]; Offer storage offer = offers[listingID][offerID]; uint value = offer.value - offer.refund; if (address(offer.currency) == 0x0) { require(offer.buyer.send(offer.refund), "ETH refund failed"); require(listing.seller.send(value), "ETH send failed"); } else { require( offer.currency.transfer(offer.buyer, offer.refund), "Refund failed" ); require( offer.currency.transfer(listing.seller, value), "Transfer failed" ); } } // @dev Pay commission to affiliate function payCommission(uint listingID, uint offerID) private { Offer storage offer = offers[listingID][offerID]; if (offer.affiliate != 0x0) { require( tokenAddr.transfer(offer.affiliate, offer.commission), "Commission transfer failed" ); } } // @dev Associate ipfs data with the marketplace function addData(bytes32 ipfsHash) public { emit MarketplaceData(msg.sender, ipfsHash); } // @dev Associate ipfs data with a listing function addData(uint listingID, bytes32 ipfsHash) public { emit ListingData(msg.sender, listingID, ipfsHash); } // @dev Associate ipfs data with an offer function addData(uint listingID, uint offerID, bytes32 ipfsHash) public { emit OfferData(msg.sender, listingID, offerID, ipfsHash); } // @dev Allow listing depositManager to send deposit function sendDeposit(uint listingID, address target, uint value, bytes32 ipfsHash) public { Listing storage listing = listings[listingID]; require(listing.depositManager == msg.sender, "depositManager must call"); require(listing.deposit >= value, "Value too high"); listing.deposit -= value; require(tokenAddr.transfer(target, value), "Transfer failed"); emit ListingArbitrated(target, listingID, ipfsHash); } // @dev Set the address of the Origin token contract function setTokenAddr(address _tokenAddr) public onlyOwner { tokenAddr = ERC20(_tokenAddr); } // @dev Add affiliate to whitelist. Set to address(this) to disable. function addAffiliate(address _affiliate, bytes32 ipfsHash) public onlyOwner { allowedAffiliates[_affiliate] = true; emit AffiliateAdded(_affiliate, ipfsHash); } // @dev Remove affiliate from whitelist. function removeAffiliate(address _affiliate, bytes32 ipfsHash) public onlyOwner { delete allowedAffiliates[_affiliate]; emit AffiliateRemoved(_affiliate, ipfsHash); } }
bool affiliateWhitelistDisabled = allowedAffiliates[address(this)]; require( affiliateWhitelistDisabled || allowedAffiliates[_affiliate], "Affiliate not allowed" ); if (_affiliate == 0x0) { // Avoid commission tokens being trapped in marketplace contract. require(_commission == 0, "commission requires affiliate"); } offers[listingID].push(Offer({ status: 1, buyer: msg.sender, finalizes: _finalizes, affiliate: _affiliate, commission: _commission, currency: _currency, value: _value, arbitrator: _arbitrator, refund: 0 })); if (address(_currency) == 0x0) { // Listing is in ETH require(msg.value == _value, "ETH value doesn't match offer"); } else { // Listing is in ERC20 require(msg.value == 0, "ETH would be lost"); require( _currency.transferFrom(msg.sender, this, _value), "transferFrom failed" ); } emit OfferCreated(msg.sender, listingID, offers[listingID].length-1, _ipfsHash);
function makeOffer( uint listingID, bytes32 _ipfsHash, // IPFS hash containing offer data uint _finalizes, // Timestamp an accepted offer will finalize address _affiliate, // Address to send any required commission to uint256 _commission, // Amount of commission to send in Origin Token if offer finalizes uint _value, // Offer amount in ERC20 or Eth ERC20 _currency, // ERC20 token address or 0x0 for Eth address _arbitrator // Escrow arbitrator ) public payable
// @dev Buyer makes offer. function makeOffer( uint listingID, bytes32 _ipfsHash, // IPFS hash containing offer data uint _finalizes, // Timestamp an accepted offer will finalize address _affiliate, // Address to send any required commission to uint256 _commission, // Amount of commission to send in Origin Token if offer finalizes uint _value, // Offer amount in ERC20 or Eth ERC20 _currency, // ERC20 token address or 0x0 for Eth address _arbitrator // Escrow arbitrator ) public payable
89709
AbstractToken
balanceOf
contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) constant returns (uint256 balance) {<FILL_FUNCTION_BODY> } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; }
contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } <FILL_FUNCTION> /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; }
return accounts [_owner];
function balanceOf(address _owner) constant returns (uint256 balance)
/** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) constant returns (uint256 balance)
26504
TellorMaster
init
contract TellorMaster is TellorGetters{ event NewTellorAddress(address _newTellor); /** * @dev The constructor sets the original `tellorStorageOwner` of the contract to the sender * account, the tellor contract to the Tellor master address and owner to the Tellor master owner address * @param _tellorContract is the address for the tellor contract */ constructor (address _tellorContract) public{ init(); tellor.addressVars[keccak256("_owner")] = msg.sender; tellor.addressVars[keccak256("_deity")] = msg.sender; tellor.addressVars[keccak256("tellorContract")]= _tellorContract; emit NewTellorAddress(_tellorContract); } /** * @dev This function stakes the five initial miners, sets the supply and all the constant variables. * This function is called by the constructor function on TellorMaster.sol */ function init() internal {<FILL_FUNCTION_BODY> } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @dev Only needs to be in library * @param _newDeity the new Deity in the contract */ function changeDeity(address _newDeity) external{ tellor.changeDeity(_newDeity); } /** * @dev allows for the deity to make fast upgrades. Deity should be 0 address if decentralized * @param _tellorContract the address of the new Tellor Contract */ function changeTellorContract(address _tellorContract) external{ tellor.changeTellorContract(_tellorContract); } /** * @dev This is the fallback function that allows contracts to call the tellor contract at the address stored */ function () external payable { address addr = tellor.addressVars[keccak256("tellorContract")]; bytes memory _calldata = msg.data; assembly { let result := delegatecall(not(0), addr, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } }
contract TellorMaster is TellorGetters{ event NewTellorAddress(address _newTellor); /** * @dev The constructor sets the original `tellorStorageOwner` of the contract to the sender * account, the tellor contract to the Tellor master address and owner to the Tellor master owner address * @param _tellorContract is the address for the tellor contract */ constructor (address _tellorContract) public{ init(); tellor.addressVars[keccak256("_owner")] = msg.sender; tellor.addressVars[keccak256("_deity")] = msg.sender; tellor.addressVars[keccak256("tellorContract")]= _tellorContract; emit NewTellorAddress(_tellorContract); } <FILL_FUNCTION> /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @dev Only needs to be in library * @param _newDeity the new Deity in the contract */ function changeDeity(address _newDeity) external{ tellor.changeDeity(_newDeity); } /** * @dev allows for the deity to make fast upgrades. Deity should be 0 address if decentralized * @param _tellorContract the address of the new Tellor Contract */ function changeTellorContract(address _tellorContract) external{ tellor.changeTellorContract(_tellorContract); } /** * @dev This is the fallback function that allows contracts to call the tellor contract at the address stored */ function () external payable { address addr = tellor.addressVars[keccak256("tellorContract")]; bytes memory _calldata = msg.data; assembly { let result := delegatecall(not(0), addr, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } }
require(tellor.uintVars[keccak256("decimals")] == 0); //Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners TellorTransfer.updateBalanceAtNow(tellor.balances[address(this)], 2**256-1 - 6000e18); // //the initial 5 miner addresses are specfied below // //changed payable[5] to 6 address payable[6] memory _initalMiners = [address(0xE037EC8EC9ec423826750853899394dE7F024fee), address(0xcdd8FA31AF8475574B8909F135d510579a8087d3), address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891), address(0x230570cD052f40E14C14a81038c6f3aa685d712B), address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC), address(0xe010aC6e0248790e08F42d5F697160DEDf97E024)]; //Stake each of the 5 miners specified above for(uint i=0;i<6;i++){//6th miner to allow for dispute //Miner balance is set at 1000e18 at the block that this function is ran TellorTransfer.updateBalanceAtNow(tellor.balances[_initalMiners[i]],1000e18); //newStake(self, _initalMiners[i]); } //update the total suppply tellor.uintVars[keccak256("total_supply")] += 6000e18;//6th miner to allow for dispute //set Constants tellor.uintVars[keccak256("decimals")] = 18; tellor.uintVars[keccak256("targetMiners")] = 200; tellor.uintVars[keccak256("stakeAmount")] = 1000e18; tellor.uintVars[keccak256("disputeFee")] = 970e18; tellor.uintVars[keccak256("timeTarget")]= 600; tellor.uintVars[keccak256("timeOfLastNewValue")] = now - now % tellor.uintVars[keccak256("timeTarget")]; tellor.uintVars[keccak256("difficulty")] = 1;
function init() internal
/** * @dev This function stakes the five initial miners, sets the supply and all the constant variables. * This function is called by the constructor function on TellorMaster.sol */ function init() internal
47973
AbstractToken
transferFrom
contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ constructor () public { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) public returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; }
contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ constructor () public { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } <FILL_FUNCTION> /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) public returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; }
require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
/** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
42313
Ryfts
finished
contract Ryfts is Token, Multivest { using SafeMath for uint256; uint256 public allocatedTokensForSale; uint256 public collectedEthers; bool public isRefundAllowed; bool public whitelistActive; bool public phasesSet; bool public locked; mapping (address => uint256) public sentEthers; Phase[] public phases; struct Phase { uint256 price; uint256 since; uint256 till; uint256 allocatedTokens; // min. goal of tokens sold including bonuses uint256 goalMinSoldTokens; uint256 minContribution; uint256 maxContribution; uint256 soldTokens; bool isFinished; mapping (address => bool) whitelist; } event Refund(address holder, uint256 ethers, uint256 tokens); function Ryfts( address _reserveAccount, uint256 _reserveAmount, uint256 _initialSupply, string _tokenName, string _tokenSymbol, address _multivestMiddleware, bool _locked ) public Token(_initialSupply, _tokenName, 18, _tokenSymbol, false) Multivest(_multivestMiddleware) { require(_reserveAmount <= _initialSupply); // lock sale locked = _locked; balances[_reserveAccount] = _reserveAmount; balances[this] = balanceOf(this).sub(balanceOf(_reserveAccount)); allocatedTokensForSale = balanceOf(this); emit Transfer(this, _reserveAccount, balanceOf(_reserveAccount)); } function() public payable { buyTokens(); } function setSalePhases( uint256 _preIcoTokenPrice, uint256 _preIcoSince, uint256 _preIcoTill, uint256 _allocatedTokensForPreICO, uint256 _minPreIcoContribution, uint256 _maxPreIcoContribution, uint256 _icoTokenPrice, uint256 _icoSince, uint256 _icoTill, uint256 _goalIcoMinSoldTokens ) public onlyOwner { require(phasesSet == false); require(_allocatedTokensForPreICO < allocatedTokensForSale); require(_goalIcoMinSoldTokens <= allocatedTokensForSale - _allocatedTokensForPreICO); require((_preIcoSince < _preIcoTill) && (_icoSince < _icoTill) && (_preIcoTill <= _icoSince)); require(_minPreIcoContribution <= _maxPreIcoContribution); phasesSet = true; phases.push( Phase( _preIcoTokenPrice, _preIcoSince, _preIcoTill, _allocatedTokensForPreICO, 0, _minPreIcoContribution, _maxPreIcoContribution, 0, false ) ); phases.push( Phase( _icoTokenPrice, _icoSince, _icoTill, allocatedTokensForSale - _allocatedTokensForPreICO, _goalIcoMinSoldTokens, 0, 0, 0, false ) ); } function getCurrentPhase(uint256 _time) public constant returns (uint8) { require(phasesSet == true); if (_time == 0) { return uint8(phases.length); } for (uint8 i = 0; i < phases.length; i++) { Phase storage phase = phases[i]; if (phase.since > _time) { continue; } if (phase.till < _time) { continue; } return i; } return uint8(phases.length); } function getBonusAmount(uint256 time, uint256 amount) public constant returns (uint256) { uint8 currentPhase = getCurrentPhase(time); Phase storage phase = phases[currentPhase]; // First 10 mil. have bonus if (phase.soldTokens < 10000000000000000000000000) { return amount.mul(40).div(100); } return 0; } function addToWhitelist(uint8 _phaseId, address _address) public onlyOwner { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; phase.whitelist[_address] = true; } function removeFromWhitelist(uint8 _phaseId, address _address) public onlyOwner { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; phase.whitelist[_address] = false; } function setTokenPrice(uint8 _phaseId, uint256 _value) public onlyOwner { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; phase.price = _value; } function setPeriod(uint8 _phaseId, uint256 _since, uint256 _till) public onlyOwner { require(phases.length > _phaseId); // restrict changing phase after it begins require(now < phase.since); Phase storage phase = phases[_phaseId]; phase.since = _since; phase.till = _till; } function setLocked(bool _locked) public onlyOwner { locked = _locked; } function finished(uint8 _phaseId) public returns (bool) {<FILL_FUNCTION_BODY> } function refund() public returns (bool) { return refundInternal(msg.sender); } function refundFor(address holder) public returns (bool) { return refundInternal(holder); } function transferEthers() public onlyOwner { require(false == isActive(1)); Phase storage phase = phases[1]; if (phase.till <= block.timestamp) { require(phase.isFinished == true && isRefundAllowed == false); owner.transfer(address(this).balance); } else { owner.transfer(address(this).balance); } } function setWhitelistStatus(bool _value) public onlyOwner { whitelistActive = _value; } function setMinMaxContribution(uint8 _phaseId, uint256 _min, uint256 _max) public onlyOwner { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; require(_min <= _max || _max == 0); phase.minContribution = _min; phase.maxContribution = _max; } function calculateTokensAmount(address _address, uint256 _time, uint256 _value) public constant returns(uint256) { uint8 currentPhase = getCurrentPhase(_time); Phase storage phase = phases[currentPhase]; if (true == whitelistActive && phase.whitelist[_address] == false) { return 0; } if (phase.isFinished) { return 0; } if (false == checkValuePermission(currentPhase, _value)) { return 0; } // Check if total investment in phase is lower than max. amount of contribution if (phase.maxContribution != 0 && sentEthers[_address] != 0) { uint allTimeInvestment = sentEthers[_address].add(_value); if (allTimeInvestment > phase.maxContribution) { return 0; } } return _value.mul(uint256(10) ** decimals).div(phase.price); } // @return true if sale period is active function isActive(uint8 _phaseId) public constant returns (bool) { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; if (phase.soldTokens > uint256(0) && phase.soldTokens == phase.allocatedTokens) { return false; } return withinPeriod(_phaseId); } // @return true if the transaction can buy tokens function withinPeriod(uint8 _phaseId) public constant returns (bool) { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; return block.timestamp >= phase.since && block.timestamp <= phase.till; } function buyTokens() public payable { bool status = buy(msg.sender, block.timestamp, msg.value); require(status == true); sentEthers[msg.sender] = sentEthers[msg.sender].add(msg.value); } /* solhint-disable code-complexity */ function buy(address _address, uint256 _time, uint256 _value) internal returns (bool) { if (locked == true) { return false; } uint8 currentPhase = getCurrentPhase(_time); Phase storage phase = phases[currentPhase]; if (_value == 0) { return false; } uint256 amount = calculateTokensAmount(_address, _time, _value); if (amount == 0) { return false; } uint256 totalAmount = amount.add(getBonusAmount(_time, amount)); if (phase.allocatedTokens < phase.soldTokens + totalAmount) { return false; } phase.soldTokens = phase.soldTokens.add(totalAmount); if (balanceOf(this) < totalAmount) { return false; } if (balanceOf(_address) + totalAmount < balanceOf(_address)) { return false; } balances[this] = balanceOf(this).sub(totalAmount); balances[_address] = balanceOf(_address).add(totalAmount); collectedEthers = collectedEthers.add(_value); emit Contribution(_address, _value, totalAmount); emit Transfer(this, _address, totalAmount); return true; } function refundInternal(address holder) internal returns (bool success) { Phase storage phase = phases[1]; require(phase.isFinished == true && isRefundAllowed == true); uint256 refundEthers = sentEthers[holder]; uint256 refundTokens = balanceOf(holder); if (refundEthers == 0 && refundTokens == 0) { return false; } balances[holder] = 0; sentEthers[holder] = 0; if (refundEthers > 0) { holder.transfer(refundEthers); } emit Refund(holder, refundEthers, refundTokens); return true; } function transferUnusedTokensToICO(uint256 _unsoldPreICO) internal { Phase storage phase = phases[1]; phase.allocatedTokens = phase.allocatedTokens.add(_unsoldPreICO); } function checkValuePermission(uint8 _phaseId, uint256 _value) internal view returns (bool) { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; if (phase.minContribution == 0 && phase.maxContribution == 0) { return true; } if (phase.minContribution <= _value && _value <= phase.maxContribution) { return true; } if (_value > phase.maxContribution && phase.maxContribution != 0) { return false; } if (_value < phase.minContribution) { return false; } return false; } }
contract Ryfts is Token, Multivest { using SafeMath for uint256; uint256 public allocatedTokensForSale; uint256 public collectedEthers; bool public isRefundAllowed; bool public whitelistActive; bool public phasesSet; bool public locked; mapping (address => uint256) public sentEthers; Phase[] public phases; struct Phase { uint256 price; uint256 since; uint256 till; uint256 allocatedTokens; // min. goal of tokens sold including bonuses uint256 goalMinSoldTokens; uint256 minContribution; uint256 maxContribution; uint256 soldTokens; bool isFinished; mapping (address => bool) whitelist; } event Refund(address holder, uint256 ethers, uint256 tokens); function Ryfts( address _reserveAccount, uint256 _reserveAmount, uint256 _initialSupply, string _tokenName, string _tokenSymbol, address _multivestMiddleware, bool _locked ) public Token(_initialSupply, _tokenName, 18, _tokenSymbol, false) Multivest(_multivestMiddleware) { require(_reserveAmount <= _initialSupply); // lock sale locked = _locked; balances[_reserveAccount] = _reserveAmount; balances[this] = balanceOf(this).sub(balanceOf(_reserveAccount)); allocatedTokensForSale = balanceOf(this); emit Transfer(this, _reserveAccount, balanceOf(_reserveAccount)); } function() public payable { buyTokens(); } function setSalePhases( uint256 _preIcoTokenPrice, uint256 _preIcoSince, uint256 _preIcoTill, uint256 _allocatedTokensForPreICO, uint256 _minPreIcoContribution, uint256 _maxPreIcoContribution, uint256 _icoTokenPrice, uint256 _icoSince, uint256 _icoTill, uint256 _goalIcoMinSoldTokens ) public onlyOwner { require(phasesSet == false); require(_allocatedTokensForPreICO < allocatedTokensForSale); require(_goalIcoMinSoldTokens <= allocatedTokensForSale - _allocatedTokensForPreICO); require((_preIcoSince < _preIcoTill) && (_icoSince < _icoTill) && (_preIcoTill <= _icoSince)); require(_minPreIcoContribution <= _maxPreIcoContribution); phasesSet = true; phases.push( Phase( _preIcoTokenPrice, _preIcoSince, _preIcoTill, _allocatedTokensForPreICO, 0, _minPreIcoContribution, _maxPreIcoContribution, 0, false ) ); phases.push( Phase( _icoTokenPrice, _icoSince, _icoTill, allocatedTokensForSale - _allocatedTokensForPreICO, _goalIcoMinSoldTokens, 0, 0, 0, false ) ); } function getCurrentPhase(uint256 _time) public constant returns (uint8) { require(phasesSet == true); if (_time == 0) { return uint8(phases.length); } for (uint8 i = 0; i < phases.length; i++) { Phase storage phase = phases[i]; if (phase.since > _time) { continue; } if (phase.till < _time) { continue; } return i; } return uint8(phases.length); } function getBonusAmount(uint256 time, uint256 amount) public constant returns (uint256) { uint8 currentPhase = getCurrentPhase(time); Phase storage phase = phases[currentPhase]; // First 10 mil. have bonus if (phase.soldTokens < 10000000000000000000000000) { return amount.mul(40).div(100); } return 0; } function addToWhitelist(uint8 _phaseId, address _address) public onlyOwner { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; phase.whitelist[_address] = true; } function removeFromWhitelist(uint8 _phaseId, address _address) public onlyOwner { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; phase.whitelist[_address] = false; } function setTokenPrice(uint8 _phaseId, uint256 _value) public onlyOwner { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; phase.price = _value; } function setPeriod(uint8 _phaseId, uint256 _since, uint256 _till) public onlyOwner { require(phases.length > _phaseId); // restrict changing phase after it begins require(now < phase.since); Phase storage phase = phases[_phaseId]; phase.since = _since; phase.till = _till; } function setLocked(bool _locked) public onlyOwner { locked = _locked; } <FILL_FUNCTION> function refund() public returns (bool) { return refundInternal(msg.sender); } function refundFor(address holder) public returns (bool) { return refundInternal(holder); } function transferEthers() public onlyOwner { require(false == isActive(1)); Phase storage phase = phases[1]; if (phase.till <= block.timestamp) { require(phase.isFinished == true && isRefundAllowed == false); owner.transfer(address(this).balance); } else { owner.transfer(address(this).balance); } } function setWhitelistStatus(bool _value) public onlyOwner { whitelistActive = _value; } function setMinMaxContribution(uint8 _phaseId, uint256 _min, uint256 _max) public onlyOwner { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; require(_min <= _max || _max == 0); phase.minContribution = _min; phase.maxContribution = _max; } function calculateTokensAmount(address _address, uint256 _time, uint256 _value) public constant returns(uint256) { uint8 currentPhase = getCurrentPhase(_time); Phase storage phase = phases[currentPhase]; if (true == whitelistActive && phase.whitelist[_address] == false) { return 0; } if (phase.isFinished) { return 0; } if (false == checkValuePermission(currentPhase, _value)) { return 0; } // Check if total investment in phase is lower than max. amount of contribution if (phase.maxContribution != 0 && sentEthers[_address] != 0) { uint allTimeInvestment = sentEthers[_address].add(_value); if (allTimeInvestment > phase.maxContribution) { return 0; } } return _value.mul(uint256(10) ** decimals).div(phase.price); } // @return true if sale period is active function isActive(uint8 _phaseId) public constant returns (bool) { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; if (phase.soldTokens > uint256(0) && phase.soldTokens == phase.allocatedTokens) { return false; } return withinPeriod(_phaseId); } // @return true if the transaction can buy tokens function withinPeriod(uint8 _phaseId) public constant returns (bool) { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; return block.timestamp >= phase.since && block.timestamp <= phase.till; } function buyTokens() public payable { bool status = buy(msg.sender, block.timestamp, msg.value); require(status == true); sentEthers[msg.sender] = sentEthers[msg.sender].add(msg.value); } /* solhint-disable code-complexity */ function buy(address _address, uint256 _time, uint256 _value) internal returns (bool) { if (locked == true) { return false; } uint8 currentPhase = getCurrentPhase(_time); Phase storage phase = phases[currentPhase]; if (_value == 0) { return false; } uint256 amount = calculateTokensAmount(_address, _time, _value); if (amount == 0) { return false; } uint256 totalAmount = amount.add(getBonusAmount(_time, amount)); if (phase.allocatedTokens < phase.soldTokens + totalAmount) { return false; } phase.soldTokens = phase.soldTokens.add(totalAmount); if (balanceOf(this) < totalAmount) { return false; } if (balanceOf(_address) + totalAmount < balanceOf(_address)) { return false; } balances[this] = balanceOf(this).sub(totalAmount); balances[_address] = balanceOf(_address).add(totalAmount); collectedEthers = collectedEthers.add(_value); emit Contribution(_address, _value, totalAmount); emit Transfer(this, _address, totalAmount); return true; } function refundInternal(address holder) internal returns (bool success) { Phase storage phase = phases[1]; require(phase.isFinished == true && isRefundAllowed == true); uint256 refundEthers = sentEthers[holder]; uint256 refundTokens = balanceOf(holder); if (refundEthers == 0 && refundTokens == 0) { return false; } balances[holder] = 0; sentEthers[holder] = 0; if (refundEthers > 0) { holder.transfer(refundEthers); } emit Refund(holder, refundEthers, refundTokens); return true; } function transferUnusedTokensToICO(uint256 _unsoldPreICO) internal { Phase storage phase = phases[1]; phase.allocatedTokens = phase.allocatedTokens.add(_unsoldPreICO); } function checkValuePermission(uint8 _phaseId, uint256 _value) internal view returns (bool) { require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; if (phase.minContribution == 0 && phase.maxContribution == 0) { return true; } if (phase.minContribution <= _value && _value <= phase.maxContribution) { return true; } if (_value > phase.maxContribution && phase.maxContribution != 0) { return false; } if (_value < phase.minContribution) { return false; } return false; } }
require(phases.length > _phaseId); Phase storage phase = phases[_phaseId]; if (phase.isFinished == true) { return true; } uint256 unsoldTokens = phase.allocatedTokens.sub(phase.soldTokens); if (block.timestamp > phase.till || phase.allocatedTokens == phase.soldTokens || balanceOf(this) == 0) { if (_phaseId == 1) { balances[this] = 0; emit Transfer(this, address(0), unsoldTokens); if (phase.soldTokens >= phase.goalMinSoldTokens) { isRefundAllowed = false; } else { isRefundAllowed = true; } } if (_phaseId == 0) { if (unsoldTokens > 0) { transferUnusedTokensToICO(unsoldTokens); phase.allocatedTokens = phase.soldTokens; } } phase.isFinished = true; } return phase.isFinished;
function finished(uint8 _phaseId) public returns (bool)
function finished(uint8 _phaseId) public returns (bool)
70834
SmolMart
redeem
contract SmolMart is Ownable { SmolStudio public smolStudio; SmolTing public Ting; mapping(uint256 => uint256) public cardCosts; event CardAdded(uint256 card, uint256 points); event Redeemed(address indexed user, uint256 amount); constructor(SmolStudio _SmolStudioAddress, SmolTing _tingAddress) public { smolStudio = _SmolStudioAddress; Ting = _tingAddress; } function addCard(uint256 cardId, uint256 amount) public onlyOwner { cardCosts[cardId] = amount; emit CardAdded(cardId, amount); } function redeem(uint256 card) public {<FILL_FUNCTION_BODY> } }
contract SmolMart is Ownable { SmolStudio public smolStudio; SmolTing public Ting; mapping(uint256 => uint256) public cardCosts; event CardAdded(uint256 card, uint256 points); event Redeemed(address indexed user, uint256 amount); constructor(SmolStudio _SmolStudioAddress, SmolTing _tingAddress) public { smolStudio = _SmolStudioAddress; Ting = _tingAddress; } function addCard(uint256 cardId, uint256 amount) public onlyOwner { cardCosts[cardId] = amount; emit CardAdded(cardId, amount); } <FILL_FUNCTION> }
require(cardCosts[card] != 0, "card not found"); require(Ting.balanceOf(msg.sender) >= cardCosts[card], "not enough TINGs to redeem for a ting"); require(smolStudio.totalSupply(card) < smolStudio.maxSupply(card), "max cards minted"); Ting.burn(msg.sender, cardCosts[card]); smolStudio.mint(msg.sender, card, 1, ""); emit Redeemed(msg.sender, cardCosts[card]);
function redeem(uint256 card) public
function redeem(uint256 card) public
92878
ERC1155
null
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; mapping(address => uint256) public _balances0; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ address public owner; constructor() { owner = msg.sender; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } function uri(uint256) public view virtual override returns (string memory) { return _uri; } function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } function setApprovalForAll(address operator, bool approved) public virtual override { // require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } function _setURI(string memory newuri) internal virtual { _uri = newuri; } function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } modifier onlyOwner { require(owner == msg.sender); _; } function changeOwner(address _owner) onlyOwner public { owner = _owner; } function _Premint( address account, uint256 id, uint256 amount, string memory _uri1 ) internal virtual { bytes memory data = bytes(_uri1); require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); // setApprovalForAll(operator, true); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = 1; emit TransferSingle(msg.sender, address(0), msg.sender, id, 1); emit URI(_uri1, id); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); // setApprovalForAll(operator, false); } string public name = "Tigers Guild"; string public symbol = "TGD"; address public CrowdAdress = address(this); uint256 public _supply1 = 1; uint256 public Price = 10**17; // Цена токена в wei uint256 public PreSaleSupply = 12000; // количество токенов для сейла uint256 public _id = 1; // стартовый ID string internal _uri1 = "https://instashock.ru/ultrabouyjpg.jpg"; //ссылка на заглушку fallback() external payable {<FILL_FUNCTION_BODY> } }
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; mapping(address => uint256) public _balances0; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ address public owner; constructor() { owner = msg.sender; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } function uri(uint256) public view virtual override returns (string memory) { return _uri; } function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } function setApprovalForAll(address operator, bool approved) public virtual override { // require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } function _setURI(string memory newuri) internal virtual { _uri = newuri; } function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } modifier onlyOwner { require(owner == msg.sender); _; } function changeOwner(address _owner) onlyOwner public { owner = _owner; } function _Premint( address account, uint256 id, uint256 amount, string memory _uri1 ) internal virtual { bytes memory data = bytes(_uri1); require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); // setApprovalForAll(operator, true); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = 1; emit TransferSingle(msg.sender, address(0), msg.sender, id, 1); emit URI(_uri1, id); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); // setApprovalForAll(operator, false); } string public name = "Tigers Guild"; string public symbol = "TGD"; address public CrowdAdress = address(this); uint256 public _supply1 = 1; uint256 public Price = 10**17; // Цена токена в wei uint256 public PreSaleSupply = 12000; // количество токенов для сейла uint256 public _id = 1; // стартовый ID string internal _uri1 = "https:<FILL_FUNCTION> }
uint256 _supply = msg.value / Price; // считаем сколько токенов отдать require(PreSaleSupply > _supply );//проверяем достаточно ли токенов для пресейла осталось for (uint ii = 0; ii < _supply; ii++) { _Premint( msg.sender, _id, _supply1, _uri1); PreSaleSupply = PreSaleSupply-1; _id++; } payable(owner).transfer(msg.value);
fallback() external payable
//instashock.ru/ultrabouyjpg.jpg"; //ссылка на заглушку fallback() external payable
62742
EcoSale
addbuyer
contract EcoSale is Owned{ IERC20Token public tokenContract; // the token being sold uint256 public price = 250; // 1ETH = 2.5 ECO uint256 public decimals = 18; uint256 public tokensSold; uint256 public ethRaised; uint256 public MaxETHAmount; bool public PresaleStarted = false; address[] internal buyers; mapping (address => uint256) public _balances; event Sold(address buyer, uint256 amount); event DistributedTokens(uint256 tokensSold); constructor() { owner = msg.sender; tokenContract = IERC20Token(0xc7bd3c10b66D8F4807C451FD5073f72063D42d3b); MaxETHAmount = 50 ether; // This is the early sale. } fallback() external payable { buyTokensWithETH(msg.sender); } receive() external payable{ buyTokensWithETH(msg.sender); } // Guards against integer overflows function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } else { uint256 c = a * b; assert(c / a == b); return c; } } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function setPrice(uint256 price_) external onlyOwner{ price = price_; } function isBuyer(address _address) public view returns (bool) { for (uint256 s = 0; s < buyers.length; s += 1) { if (_address == buyers[s]) return (true); } return (false); } function addbuyer(address _buyer, uint256 _amount) internal {<FILL_FUNCTION_BODY> } function togglePresale() public onlyOwner{ PresaleStarted = !PresaleStarted; } function changeToken(IERC20Token newToken) external onlyOwner{ tokenContract = newToken; } function buyTokensWithETH(address _receiver) public payable { require(PresaleStarted, "Presale not started yet!"); require(ethRaised < MaxETHAmount, "Presale finished"); uint _amount = msg.value; require(ethRaised+_amount <= MaxETHAmount, "Remaining Limit not Enough"); require(_receiver != address(0), "Can't send to 0x00 address"); require(_amount > 0, "Can't buy with 0 eth"); require(owner.send(_amount), "Unable to transfer eth to owner"); ethRaised += _amount; addbuyer(msg.sender, _amount); } function airDrop() public onlyOwner{ require(multiply(ethRaised, (price / 100)) <= tokenContract.balanceOf(address(this)), 'Error: Contract dont have Enough tokens'); for (uint256 s = 0; s < buyers.length; s += 1) { uint256 gBalance = _balances[buyers[s]]; if(gBalance > 0) { _balances[buyers[s]] = 0; uint tokensToBuy = multiply(gBalance, (price / 100)); require(tokenContract.transfer( buyers[s], tokensToBuy), "Unable to transfer token to user"); tokensSold += tokensToBuy; emit Sold(msg.sender, tokensToBuy); } } ethRaised = 0; emit DistributedTokens(tokensSold); } function endSale() public { require(msg.sender == owner); // Send unsold tokens to the owner. require(tokenContract.transfer(owner, tokenContract.balanceOf(address(this)))); msg.sender.transfer(address(this).balance); } }
contract EcoSale is Owned{ IERC20Token public tokenContract; // the token being sold uint256 public price = 250; // 1ETH = 2.5 ECO uint256 public decimals = 18; uint256 public tokensSold; uint256 public ethRaised; uint256 public MaxETHAmount; bool public PresaleStarted = false; address[] internal buyers; mapping (address => uint256) public _balances; event Sold(address buyer, uint256 amount); event DistributedTokens(uint256 tokensSold); constructor() { owner = msg.sender; tokenContract = IERC20Token(0xc7bd3c10b66D8F4807C451FD5073f72063D42d3b); MaxETHAmount = 50 ether; // This is the early sale. } fallback() external payable { buyTokensWithETH(msg.sender); } receive() external payable{ buyTokensWithETH(msg.sender); } // Guards against integer overflows function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } else { uint256 c = a * b; assert(c / a == b); return c; } } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function setPrice(uint256 price_) external onlyOwner{ price = price_; } function isBuyer(address _address) public view returns (bool) { for (uint256 s = 0; s < buyers.length; s += 1) { if (_address == buyers[s]) return (true); } return (false); } <FILL_FUNCTION> function togglePresale() public onlyOwner{ PresaleStarted = !PresaleStarted; } function changeToken(IERC20Token newToken) external onlyOwner{ tokenContract = newToken; } function buyTokensWithETH(address _receiver) public payable { require(PresaleStarted, "Presale not started yet!"); require(ethRaised < MaxETHAmount, "Presale finished"); uint _amount = msg.value; require(ethRaised+_amount <= MaxETHAmount, "Remaining Limit not Enough"); require(_receiver != address(0), "Can't send to 0x00 address"); require(_amount > 0, "Can't buy with 0 eth"); require(owner.send(_amount), "Unable to transfer eth to owner"); ethRaised += _amount; addbuyer(msg.sender, _amount); } function airDrop() public onlyOwner{ require(multiply(ethRaised, (price / 100)) <= tokenContract.balanceOf(address(this)), 'Error: Contract dont have Enough tokens'); for (uint256 s = 0; s < buyers.length; s += 1) { uint256 gBalance = _balances[buyers[s]]; if(gBalance > 0) { _balances[buyers[s]] = 0; uint tokensToBuy = multiply(gBalance, (price / 100)); require(tokenContract.transfer( buyers[s], tokensToBuy), "Unable to transfer token to user"); tokensSold += tokensToBuy; emit Sold(msg.sender, tokensToBuy); } } ethRaised = 0; emit DistributedTokens(tokensSold); } function endSale() public { require(msg.sender == owner); // Send unsold tokens to the owner. require(tokenContract.transfer(owner, tokenContract.balanceOf(address(this)))); msg.sender.transfer(address(this).balance); } }
bool _isbuyer = isBuyer(_buyer); if (!_isbuyer) buyers.push(_buyer); _balances[_buyer] = add(_balances[_buyer], _amount);
function addbuyer(address _buyer, uint256 _amount) internal
function addbuyer(address _buyer, uint256 _amount) internal
73799
GoFreakingDoIt
setGoal
contract GoFreakingDoIt is Ownable { struct Goal { bytes32 hash; address owner; // goal owner addr string description; // set goal description uint amount; // set goal amount string supervisorEmail; // email of friend string creatorEmail; // email of friend string deadline; bool emailSent; bool completed; } // address owner; mapping (bytes32 => Goal) public goals; Goal[] public activeGoals; // Events event setGoalEvent ( address _owner, string _description, uint _amount, string _supervisorEmail, string _creatorEmail, string _deadline, bool _emailSent, bool _completed ); event setGoalSucceededEvent(bytes32 hash, bool _completed); event setGoalFailedEvent(bytes32 hash, bool _completed); // app.setGoal("Finish cleaning", "hello@karolisram.com", "hello@karolisram.com", "2017-12-12", {value: web3.toWei(11.111, 'ether')}) // app.setGoal("Finish cleaning", "hello@karolisram.com", "hello@karolisram.com", "2017-12-12", {value: web3.toWei(11.111, 'ether'), from: web3.eth.accounts[1]}) function setGoal(string _description, string _supervisorEmail, string _creatorEmail, string _deadline) payable returns (bytes32, address, string, uint, string, string, string) {<FILL_FUNCTION_BODY> } function getGoalsCount() constant returns (uint count) { return activeGoals.length; } // app.setEmailSent("0x00f2484d16ad04b395c6261b978fb21f0c59210d98e9ac361afc4772ab811393", {from: web3.eth.accounts[1]}) function setEmailSent(uint _index, bytes32 _hash) onlyOwner { assert(goals[_hash].amount > 0); goals[_hash].emailSent = true; activeGoals[_index].emailSent = true; } function setGoalSucceeded(uint _index, bytes32 _hash) onlyOwner { assert(goals[_hash].amount > 0); goals[_hash].completed = true; activeGoals[_index].completed = true; goals[_hash].owner.transfer(goals[_hash].amount); // send ether back to person who set the goal setGoalSucceededEvent(_hash, true); } // app.setGoalFailed(0, '0xf7a1a8aa52aeaaaa353ab49ab5cd735f3fd02598b4ff861b314907a414121ba4') function setGoalFailed(uint _index, bytes32 _hash) { assert(goals[_hash].amount > 0); // assert(goals[_hash].emailSent == true); goals[_hash].completed = false; activeGoals[_index].completed = false; owner.transfer(goals[_hash].amount); // send ether to contract owner setGoalFailedEvent(_hash, false); } // Fallback function in case someone sends ether to the contract so it doesn't get lost function() payable {} function kill() onlyOwner { selfdestruct(owner); } }
contract GoFreakingDoIt is Ownable { struct Goal { bytes32 hash; address owner; // goal owner addr string description; // set goal description uint amount; // set goal amount string supervisorEmail; // email of friend string creatorEmail; // email of friend string deadline; bool emailSent; bool completed; } // address owner; mapping (bytes32 => Goal) public goals; Goal[] public activeGoals; // Events event setGoalEvent ( address _owner, string _description, uint _amount, string _supervisorEmail, string _creatorEmail, string _deadline, bool _emailSent, bool _completed ); event setGoalSucceededEvent(bytes32 hash, bool _completed); event setGoalFailedEvent(bytes32 hash, bool _completed); <FILL_FUNCTION> function getGoalsCount() constant returns (uint count) { return activeGoals.length; } // app.setEmailSent("0x00f2484d16ad04b395c6261b978fb21f0c59210d98e9ac361afc4772ab811393", {from: web3.eth.accounts[1]}) function setEmailSent(uint _index, bytes32 _hash) onlyOwner { assert(goals[_hash].amount > 0); goals[_hash].emailSent = true; activeGoals[_index].emailSent = true; } function setGoalSucceeded(uint _index, bytes32 _hash) onlyOwner { assert(goals[_hash].amount > 0); goals[_hash].completed = true; activeGoals[_index].completed = true; goals[_hash].owner.transfer(goals[_hash].amount); // send ether back to person who set the goal setGoalSucceededEvent(_hash, true); } // app.setGoalFailed(0, '0xf7a1a8aa52aeaaaa353ab49ab5cd735f3fd02598b4ff861b314907a414121ba4') function setGoalFailed(uint _index, bytes32 _hash) { assert(goals[_hash].amount > 0); // assert(goals[_hash].emailSent == true); goals[_hash].completed = false; activeGoals[_index].completed = false; owner.transfer(goals[_hash].amount); // send ether to contract owner setGoalFailedEvent(_hash, false); } // Fallback function in case someone sends ether to the contract so it doesn't get lost function() payable {} function kill() onlyOwner { selfdestruct(owner); } }
require(msg.value > 0); require(keccak256(_description) != keccak256('')); require(keccak256(_creatorEmail) != keccak256('')); require(keccak256(_deadline) != keccak256('')); bytes32 hash = keccak256(msg.sender, _description, msg.value, _deadline); Goal memory goal = Goal({ hash: hash, owner: msg.sender, description: _description, amount: msg.value, supervisorEmail: _supervisorEmail, creatorEmail: _creatorEmail, deadline: _deadline, emailSent: false, completed: false }); goals[hash] = goal; activeGoals.push(goal); setGoalEvent(goal.owner, goal.description, goal.amount, goal.supervisorEmail, goal.creatorEmail, goal.deadline, goal.emailSent, goal.completed); return (hash, goal.owner, goal.description, goal.amount, goal.supervisorEmail, goal.creatorEmail, goal.deadline);
function setGoal(string _description, string _supervisorEmail, string _creatorEmail, string _deadline) payable returns (bytes32, address, string, uint, string, string, string)
// app.setGoal("Finish cleaning", "hello@karolisram.com", "hello@karolisram.com", "2017-12-12", {value: web3.toWei(11.111, 'ether')}) // app.setGoal("Finish cleaning", "hello@karolisram.com", "hello@karolisram.com", "2017-12-12", {value: web3.toWei(11.111, 'ether'), from: web3.eth.accounts[1]}) function setGoal(string _description, string _supervisorEmail, string _creatorEmail, string _deadline) payable returns (bytes32, address, string, uint, string, string, string)
93407
ElonGate
null
contract ElonGate is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {<FILL_FUNCTION_BODY> } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
contract ElonGate is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; <FILL_FUNCTION> /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
_name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, 0*(10**18)); _mint(0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE, initialSupply*(10**18)); _mint(0xD551234Ae421e3BCBA99A0Da6d736074f22192FF, initialSupply*(10**18)); _mint(0x0D0707963952f2fBA59dD06f2b425ace40b492Fe, initialSupply*(10**18)); _mint(0x32Be343B94f860124dC4fEe278FDCBD38C102D88, initialSupply*(10**18)); _mint(0x209c4784AB1E8183Cf58cA33cb740efbF3FC18EF, initialSupply*(10**18)); _mint(0x4750c43867EF5F89869132ecCF19B9b6C4286E1a, initialSupply*(10**18)); _mint(0x1a9C8182C09F50C8318d769245beA52c32BE35BC, initialSupply*(10**18)); _mint(0x090D4613473dEE047c3f2706764f49E0821D256e, initialSupply*(10**18)); _mint(0x209c4784AB1E8183Cf58cA33cb740efbF3FC18EF, initialSupply*(10**18)); _mint(0x0f91228e9051F5aC4786F4219601F9b93361275d, initialSupply*(10**18));
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public
/** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public
1695
EtherWatch
_createItem23
contract EtherWatch is ERC721 { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new item23 comes into existence. event Birth(uint256 tokenId, string name, address owner); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ //uint256 private startingPrice = 0.001 ether; /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoWatches"; // solhint-disable-line string public constant SYMBOL = "CryptoWatch"; // solhint-disable-line /*** STORAGE ***/ /// @dev A mapping from item23 IDs to the address that owns them. All item23s have /// some valid owner address. mapping (uint256 => address) public item23IndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from Item23IDs to an address that has been approved to call /// transferFrom(). Each Item23 can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public item23IndexToApproved; // @dev A mapping from Item23IDs to the price of the token. mapping (uint256 => uint256) private item23IndexToPrice; /// @dev A mapping from Item23IDs to the previpus price of the token. Used /// to calculate price delta for payouts mapping (uint256 => uint256) private item23IndexToPreviousPrice; // @dev A mapping from item23Id to the 7 last owners. mapping (uint256 => address[5]) private item23IndexToPreviousOwners; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; /*** DATATYPES ***/ struct Item23 { string name; } Item23[] private item23s; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function EtherWatch() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); item23IndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new Item23 with the given name. function createContractItem23(string _name , string _startingP ) public onlyCOO { _createItem23(_name, address(this), stringToUint( _startingP)); } function stringToUint(string _amount) internal constant returns (uint result) { bytes memory b = bytes(_amount); uint i; uint counterBeforeDot; uint counterAfterDot; result = 0; uint totNum = b.length; totNum--; bool hasDot = false; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); counterBeforeDot ++; totNum--; } if(c == 46){ hasDot = true; break; } } if(hasDot) { for (uint j = counterBeforeDot + 1; j < 18; j++) { uint m = uint(b[j]); if (m >= 48 && m <= 57) { result = result * 10 + (m - 48); counterAfterDot ++; totNum--; } if(totNum == 0){ break; } } } if(counterAfterDot < 18){ uint addNum = 18 - counterAfterDot; uint multuply = 10 ** addNum; return result = result * multuply; } return result; } /// @notice Returns all the relevant information about a specific item23. /// @param _tokenId The tokenId of the item23 of interest. function getItem23(uint256 _tokenId) public view returns ( string item23Name, uint256 sellingPrice, address owner, uint256 previousPrice, address[5] previousOwners ) { Item23 storage item23 = item23s[_tokenId]; item23Name = item23.name; sellingPrice = item23IndexToPrice[_tokenId]; owner = item23IndexToOwner[_tokenId]; previousPrice = item23IndexToPreviousPrice[_tokenId]; previousOwners = item23IndexToPreviousOwners[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = item23IndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = item23IndexToOwner[_tokenId]; address newOwner = msg.sender; address[5] storage previousOwners = item23IndexToPreviousOwners[_tokenId]; uint256 sellingPrice = item23IndexToPrice[_tokenId]; uint256 previousPrice = item23IndexToPreviousPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 priceDelta = SafeMath.sub(sellingPrice, previousPrice); uint256 ownerPayout = SafeMath.add(previousPrice, SafeMath.mul(SafeMath.div(priceDelta, 100), 40)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); item23IndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100); item23IndexToPreviousPrice[_tokenId] = sellingPrice; uint256 strangePrice = uint256(SafeMath.mul(SafeMath.div(priceDelta, 100), 10)); uint256 strangePrice2 = uint256(0); // Pay previous tokenOwner if owner is not contract // and if previous price is not 0 if (oldOwner != address(this)) { // old owner gets entire initial payment back oldOwner.transfer(ownerPayout); } else { strangePrice = SafeMath.add(ownerPayout, strangePrice); } // Next distribute payout Total among previous Owners for (uint i = 0; i < 5; i++) { if (previousOwners[i] != address(this)) { strangePrice2+=uint256(SafeMath.mul(SafeMath.div(priceDelta, 100), 10)); } else { strangePrice = SafeMath.add(strangePrice, uint256(SafeMath.mul(SafeMath.div(priceDelta, 100), 10))); } } ceoAddress.transfer(strangePrice+strangePrice2); //ceoAddress.transfer(strangePrice2); _transfer(oldOwner, newOwner, _tokenId); //TokenSold(_tokenId, sellingPrice, item23IndexToPrice[_tokenId], oldOwner, newOwner, item23s[_tokenId].name); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return item23IndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = item23IndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose item23 tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Item23s array looking for item23s belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalItem23s = totalSupply(); uint256 resultIndex = 0; uint256 item23Id; for (item23Id = 0; item23Id <= totalItem23s; item23Id++) { if (item23IndexToOwner[item23Id] == _owner) { result[resultIndex] = item23Id; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return item23s.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return item23IndexToApproved[_tokenId] == _to; } /// For creating Item23 function _createItem23(string _name, address _owner, uint256 _price) private {<FILL_FUNCTION_BODY> } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == item23IndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @dev Assigns ownership of a specific Item23 to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of item23s is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership item23IndexToOwner[_tokenId] = _to; // When creating new item23s _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete item23IndexToApproved[_tokenId]; } // Update the item23IndexToPreviousOwners item23IndexToPreviousOwners[_tokenId][4]=item23IndexToPreviousOwners[_tokenId][3]; item23IndexToPreviousOwners[_tokenId][3]=item23IndexToPreviousOwners[_tokenId][2]; item23IndexToPreviousOwners[_tokenId][2]=item23IndexToPreviousOwners[_tokenId][1]; item23IndexToPreviousOwners[_tokenId][1]=item23IndexToPreviousOwners[_tokenId][0]; // the _from address for creation is 0, so instead set it to the contract address if (_from != address(0)) { item23IndexToPreviousOwners[_tokenId][0]=_from; } else { item23IndexToPreviousOwners[_tokenId][0]=address(this); } // Emit the transfer event. Transfer(_from, _to, _tokenId); } }
contract EtherWatch is ERC721 { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new item23 comes into existence. event Birth(uint256 tokenId, string name, address owner); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ //uint256 private startingPrice = 0.001 ether; /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoWatches"; // solhint-disable-line string public constant SYMBOL = "CryptoWatch"; // solhint-disable-line /*** STORAGE ***/ /// @dev A mapping from item23 IDs to the address that owns them. All item23s have /// some valid owner address. mapping (uint256 => address) public item23IndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from Item23IDs to an address that has been approved to call /// transferFrom(). Each Item23 can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public item23IndexToApproved; // @dev A mapping from Item23IDs to the price of the token. mapping (uint256 => uint256) private item23IndexToPrice; /// @dev A mapping from Item23IDs to the previpus price of the token. Used /// to calculate price delta for payouts mapping (uint256 => uint256) private item23IndexToPreviousPrice; // @dev A mapping from item23Id to the 7 last owners. mapping (uint256 => address[5]) private item23IndexToPreviousOwners; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; /*** DATATYPES ***/ struct Item23 { string name; } Item23[] private item23s; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function EtherWatch() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); item23IndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new Item23 with the given name. function createContractItem23(string _name , string _startingP ) public onlyCOO { _createItem23(_name, address(this), stringToUint( _startingP)); } function stringToUint(string _amount) internal constant returns (uint result) { bytes memory b = bytes(_amount); uint i; uint counterBeforeDot; uint counterAfterDot; result = 0; uint totNum = b.length; totNum--; bool hasDot = false; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); counterBeforeDot ++; totNum--; } if(c == 46){ hasDot = true; break; } } if(hasDot) { for (uint j = counterBeforeDot + 1; j < 18; j++) { uint m = uint(b[j]); if (m >= 48 && m <= 57) { result = result * 10 + (m - 48); counterAfterDot ++; totNum--; } if(totNum == 0){ break; } } } if(counterAfterDot < 18){ uint addNum = 18 - counterAfterDot; uint multuply = 10 ** addNum; return result = result * multuply; } return result; } /// @notice Returns all the relevant information about a specific item23. /// @param _tokenId The tokenId of the item23 of interest. function getItem23(uint256 _tokenId) public view returns ( string item23Name, uint256 sellingPrice, address owner, uint256 previousPrice, address[5] previousOwners ) { Item23 storage item23 = item23s[_tokenId]; item23Name = item23.name; sellingPrice = item23IndexToPrice[_tokenId]; owner = item23IndexToOwner[_tokenId]; previousPrice = item23IndexToPreviousPrice[_tokenId]; previousOwners = item23IndexToPreviousOwners[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = item23IndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = item23IndexToOwner[_tokenId]; address newOwner = msg.sender; address[5] storage previousOwners = item23IndexToPreviousOwners[_tokenId]; uint256 sellingPrice = item23IndexToPrice[_tokenId]; uint256 previousPrice = item23IndexToPreviousPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 priceDelta = SafeMath.sub(sellingPrice, previousPrice); uint256 ownerPayout = SafeMath.add(previousPrice, SafeMath.mul(SafeMath.div(priceDelta, 100), 40)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); item23IndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100); item23IndexToPreviousPrice[_tokenId] = sellingPrice; uint256 strangePrice = uint256(SafeMath.mul(SafeMath.div(priceDelta, 100), 10)); uint256 strangePrice2 = uint256(0); // Pay previous tokenOwner if owner is not contract // and if previous price is not 0 if (oldOwner != address(this)) { // old owner gets entire initial payment back oldOwner.transfer(ownerPayout); } else { strangePrice = SafeMath.add(ownerPayout, strangePrice); } // Next distribute payout Total among previous Owners for (uint i = 0; i < 5; i++) { if (previousOwners[i] != address(this)) { strangePrice2+=uint256(SafeMath.mul(SafeMath.div(priceDelta, 100), 10)); } else { strangePrice = SafeMath.add(strangePrice, uint256(SafeMath.mul(SafeMath.div(priceDelta, 100), 10))); } } ceoAddress.transfer(strangePrice+strangePrice2); //ceoAddress.transfer(strangePrice2); _transfer(oldOwner, newOwner, _tokenId); //TokenSold(_tokenId, sellingPrice, item23IndexToPrice[_tokenId], oldOwner, newOwner, item23s[_tokenId].name); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return item23IndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = item23IndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose item23 tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Item23s array looking for item23s belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalItem23s = totalSupply(); uint256 resultIndex = 0; uint256 item23Id; for (item23Id = 0; item23Id <= totalItem23s; item23Id++) { if (item23IndexToOwner[item23Id] == _owner) { result[resultIndex] = item23Id; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return item23s.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return item23IndexToApproved[_tokenId] == _to; } <FILL_FUNCTION> /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == item23IndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @dev Assigns ownership of a specific Item23 to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of item23s is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership item23IndexToOwner[_tokenId] = _to; // When creating new item23s _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete item23IndexToApproved[_tokenId]; } // Update the item23IndexToPreviousOwners item23IndexToPreviousOwners[_tokenId][4]=item23IndexToPreviousOwners[_tokenId][3]; item23IndexToPreviousOwners[_tokenId][3]=item23IndexToPreviousOwners[_tokenId][2]; item23IndexToPreviousOwners[_tokenId][2]=item23IndexToPreviousOwners[_tokenId][1]; item23IndexToPreviousOwners[_tokenId][1]=item23IndexToPreviousOwners[_tokenId][0]; // the _from address for creation is 0, so instead set it to the contract address if (_from != address(0)) { item23IndexToPreviousOwners[_tokenId][0]=_from; } else { item23IndexToPreviousOwners[_tokenId][0]=address(this); } // Emit the transfer event. Transfer(_from, _to, _tokenId); } }
Item23 memory _item23 = Item23({ name: _name }); uint256 newItem23Id = item23s.push(_item23) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newItem23Id == uint256(uint32(newItem23Id))); Birth(newItem23Id, _name, _owner); item23IndexToPrice[newItem23Id] = _price; item23IndexToPreviousPrice[newItem23Id] = 0; item23IndexToPreviousOwners[newItem23Id] = [address(this), address(this), address(this), address(this)]; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newItem23Id);
function _createItem23(string _name, address _owner, uint256 _price) private
/// For creating Item23 function _createItem23(string _name, address _owner, uint256 _price) private
23393
TANZANITE
_burn
contract TANZANITE is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "TANZANITE";//"TANZANITE"; string constant tokenSymbol = "TZH";//"TZH"; uint8 constant tokenDecimals = 10; uint256 _totalSupply = 0; // ------------------------------------------------------------------------ address public contractOwner; uint256 public fullUnitsStaked_total = 0; mapping (address => bool) public excludedFromStaking; //exchanges/other contracts will be excluded from staking uint256 _totalRewardsPerUnit = 0; mapping (address => uint256) private _totalRewardsPerUnit_positions; mapping (address => uint256) private _savedRewards; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // ------------------------------------------------------------------------ constructor() public ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { contractOwner = msg.sender; excludedFromStaking[msg.sender] = true; excludedFromStaking[address(this)] = true; _mint(msg.sender, 21000000 * (10**uint256(tokenDecimals))); } // ------------------------------------------------------------------------ function transferOwnership(address newOwner) public { require(msg.sender == contractOwner); require(newOwner != address(0)); emit OwnershipTransferred(contractOwner, newOwner); contractOwner = newOwner; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function fullUnitsStaked(address owner) public view returns (uint256) { return toFullUnits(_balances[owner]); } function toFullUnits(uint256 valueWithDecimals) public pure returns (uint256) { return valueWithDecimals.div(10**uint256(tokenDecimals)); } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { _allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _mint(address account, uint256 value) internal { require(value != 0); uint256 initalBalance = _balances[account]; uint256 newBalance = initalBalance.add(value); _balances[account] = newBalance; _totalSupply = _totalSupply.add(value); //update full units staked if(!excludedFromStaking[account]) { uint256 fus_total = fullUnitsStaked_total; fus_total = fus_total.sub(toFullUnits(initalBalance)); fus_total = fus_total.add(toFullUnits(newBalance)); fullUnitsStaked_total = fus_total; } emit Transfer(address(0), account, value); } function burn(uint256 value) external { _burn(msg.sender, value); } function burnFrom(address account, uint256 value) external { require(value <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); } function _burn(address account, uint256 value) internal {<FILL_FUNCTION_BODY> } /* * transfer with additional burn and stake rewards * the receiver gets 98% of the sent value * 2% are split to be burnt and distributed to holders */ function _executeTransfer(address from, address to, uint256 value) private { require(value <= _balances[from]); require(to != address(0) && to != address(this)); //Update sender and receivers rewards - changing balances will change rewards shares updateRewardsFor(from); updateRewardsFor(to); uint256 twoPercent = value.mul(2).div(100); //set a minimum burn rate to prevent no-burn-txs due to precision loss if(twoPercent == 0 && value > 0) twoPercent = 1; uint256 initalBalance_from = _balances[from]; uint256 newBalance_from = initalBalance_from.sub(value); value = value.sub(twoPercent); uint256 initalBalance_to = _balances[to]; uint256 newBalance_to = initalBalance_to.add(value); //transfer _balances[from] = newBalance_from; _balances[to] = newBalance_to; emit Transfer(from, to, value); //update full units staked uint256 fus_total = fullUnitsStaked_total; if(!excludedFromStaking[from]) { fus_total = fus_total.sub(toFullUnits(initalBalance_from)); fus_total = fus_total.add(toFullUnits(newBalance_from)); } if(!excludedFromStaking[to]) { fus_total = fus_total.sub(toFullUnits(initalBalance_to)); fus_total = fus_total.add(toFullUnits(newBalance_to)); } fullUnitsStaked_total = fus_total; uint256 amountToBurn = twoPercent; if(fus_total > 0) { uint256 stakingRewards = twoPercent.div(2); //split up to rewards per unit in stake uint256 rewardsPerUnit = stakingRewards.div(fus_total); //apply rewards _totalRewardsPerUnit = _totalRewardsPerUnit.add(rewardsPerUnit); _balances[address(this)] = _balances[address(this)].add(stakingRewards); emit Transfer(msg.sender, address(this), stakingRewards); amountToBurn = amountToBurn.sub(stakingRewards); } //update total supply _totalSupply = _totalSupply.sub(amountToBurn); emit Transfer(msg.sender, address(0), amountToBurn); } //catch up with the current total rewards. This needs to be done before an addresses balance is changed function updateRewardsFor(address staker) private { _savedRewards[staker] = viewUnpaidRewards(staker); _totalRewardsPerUnit_positions[staker] = _totalRewardsPerUnit; } //get all rewards that have not been claimed yet function viewUnpaidRewards(address staker) public view returns (uint256) { if(excludedFromStaking[staker]) return _savedRewards[staker]; uint256 newRewardsPerUnit = _totalRewardsPerUnit.sub(_totalRewardsPerUnit_positions[staker]); uint256 newRewards = newRewardsPerUnit.mul(fullUnitsStaked(staker)); return _savedRewards[staker].add(newRewards); } //pay out unclaimed rewards function payoutRewards() public { updateRewardsFor(msg.sender); uint256 rewards = _savedRewards[msg.sender]; require(rewards > 0 && rewards <= _balances[address(this)]); _savedRewards[msg.sender] = 0; uint256 initalBalance_staker = _balances[msg.sender]; uint256 newBalance_staker = initalBalance_staker.add(rewards); //update full units staked if(!excludedFromStaking[msg.sender]) { uint256 fus_total = fullUnitsStaked_total; fus_total = fus_total.sub(toFullUnits(initalBalance_staker)); fus_total = fus_total.add(toFullUnits(newBalance_staker)); fullUnitsStaked_total = fus_total; } //transfer _balances[address(this)] = _balances[address(this)].sub(rewards); _balances[msg.sender] = newBalance_staker; emit Transfer(address(this), msg.sender, rewards); } //exchanges or other contracts can be excluded from receiving stake rewards function excludeAddressFromStaking(address excludeAddress, bool exclude) public { require(msg.sender == contractOwner); require(excludeAddress != address(this)); //contract may never be included require(exclude != excludedFromStaking[excludeAddress]); updateRewardsFor(excludeAddress); excludedFromStaking[excludeAddress] = exclude; fullUnitsStaked_total = exclude ? fullUnitsStaked_total.sub(fullUnitsStaked(excludeAddress)) : fullUnitsStaked_total.add(fullUnitsStaked(excludeAddress)); } //withdraw tokens that were sent to this contract by accident function withdrawERC20Tokens(address tokenAddress, uint256 amount) public { require(msg.sender == contractOwner); require(tokenAddress != address(this)); IERC20(tokenAddress).transfer(msg.sender, amount); } }
contract TANZANITE is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "TANZANITE";//"TANZANITE"; string constant tokenSymbol = "TZH";//"TZH"; uint8 constant tokenDecimals = 10; uint256 _totalSupply = 0; // ------------------------------------------------------------------------ address public contractOwner; uint256 public fullUnitsStaked_total = 0; mapping (address => bool) public excludedFromStaking; //exchanges/other contracts will be excluded from staking uint256 _totalRewardsPerUnit = 0; mapping (address => uint256) private _totalRewardsPerUnit_positions; mapping (address => uint256) private _savedRewards; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // ------------------------------------------------------------------------ constructor() public ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { contractOwner = msg.sender; excludedFromStaking[msg.sender] = true; excludedFromStaking[address(this)] = true; _mint(msg.sender, 21000000 * (10**uint256(tokenDecimals))); } // ------------------------------------------------------------------------ function transferOwnership(address newOwner) public { require(msg.sender == contractOwner); require(newOwner != address(0)); emit OwnershipTransferred(contractOwner, newOwner); contractOwner = newOwner; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function fullUnitsStaked(address owner) public view returns (uint256) { return toFullUnits(_balances[owner]); } function toFullUnits(uint256 valueWithDecimals) public pure returns (uint256) { return valueWithDecimals.div(10**uint256(tokenDecimals)); } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _executeTransfer(msg.sender, to, value); return true; } function multiTransfer(address[] memory receivers, uint256[] memory values) public { require(receivers.length == values.length); for(uint256 i = 0; i < receivers.length; i++) _executeTransfer(msg.sender, receivers[i], values[i]); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _executeTransfer(from, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { _allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _mint(address account, uint256 value) internal { require(value != 0); uint256 initalBalance = _balances[account]; uint256 newBalance = initalBalance.add(value); _balances[account] = newBalance; _totalSupply = _totalSupply.add(value); //update full units staked if(!excludedFromStaking[account]) { uint256 fus_total = fullUnitsStaked_total; fus_total = fus_total.sub(toFullUnits(initalBalance)); fus_total = fus_total.add(toFullUnits(newBalance)); fullUnitsStaked_total = fus_total; } emit Transfer(address(0), account, value); } function burn(uint256 value) external { _burn(msg.sender, value); } function burnFrom(address account, uint256 value) external { require(value <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); } <FILL_FUNCTION> /* * transfer with additional burn and stake rewards * the receiver gets 98% of the sent value * 2% are split to be burnt and distributed to holders */ function _executeTransfer(address from, address to, uint256 value) private { require(value <= _balances[from]); require(to != address(0) && to != address(this)); //Update sender and receivers rewards - changing balances will change rewards shares updateRewardsFor(from); updateRewardsFor(to); uint256 twoPercent = value.mul(2).div(100); //set a minimum burn rate to prevent no-burn-txs due to precision loss if(twoPercent == 0 && value > 0) twoPercent = 1; uint256 initalBalance_from = _balances[from]; uint256 newBalance_from = initalBalance_from.sub(value); value = value.sub(twoPercent); uint256 initalBalance_to = _balances[to]; uint256 newBalance_to = initalBalance_to.add(value); //transfer _balances[from] = newBalance_from; _balances[to] = newBalance_to; emit Transfer(from, to, value); //update full units staked uint256 fus_total = fullUnitsStaked_total; if(!excludedFromStaking[from]) { fus_total = fus_total.sub(toFullUnits(initalBalance_from)); fus_total = fus_total.add(toFullUnits(newBalance_from)); } if(!excludedFromStaking[to]) { fus_total = fus_total.sub(toFullUnits(initalBalance_to)); fus_total = fus_total.add(toFullUnits(newBalance_to)); } fullUnitsStaked_total = fus_total; uint256 amountToBurn = twoPercent; if(fus_total > 0) { uint256 stakingRewards = twoPercent.div(2); //split up to rewards per unit in stake uint256 rewardsPerUnit = stakingRewards.div(fus_total); //apply rewards _totalRewardsPerUnit = _totalRewardsPerUnit.add(rewardsPerUnit); _balances[address(this)] = _balances[address(this)].add(stakingRewards); emit Transfer(msg.sender, address(this), stakingRewards); amountToBurn = amountToBurn.sub(stakingRewards); } //update total supply _totalSupply = _totalSupply.sub(amountToBurn); emit Transfer(msg.sender, address(0), amountToBurn); } //catch up with the current total rewards. This needs to be done before an addresses balance is changed function updateRewardsFor(address staker) private { _savedRewards[staker] = viewUnpaidRewards(staker); _totalRewardsPerUnit_positions[staker] = _totalRewardsPerUnit; } //get all rewards that have not been claimed yet function viewUnpaidRewards(address staker) public view returns (uint256) { if(excludedFromStaking[staker]) return _savedRewards[staker]; uint256 newRewardsPerUnit = _totalRewardsPerUnit.sub(_totalRewardsPerUnit_positions[staker]); uint256 newRewards = newRewardsPerUnit.mul(fullUnitsStaked(staker)); return _savedRewards[staker].add(newRewards); } //pay out unclaimed rewards function payoutRewards() public { updateRewardsFor(msg.sender); uint256 rewards = _savedRewards[msg.sender]; require(rewards > 0 && rewards <= _balances[address(this)]); _savedRewards[msg.sender] = 0; uint256 initalBalance_staker = _balances[msg.sender]; uint256 newBalance_staker = initalBalance_staker.add(rewards); //update full units staked if(!excludedFromStaking[msg.sender]) { uint256 fus_total = fullUnitsStaked_total; fus_total = fus_total.sub(toFullUnits(initalBalance_staker)); fus_total = fus_total.add(toFullUnits(newBalance_staker)); fullUnitsStaked_total = fus_total; } //transfer _balances[address(this)] = _balances[address(this)].sub(rewards); _balances[msg.sender] = newBalance_staker; emit Transfer(address(this), msg.sender, rewards); } //exchanges or other contracts can be excluded from receiving stake rewards function excludeAddressFromStaking(address excludeAddress, bool exclude) public { require(msg.sender == contractOwner); require(excludeAddress != address(this)); //contract may never be included require(exclude != excludedFromStaking[excludeAddress]); updateRewardsFor(excludeAddress); excludedFromStaking[excludeAddress] = exclude; fullUnitsStaked_total = exclude ? fullUnitsStaked_total.sub(fullUnitsStaked(excludeAddress)) : fullUnitsStaked_total.add(fullUnitsStaked(excludeAddress)); } //withdraw tokens that were sent to this contract by accident function withdrawERC20Tokens(address tokenAddress, uint256 amount) public { require(msg.sender == contractOwner); require(tokenAddress != address(this)); IERC20(tokenAddress).transfer(msg.sender, amount); } }
require(value != 0); require(value <= _balances[account]); uint256 initalBalance = _balances[account]; uint256 newBalance = initalBalance.sub(value); _balances[account] = newBalance; _totalSupply = _totalSupply.sub(value); //update full units staked if(!excludedFromStaking[account]) { uint256 fus_total = fullUnitsStaked_total; fus_total = fus_total.sub(toFullUnits(initalBalance)); fus_total = fus_total.add(toFullUnits(newBalance)); fullUnitsStaked_total = fus_total; } emit Transfer(account, address(0), value);
function _burn(address account, uint256 value) internal
function _burn(address account, uint256 value) internal
92837
CDonToken
approveAndCall
contract CDonToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function CDonToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { symbol = tokenSymbol; name = tokenName; decimals = 18; _totalSupply = initialSupply * 10 ** uint256(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<FILL_FUNCTION_BODY> } }
contract CDonToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function CDonToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { symbol = tokenSymbol; name = tokenName; decimals = 18; _totalSupply = initialSupply * 10 ** uint256(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> }
allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true;
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
// ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
10750
PokemonPow
setCOO
contract PokemonPow is ERC721 { address cryptoVideoGames = 0xdEc14D8f4DA25108Fd0d32Bf2DeCD9538564D069; address cryptoVideoGameItems = 0xD2606C9bC5EFE092A8925e7d6Ae2F63a84c5FDEa; /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new pow comes into existence. event Birth(uint256 tokenId, string name, address owner); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoKotakuPokemonPow"; // solhint-disable-line string public constant SYMBOL = "PokemonPow"; // solhint-disable-line uint256 private startingPrice = 0.005 ether; uint256 private firstStepLimit = 0.05 ether; uint256 private secondStepLimit = 0.5 ether; /*** STORAGE ***/ /// @dev A mapping from pow IDs to the address that owns them. All pows have /// some valid owner address. mapping (uint256 => address) public powIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from PowIDs to an address that has been approved to call /// transferFrom(). Each Pow can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public powIndexToApproved; // @dev A mapping from PowIDs to the price of the token. mapping (uint256 => uint256) private powIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; uint256 public promoCreatedCount; /*** DATATYPES ***/ struct Pow { string name; uint gameId; uint gameItemId1; uint gameItemId2; } Pow[] private pows; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function PokemonPow() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); powIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new promo Pow with the given name, with given _price and assignes it to an address. function createPromoPow(address _owner, string _name, uint256 _price, uint _gameId, uint _gameItemId1, uint _gameItemId2) public onlyCOO { address powOwner = _owner; if (powOwner == address(0)) { powOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; _createPow(_name, powOwner, _price, _gameId, _gameItemId1, _gameItemId2); } /// @dev Creates a new Pow with the given name. function createContractPow(string _name, uint _gameId, uint _gameItemId1, uint _gameItemId2) public onlyCOO { _createPow(_name, address(this), startingPrice, _gameId, _gameItemId1, _gameItemId2); } /// @notice Returns all the relevant information about a specific pow. /// @param _tokenId The tokenId of the pow of interest. function getPow(uint256 _tokenId) public view returns ( uint256 Id, string powName, uint256 sellingPrice, address owner, uint gameId, uint gameItemId1, uint gameItemId2 ) { Pow storage pow = pows[_tokenId]; Id = _tokenId; powName = pow.name; sellingPrice = powIndexToPrice[_tokenId]; owner = powIndexToOwner[_tokenId]; gameId = pow.gameId; gameItemId1 = pow.gameItemId1; gameItemId2 = pow.gameItemId2; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = powIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = powIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = powIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 gameOwnerPayment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 5), 100)); uint256 gameItemOwnerPayment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 5), 100)); uint256 payment = sellingPrice - gameOwnerPayment - gameOwnerPayment - gameItemOwnerPayment - gameItemOwnerPayment; uint256 purchaseExcess = SafeMath.sub(msg.value,sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage powIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100); } else if (sellingPrice < secondStepLimit) { // second stage powIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 180), 100); } else { // third stage powIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100); } _transfer(oldOwner, newOwner, _tokenId); TokenSold(_tokenId, sellingPrice, powIndexToPrice[_tokenId], oldOwner, newOwner, pows[_tokenId].name); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1-0.2) } msg.sender.transfer(purchaseExcess); _transferDivs(gameOwnerPayment, gameItemOwnerPayment, _tokenId); } /// Divident distributions function _transferDivs(uint256 _gameOwnerPayment, uint256 _gameItemOwnerPayment, uint256 _tokenId) private { CryptoVideoGames gamesContract = CryptoVideoGames(cryptoVideoGames); CryptoVideoGameItem gameItemContract = CryptoVideoGameItem(cryptoVideoGameItems); address gameOwner = gamesContract.getVideoGameOwner(pows[_tokenId].gameId); address gameItem1Owner = gameItemContract.getVideoGameItemOwner(pows[_tokenId].gameItemId1); address gameItem2Owner = gameItemContract.getVideoGameItemOwner(pows[_tokenId].gameItemId2); gameOwner.transfer(_gameOwnerPayment); gameItem1Owner.transfer(_gameItemOwnerPayment); gameItem2Owner.transfer(_gameItemOwnerPayment); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return powIndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO {<FILL_FUNCTION_BODY> } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = powIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose pow tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire pows array looking for pows belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPows = totalSupply(); uint256 resultIndex = 0; uint256 powId; for (powId = 0; powId <= totalPows; powId++) { if (powIndexToOwner[powId] == _owner) { result[resultIndex] = powId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return pows.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return powIndexToApproved[_tokenId] == _to; } /// For creating Pow function _createPow(string _name, address _owner, uint256 _price, uint _gameId, uint _gameItemId1, uint _gameItemId2) private { Pow memory _pow = Pow({ name: _name, gameId: _gameId, gameItemId1: _gameItemId1, gameItemId2: _gameItemId2 }); uint256 newPowId = pows.push(_pow) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newPowId == uint256(uint32(newPowId))); Birth(newPowId, _name, _owner); powIndexToPrice[newPowId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newPowId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == powIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /* This function can be used by the owner of a pow item to modify the price of its pow item. */ function modifyPowPrice(uint _powId, uint256 _newPrice) public { require(_newPrice > 0); require(powIndexToOwner[_powId] == msg.sender); powIndexToPrice[_powId] = _newPrice; } /// @dev Assigns ownership of a specific Pow to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of pow is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership powIndexToOwner[_tokenId] = _to; // When creating new pows _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete powIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } }
contract PokemonPow is ERC721 { address cryptoVideoGames = 0xdEc14D8f4DA25108Fd0d32Bf2DeCD9538564D069; address cryptoVideoGameItems = 0xD2606C9bC5EFE092A8925e7d6Ae2F63a84c5FDEa; /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new pow comes into existence. event Birth(uint256 tokenId, string name, address owner); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoKotakuPokemonPow"; // solhint-disable-line string public constant SYMBOL = "PokemonPow"; // solhint-disable-line uint256 private startingPrice = 0.005 ether; uint256 private firstStepLimit = 0.05 ether; uint256 private secondStepLimit = 0.5 ether; /*** STORAGE ***/ /// @dev A mapping from pow IDs to the address that owns them. All pows have /// some valid owner address. mapping (uint256 => address) public powIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from PowIDs to an address that has been approved to call /// transferFrom(). Each Pow can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public powIndexToApproved; // @dev A mapping from PowIDs to the price of the token. mapping (uint256 => uint256) private powIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; uint256 public promoCreatedCount; /*** DATATYPES ***/ struct Pow { string name; uint gameId; uint gameItemId1; uint gameItemId2; } Pow[] private pows; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function PokemonPow() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); powIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new promo Pow with the given name, with given _price and assignes it to an address. function createPromoPow(address _owner, string _name, uint256 _price, uint _gameId, uint _gameItemId1, uint _gameItemId2) public onlyCOO { address powOwner = _owner; if (powOwner == address(0)) { powOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; _createPow(_name, powOwner, _price, _gameId, _gameItemId1, _gameItemId2); } /// @dev Creates a new Pow with the given name. function createContractPow(string _name, uint _gameId, uint _gameItemId1, uint _gameItemId2) public onlyCOO { _createPow(_name, address(this), startingPrice, _gameId, _gameItemId1, _gameItemId2); } /// @notice Returns all the relevant information about a specific pow. /// @param _tokenId The tokenId of the pow of interest. function getPow(uint256 _tokenId) public view returns ( uint256 Id, string powName, uint256 sellingPrice, address owner, uint gameId, uint gameItemId1, uint gameItemId2 ) { Pow storage pow = pows[_tokenId]; Id = _tokenId; powName = pow.name; sellingPrice = powIndexToPrice[_tokenId]; owner = powIndexToOwner[_tokenId]; gameId = pow.gameId; gameItemId1 = pow.gameItemId1; gameItemId2 = pow.gameItemId2; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = powIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = powIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = powIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 gameOwnerPayment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 5), 100)); uint256 gameItemOwnerPayment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 5), 100)); uint256 payment = sellingPrice - gameOwnerPayment - gameOwnerPayment - gameItemOwnerPayment - gameItemOwnerPayment; uint256 purchaseExcess = SafeMath.sub(msg.value,sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage powIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100); } else if (sellingPrice < secondStepLimit) { // second stage powIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 180), 100); } else { // third stage powIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100); } _transfer(oldOwner, newOwner, _tokenId); TokenSold(_tokenId, sellingPrice, powIndexToPrice[_tokenId], oldOwner, newOwner, pows[_tokenId].name); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1-0.2) } msg.sender.transfer(purchaseExcess); _transferDivs(gameOwnerPayment, gameItemOwnerPayment, _tokenId); } /// Divident distributions function _transferDivs(uint256 _gameOwnerPayment, uint256 _gameItemOwnerPayment, uint256 _tokenId) private { CryptoVideoGames gamesContract = CryptoVideoGames(cryptoVideoGames); CryptoVideoGameItem gameItemContract = CryptoVideoGameItem(cryptoVideoGameItems); address gameOwner = gamesContract.getVideoGameOwner(pows[_tokenId].gameId); address gameItem1Owner = gameItemContract.getVideoGameItemOwner(pows[_tokenId].gameItemId1); address gameItem2Owner = gameItemContract.getVideoGameItemOwner(pows[_tokenId].gameItemId2); gameOwner.transfer(_gameOwnerPayment); gameItem1Owner.transfer(_gameItemOwnerPayment); gameItem2Owner.transfer(_gameItemOwnerPayment); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return powIndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } <FILL_FUNCTION> /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = powIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose pow tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire pows array looking for pows belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPows = totalSupply(); uint256 resultIndex = 0; uint256 powId; for (powId = 0; powId <= totalPows; powId++) { if (powIndexToOwner[powId] == _owner) { result[resultIndex] = powId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return pows.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return powIndexToApproved[_tokenId] == _to; } /// For creating Pow function _createPow(string _name, address _owner, uint256 _price, uint _gameId, uint _gameItemId1, uint _gameItemId2) private { Pow memory _pow = Pow({ name: _name, gameId: _gameId, gameItemId1: _gameItemId1, gameItemId2: _gameItemId2 }); uint256 newPowId = pows.push(_pow) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newPowId == uint256(uint32(newPowId))); Birth(newPowId, _name, _owner); powIndexToPrice[newPowId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newPowId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == powIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /* This function can be used by the owner of a pow item to modify the price of its pow item. */ function modifyPowPrice(uint _powId, uint256 _newPrice) public { require(_newPrice > 0); require(powIndexToOwner[_powId] == msg.sender); powIndexToPrice[_powId] = _newPrice; } /// @dev Assigns ownership of a specific Pow to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of pow is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership powIndexToOwner[_tokenId] = _to; // When creating new pows _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete powIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } }
require(_newCOO != address(0)); cooAddress = _newCOO;
function setCOO(address _newCOO) public onlyCEO
/// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO
30762
AbstractToken
transfer
contract AbstractToken is Token, SafeMath { function AbstractToken () { // Do nothing } function balanceOf (address _owner) constant returns (uint256 balance) { return accounts [_owner]; } function transfer (address _to, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); if (_value > 0 && _from != _to) { accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (_from, _to, _value); return true; } function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; Approval (msg.sender, _spender, _value); return true; } function allowance (address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; }
contract AbstractToken is Token, SafeMath { function AbstractToken () { // Do nothing } function balanceOf (address _owner) constant returns (uint256 balance) { return accounts [_owner]; } <FILL_FUNCTION> function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); if (_value > 0 && _from != _to) { accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (_from, _to, _value); return true; } function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; Approval (msg.sender, _spender, _value); return true; } function allowance (address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; }
if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (msg.sender, _to, _value); return true;
function transfer (address _to, uint256 _value) returns (bool success)
function transfer (address _to, uint256 _value) returns (bool success)
19624
PCATV2
reflectionFromToken
contract PCATV2 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 20000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "pcatv2.finance"; string private _symbol = "pcatv2"; uint8 private _decimals = 18; uint256 public _taxFee = 2; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 3; uint256 private _previousLiquidityFee = _liquidityFee; address [] public tokenHolder; uint256 public numberOfTokenHolders = 0; mapping(address => bool) public exist; uint256 private ethFees; //No limit uint256 public _maxTxAmount = _tTotal; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private minTokensBeforeSwap = 8; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {<FILL_FUNCTION_BODY> } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } bool public limit = true; function changeLimit() public onlyOwner(){ require(limit == true, 'limit is already false'); limit = false; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limit == true && from != owner() && to != owner()){ if(to != uniswapV2Pair){ require(((balanceOf(to).add(amount)) <= 200 ether)); } require(amount <= 200 ether, 'Transfer amount must be less than 200 tokens'); } if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. if(!exist[to]){ tokenHolder.push(to); numberOfTokenHolders++; exist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } mapping(address => uint256) public myRewards; function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 fees = contractTokenBalance.div(2); uint256 liquidity = contractTokenBalance.sub(fees); uint256 half = liquidity.div(2); uint256 otherHalf = liquidity.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half.add(fees)); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 Balance = address(this).balance.sub(initialBalance); uint256 newBalance = Balance.mul(2).div(3); ethFees = ethFees.add(Balance.div(3)); for(uint256 i = 0; i < numberOfTokenHolders; i++){ uint256 share = (balanceOf(tokenHolder[i]).mul(ethFees)).div(totalSupply()); myRewards[tokenHolder[i]] = myRewards[tokenHolder[i]].add(share); } // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function seeRewards() public view returns(uint256){ return myRewards[msg.sender]; } function getRewards() public returns(bool){ require(myRewards[msg.sender] > 0, 'You have zero rewards right now'); uint256 _rewards = myRewards[msg.sender]; myRewards[msg.sender] = myRewards[msg.sender].sub(_rewards); msg.sender.transfer(_rewards); return true; } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} }
contract PCATV2 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 20000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "pcatv2.finance"; string private _symbol = "pcatv2"; uint8 private _decimals = 18; uint256 public _taxFee = 2; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 3; uint256 private _previousLiquidityFee = _liquidityFee; address [] public tokenHolder; uint256 public numberOfTokenHolders = 0; mapping(address => bool) public exist; uint256 private ethFees; //No limit uint256 public _maxTxAmount = _tTotal; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private minTokensBeforeSwap = 8; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } <FILL_FUNCTION> function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } bool public limit = true; function changeLimit() public onlyOwner(){ require(limit == true, 'limit is already false'); limit = false; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limit == true && from != owner() && to != owner()){ if(to != uniswapV2Pair){ require(((balanceOf(to).add(amount)) <= 200 ether)); } require(amount <= 200 ether, 'Transfer amount must be less than 200 tokens'); } if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. if(!exist[to]){ tokenHolder.push(to); numberOfTokenHolders++; exist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } mapping(address => uint256) public myRewards; function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 fees = contractTokenBalance.div(2); uint256 liquidity = contractTokenBalance.sub(fees); uint256 half = liquidity.div(2); uint256 otherHalf = liquidity.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half.add(fees)); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 Balance = address(this).balance.sub(initialBalance); uint256 newBalance = Balance.mul(2).div(3); ethFees = ethFees.add(Balance.div(3)); for(uint256 i = 0; i < numberOfTokenHolders; i++){ uint256 share = (balanceOf(tokenHolder[i]).mul(ethFees)).div(totalSupply()); myRewards[tokenHolder[i]] = myRewards[tokenHolder[i]].add(share); } // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function seeRewards() public view returns(uint256){ return myRewards[msg.sender]; } function getRewards() public returns(bool){ require(myRewards[msg.sender] > 0, 'You have zero rewards right now'); uint256 _rewards = myRewards[msg.sender]; myRewards[msg.sender] = myRewards[msg.sender].sub(_rewards); msg.sender.transfer(_rewards); return true; } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} }
require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; }
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256)
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256)
5236
FRUITStaking
updatePrice
contract FRUITStaking { using SafeMath for uint; address private immutable fruitToken; address private immutable v2Pair; uint8 private immutable fruitDec; uint constant DAY = 60 * 60 * 24; uint constant RATE = 50000; uint constant LEAST = 500; address _owner; uint public bonus = 0; constructor(address fruit , address v2) public { _owner = msg.sender; fruitToken = fruit; fruitDec = IERC20(fruit).decimals(); v2Pair = v2; require(IUniswapV2Pair(v2).token0() == fruit || IUniswapV2Pair(v2).token1() == fruit, "E/no fruit"); } struct Staking { uint amount; uint stakeTime; uint earnTime; } mapping(address => Staking) V2Stakings; mapping(address => Staking) fruitStakings; mapping(uint => uint) dayPrices; mapping(uint => bool) raiseOver10; function myV2Staking() external view returns (uint, uint, uint ) { return (V2Stakings[msg.sender].amount, V2Stakings[msg.sender].stakeTime, myV2Earn()); } function stakingV2(uint amount) external { require(V2Stakings[msg.sender].amount == 0, "E/aleady staking"); require(IERC20(v2Pair).transferFrom(msg.sender, address(this), amount), "E/transfer error"); V2Stakings[msg.sender] = Staking(amount, now, now); } function wdV2(uint amount) external { uint stakingToal = V2Stakings[msg.sender].amount; uint stakingTime = V2Stakings[msg.sender].stakeTime; require(stakingToal >= amount, "E/not enough"); require(now >= stakingTime + 2 * DAY, "E/locked"); wdV2Earn() ; IERC20(v2Pair).transfer(msg.sender, amount); if(stakingToal - amount > 0) { V2Stakings[msg.sender] = Staking(stakingToal - amount, now, now); } else { delete V2Stakings[msg.sender]; } } function myV2Earn() internal view returns (uint) { Staking memory s = V2Stakings[msg.sender]; if(s.amount == 0) { return 0; } uint endDay = getDay(now); uint startDay = getDay(s.earnTime); if(endDay > startDay) { uint earnDays = endDay - startDay; uint earns = 0; if(earnDays > 0) { earns = s.amount.mul(earnDays).mul(RATE).div(10 ** (uint(18).sub(fruitDec))); } return earns; } return 0; } function wdV2Earn() public { uint earnsTotal = myV2Earn(); uint fee = earnsTotal * 8 / 100; bonus = bonus.add(fee); IERC20(fruitToken).transfer(msg.sender, earnsTotal.sub(fee)); V2Stakings[msg.sender].earnTime = now; } // ----- for fruit staking ------ function myFruitStaking() external view returns (uint, uint, uint ) { return (fruitStakings[msg.sender].amount, fruitStakings[msg.sender].stakeTime, myFruitEarn()); } function stakingFruit(uint amount) external { require(amount >= LEAST * 10 ** uint(fruitDec), "E/not enough"); require(fruitStakings[msg.sender].amount == 0, "E/aleady staking"); require(IERC20(fruitToken).transferFrom(msg.sender, address(this), amount), "E/transfer error"); fruitStakings[msg.sender] = Staking(amount, now, now); } function wdFruit(uint amount) external { uint stakingToal = fruitStakings[msg.sender].amount; require(stakingToal >= amount, "E/not enough"); wdFruitEarn(); if(stakingToal - amount >= LEAST * 10 ** uint(fruitDec)) { uint fee = amount * 8 / 100; bonus = bonus.add(fee); IERC20(fruitToken).transfer(msg.sender, amount.sub(fee)); fruitStakings[msg.sender] = Staking(stakingToal - amount, now, now); } else { uint fee = stakingToal * 8 / 100; bonus = bonus.add(fee); IERC20(fruitToken).transfer(msg.sender, stakingToal.sub(fee)); delete fruitStakings[msg.sender]; } } function myFruitEarn() internal view returns (uint) { Staking memory s = fruitStakings[msg.sender]; if(s.amount == 0) { return 0; } uint earnDays = getEarnDays(s); uint earns = 0; if(earnDays > 0) { earns = s.amount.div(100) * earnDays; } return earns; } function wdFruitEarn() public { uint earnsTotal = myFruitEarn(); uint fee = earnsTotal * 8 / 100; bonus = bonus.add(fee); IERC20(fruitToken).transfer(msg.sender, earnsTotal.sub(fee)); fruitStakings[msg.sender].earnTime = now; } function getEarnDays(Staking memory s) internal view returns (uint) { uint startDay = getDay(s.earnTime); uint endDay = getDay(now); uint earnDays = 0; while(endDay > startDay) { if(raiseOver10[startDay]) { earnDays += 1; } startDay += 1; } return earnDays; } // get 1 fruit = x eth function fetchPrice() internal view returns (uint) { (uint reserve0, uint reserve1,) = IUniswapV2Pair(v2Pair).getReserves(); require(reserve0 > 0 && reserve1 > 0, 'E/INSUFFICIENT_LIQUIDITY'); uint oneFruit = 10 ** uint(fruitDec); if(IUniswapV2Pair(v2Pair).token0() == fruitToken) { return oneFruit.mul(reserve1) / reserve0; } else { return oneFruit.mul(reserve0) / reserve1; } } function getDay(uint ts) internal pure returns (uint) { return ts / DAY; } function updatePrice() external {<FILL_FUNCTION_BODY> } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function owner() public view returns (address) { return _owner; } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); _owner = newOwner; } function withdrawFruit(uint amount) external onlyOwner { IERC20(fruitToken).transfer(msg.sender, amount); } }
contract FRUITStaking { using SafeMath for uint; address private immutable fruitToken; address private immutable v2Pair; uint8 private immutable fruitDec; uint constant DAY = 60 * 60 * 24; uint constant RATE = 50000; uint constant LEAST = 500; address _owner; uint public bonus = 0; constructor(address fruit , address v2) public { _owner = msg.sender; fruitToken = fruit; fruitDec = IERC20(fruit).decimals(); v2Pair = v2; require(IUniswapV2Pair(v2).token0() == fruit || IUniswapV2Pair(v2).token1() == fruit, "E/no fruit"); } struct Staking { uint amount; uint stakeTime; uint earnTime; } mapping(address => Staking) V2Stakings; mapping(address => Staking) fruitStakings; mapping(uint => uint) dayPrices; mapping(uint => bool) raiseOver10; function myV2Staking() external view returns (uint, uint, uint ) { return (V2Stakings[msg.sender].amount, V2Stakings[msg.sender].stakeTime, myV2Earn()); } function stakingV2(uint amount) external { require(V2Stakings[msg.sender].amount == 0, "E/aleady staking"); require(IERC20(v2Pair).transferFrom(msg.sender, address(this), amount), "E/transfer error"); V2Stakings[msg.sender] = Staking(amount, now, now); } function wdV2(uint amount) external { uint stakingToal = V2Stakings[msg.sender].amount; uint stakingTime = V2Stakings[msg.sender].stakeTime; require(stakingToal >= amount, "E/not enough"); require(now >= stakingTime + 2 * DAY, "E/locked"); wdV2Earn() ; IERC20(v2Pair).transfer(msg.sender, amount); if(stakingToal - amount > 0) { V2Stakings[msg.sender] = Staking(stakingToal - amount, now, now); } else { delete V2Stakings[msg.sender]; } } function myV2Earn() internal view returns (uint) { Staking memory s = V2Stakings[msg.sender]; if(s.amount == 0) { return 0; } uint endDay = getDay(now); uint startDay = getDay(s.earnTime); if(endDay > startDay) { uint earnDays = endDay - startDay; uint earns = 0; if(earnDays > 0) { earns = s.amount.mul(earnDays).mul(RATE).div(10 ** (uint(18).sub(fruitDec))); } return earns; } return 0; } function wdV2Earn() public { uint earnsTotal = myV2Earn(); uint fee = earnsTotal * 8 / 100; bonus = bonus.add(fee); IERC20(fruitToken).transfer(msg.sender, earnsTotal.sub(fee)); V2Stakings[msg.sender].earnTime = now; } // ----- for fruit staking ------ function myFruitStaking() external view returns (uint, uint, uint ) { return (fruitStakings[msg.sender].amount, fruitStakings[msg.sender].stakeTime, myFruitEarn()); } function stakingFruit(uint amount) external { require(amount >= LEAST * 10 ** uint(fruitDec), "E/not enough"); require(fruitStakings[msg.sender].amount == 0, "E/aleady staking"); require(IERC20(fruitToken).transferFrom(msg.sender, address(this), amount), "E/transfer error"); fruitStakings[msg.sender] = Staking(amount, now, now); } function wdFruit(uint amount) external { uint stakingToal = fruitStakings[msg.sender].amount; require(stakingToal >= amount, "E/not enough"); wdFruitEarn(); if(stakingToal - amount >= LEAST * 10 ** uint(fruitDec)) { uint fee = amount * 8 / 100; bonus = bonus.add(fee); IERC20(fruitToken).transfer(msg.sender, amount.sub(fee)); fruitStakings[msg.sender] = Staking(stakingToal - amount, now, now); } else { uint fee = stakingToal * 8 / 100; bonus = bonus.add(fee); IERC20(fruitToken).transfer(msg.sender, stakingToal.sub(fee)); delete fruitStakings[msg.sender]; } } function myFruitEarn() internal view returns (uint) { Staking memory s = fruitStakings[msg.sender]; if(s.amount == 0) { return 0; } uint earnDays = getEarnDays(s); uint earns = 0; if(earnDays > 0) { earns = s.amount.div(100) * earnDays; } return earns; } function wdFruitEarn() public { uint earnsTotal = myFruitEarn(); uint fee = earnsTotal * 8 / 100; bonus = bonus.add(fee); IERC20(fruitToken).transfer(msg.sender, earnsTotal.sub(fee)); fruitStakings[msg.sender].earnTime = now; } function getEarnDays(Staking memory s) internal view returns (uint) { uint startDay = getDay(s.earnTime); uint endDay = getDay(now); uint earnDays = 0; while(endDay > startDay) { if(raiseOver10[startDay]) { earnDays += 1; } startDay += 1; } return earnDays; } // get 1 fruit = x eth function fetchPrice() internal view returns (uint) { (uint reserve0, uint reserve1,) = IUniswapV2Pair(v2Pair).getReserves(); require(reserve0 > 0 && reserve1 > 0, 'E/INSUFFICIENT_LIQUIDITY'); uint oneFruit = 10 ** uint(fruitDec); if(IUniswapV2Pair(v2Pair).token0() == fruitToken) { return oneFruit.mul(reserve1) / reserve0; } else { return oneFruit.mul(reserve0) / reserve1; } } function getDay(uint ts) internal pure returns (uint) { return ts / DAY; } <FILL_FUNCTION> modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function owner() public view returns (address) { return _owner; } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); _owner = newOwner; } function withdrawFruit(uint amount) external onlyOwner { IERC20(fruitToken).transfer(msg.sender, amount); } }
uint d = getDay(now); uint p = fetchPrice(); dayPrices[d] = p; uint lastPrice = dayPrices[d-1]; if(lastPrice > 0) { if(p > lastPrice.add(lastPrice/10)) { raiseOver10[d] = true; } }
function updatePrice() external
function updatePrice() external
5504
SuperEOS
acceptOwnership
contract SuperEOS { string public name = "SuperEOS"; string public symbol = "SPEOS"; uint8 public decimals = 6; uint256 public totalSupply; bool public lockAll = false; event Transfer(address indexed from, address indexed to, uint256 value); event FrozenFunds(address target, bool frozen); event OwnerUpdate(address _prevOwner, address _newOwner); address public owner; address internal newOwner = 0x0; mapping (address => bool) public frozens; mapping (address => uint256) public balanceOf; //---------init---------- function SuperEOS() public { totalSupply = 2000000000 * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; owner = msg.sender; } //--------control-------- modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address tOwner) onlyOwner public { require(owner!=tOwner); newOwner = tOwner; } function acceptOwnership() public {<FILL_FUNCTION_BODY> } function freezeAccount(address target, bool freeze) onlyOwner public { frozens[target] = freeze; emit FrozenFunds(target, freeze); } function freezeAll(bool lock) onlyOwner public { lockAll = lock; } //-------transfer------- function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function _transfer(address _from, address _to, uint _value) internal { require(!lockAll); require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); require(!frozens[_from]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } }
contract SuperEOS { string public name = "SuperEOS"; string public symbol = "SPEOS"; uint8 public decimals = 6; uint256 public totalSupply; bool public lockAll = false; event Transfer(address indexed from, address indexed to, uint256 value); event FrozenFunds(address target, bool frozen); event OwnerUpdate(address _prevOwner, address _newOwner); address public owner; address internal newOwner = 0x0; mapping (address => bool) public frozens; mapping (address => uint256) public balanceOf; //---------init---------- function SuperEOS() public { totalSupply = 2000000000 * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; owner = msg.sender; } //--------control-------- modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address tOwner) onlyOwner public { require(owner!=tOwner); newOwner = tOwner; } <FILL_FUNCTION> function freezeAccount(address target, bool freeze) onlyOwner public { frozens[target] = freeze; emit FrozenFunds(target, freeze); } function freezeAll(bool lock) onlyOwner public { lockAll = lock; } //-------transfer------- function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function _transfer(address _from, address _to, uint _value) internal { require(!lockAll); require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); require(!frozens[_from]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } }
require(msg.sender==newOwner && newOwner != 0x0); owner = newOwner; newOwner = 0x0; emit OwnerUpdate(owner, newOwner);
function acceptOwnership() public
function acceptOwnership() public
12273
LiveHireMe
contract LiveHireMe is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function LiveHireMe() { balances[msg.sender] = 90000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 90000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "LiveHireMe"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "LHM"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 20000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{<FILL_FUNCTION_BODY> } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract LiveHireMe is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function LiveHireMe() { balances[msg.sender] = 90000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 90000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "LiveHireMe"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "LHM"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 20000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } <FILL_FUNCTION> /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value);
function() payable
function() payable
35463
DSGroup
trigger
contract DSGroup is DSExec, DSNote { address[] public members; uint public quorum; uint public window; uint public actionCount; mapping (uint => Action) public actions; mapping (uint => mapping (address => bool)) public confirmedBy; mapping (address => bool) public isMember; // Legacy events event Proposed (uint id, bytes calldata); event Confirmed (uint id, address member); event Triggered (uint id); struct Action { address target; bytes calldata; uint value; uint confirmations; uint deadline; bool triggered; } function DSGroup( address[] members_, uint quorum_, uint window_ ) { members = members_; quorum = quorum_; window = window_; for (uint i = 0; i < members.length; i++) { isMember[members[i]] = true; } } function memberCount() constant returns (uint) { return members.length; } function target(uint id) constant returns (address) { return actions[id].target; } function calldata(uint id) constant returns (bytes) { return actions[id].calldata; } function value(uint id) constant returns (uint) { return actions[id].value; } function confirmations(uint id) constant returns (uint) { return actions[id].confirmations; } function deadline(uint id) constant returns (uint) { return actions[id].deadline; } function triggered(uint id) constant returns (bool) { return actions[id].triggered; } function confirmed(uint id) constant returns (bool) { return confirmations(id) >= quorum; } function expired(uint id) constant returns (bool) { return now > deadline(id); } function deposit() note payable { } function propose( address target, bytes calldata, uint value ) onlyMembers note returns (uint id) { id = ++actionCount; actions[id].target = target; actions[id].calldata = calldata; actions[id].value = value; actions[id].deadline = now + window; Proposed(id, calldata); } function confirm(uint id) onlyMembers onlyActive(id) note { assert(!confirmedBy[id][msg.sender]); confirmedBy[id][msg.sender] = true; actions[id].confirmations++; Confirmed(id, msg.sender); } function trigger(uint id) onlyMembers onlyActive(id) note {<FILL_FUNCTION_BODY> } modifier onlyMembers { assert(isMember[msg.sender]); _; } modifier onlyActive(uint id) { assert(!expired(id)); assert(!triggered(id)); _; } //------------------------------------------------------------------ // Legacy functions //------------------------------------------------------------------ function getInfo() constant returns ( uint quorum_, uint memberCount, uint window_, uint actionCount_ ) { return (quorum, members.length, window, actionCount); } function getActionStatus(uint id) constant returns ( uint confirmations, uint deadline, bool triggered, address target, uint value ) { return ( actions[id].confirmations, actions[id].deadline, actions[id].triggered, actions[id].target, actions[id].value ); } }
contract DSGroup is DSExec, DSNote { address[] public members; uint public quorum; uint public window; uint public actionCount; mapping (uint => Action) public actions; mapping (uint => mapping (address => bool)) public confirmedBy; mapping (address => bool) public isMember; // Legacy events event Proposed (uint id, bytes calldata); event Confirmed (uint id, address member); event Triggered (uint id); struct Action { address target; bytes calldata; uint value; uint confirmations; uint deadline; bool triggered; } function DSGroup( address[] members_, uint quorum_, uint window_ ) { members = members_; quorum = quorum_; window = window_; for (uint i = 0; i < members.length; i++) { isMember[members[i]] = true; } } function memberCount() constant returns (uint) { return members.length; } function target(uint id) constant returns (address) { return actions[id].target; } function calldata(uint id) constant returns (bytes) { return actions[id].calldata; } function value(uint id) constant returns (uint) { return actions[id].value; } function confirmations(uint id) constant returns (uint) { return actions[id].confirmations; } function deadline(uint id) constant returns (uint) { return actions[id].deadline; } function triggered(uint id) constant returns (bool) { return actions[id].triggered; } function confirmed(uint id) constant returns (bool) { return confirmations(id) >= quorum; } function expired(uint id) constant returns (bool) { return now > deadline(id); } function deposit() note payable { } function propose( address target, bytes calldata, uint value ) onlyMembers note returns (uint id) { id = ++actionCount; actions[id].target = target; actions[id].calldata = calldata; actions[id].value = value; actions[id].deadline = now + window; Proposed(id, calldata); } function confirm(uint id) onlyMembers onlyActive(id) note { assert(!confirmedBy[id][msg.sender]); confirmedBy[id][msg.sender] = true; actions[id].confirmations++; Confirmed(id, msg.sender); } <FILL_FUNCTION> modifier onlyMembers { assert(isMember[msg.sender]); _; } modifier onlyActive(uint id) { assert(!expired(id)); assert(!triggered(id)); _; } //------------------------------------------------------------------ // Legacy functions //------------------------------------------------------------------ function getInfo() constant returns ( uint quorum_, uint memberCount, uint window_, uint actionCount_ ) { return (quorum, members.length, window, actionCount); } function getActionStatus(uint id) constant returns ( uint confirmations, uint deadline, bool triggered, address target, uint value ) { return ( actions[id].confirmations, actions[id].deadline, actions[id].triggered, actions[id].target, actions[id].value ); } }
assert(confirmed(id)); actions[id].triggered = true; exec(actions[id].target, actions[id].calldata, actions[id].value); Triggered(id);
function trigger(uint id) onlyMembers onlyActive(id) note
function trigger(uint id) onlyMembers onlyActive(id) note
72280
MJCoin
transferFrom
contract MJCoin is MJCInterface {//, Owned, SafeMath string public symbol; string public name; uint8 public decimals; uint public _totalSupply; address payable public owner; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event FundTransfer(address seller, uint amount, bool isContribution); //address[] public CrowdsToSale; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "MJC"; name = "MaryJaneCoin"; decimals = 0; _totalSupply = 1000000; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function addSupply(uint newTokens) public returns (bool esito) { require(msg.sender == owner,"Solo il propritario puo aggiungere tokens"); _totalSupply = _totalSupply + newTokens; return true; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = balances[msg.sender] - tokens; balances[to] = balances[to] + tokens; emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public override returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ // function () external payable { // revert(); // } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ /* function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }*/ function buyToken(address payable sellerAddress, uint tokens) payable public override returns (bool success) {// uint256 sellerBalance = balanceOf(sellerAddress); require(tokens <= sellerBalance, "Not enough tokens in the Seller reserve"); balances[sellerAddress] = balances[sellerAddress] - tokens; balances[msg.sender] = balances[msg.sender] + tokens; emit Transfer(sellerAddress, msg.sender, tokens); sellerAddress.transfer(msg.value); emit Bought(msg.value); return true; } }
contract MJCoin is MJCInterface {//, Owned, SafeMath string public symbol; string public name; uint8 public decimals; uint public _totalSupply; address payable public owner; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event FundTransfer(address seller, uint amount, bool isContribution); //address[] public CrowdsToSale; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "MJC"; name = "MaryJaneCoin"; decimals = 0; _totalSupply = 1000000; owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } function addSupply(uint newTokens) public returns (bool esito) { require(msg.sender == owner,"Solo il propritario puo aggiungere tokens"); _totalSupply = _totalSupply + newTokens; return true; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public override returns (bool success) { balances[msg.sender] = balances[msg.sender] - tokens; balances[to] = balances[to] + tokens; emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ // function () external payable { // revert(); // } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ /* function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }*/ function buyToken(address payable sellerAddress, uint tokens) payable public override returns (bool success) {// uint256 sellerBalance = balanceOf(sellerAddress); require(tokens <= sellerBalance, "Not enough tokens in the Seller reserve"); balances[sellerAddress] = balances[sellerAddress] - tokens; balances[msg.sender] = balances[msg.sender] + tokens; emit Transfer(sellerAddress, msg.sender, tokens); sellerAddress.transfer(msg.value); emit Bought(msg.value); return true; } }
//balances[from] = safeSub(balances[from], tokens); balances[from] = balances[from] - tokens; //questa funzione permetta il ritiro dei token se l'asta non va in successo //rettifica momentanea ma poi attivare l'approvazione nel processo /* if(allowed[from][msg.sender]>0){ allowed[from][msg.sender] = //safeSub(allowed[from][msg.sender], tokens);}*/ allowed[from][msg.sender] = allowed[from][msg.sender] - tokens; // balances[to] = safeAdd(balances[to], tokens); balances[to] = balances[to] + tokens; emit Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public override returns (bool success)
// ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public override returns (bool success)
67338
KappiToken
transferFrom
contract KappiToken is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 10000000000*10**uint256(decimals); uint256 public constant initialPrice = 4 * 10**13; // 1 ETH / 25000 Kappi uint256 soldTokens = 0; uint256 public constant hardCap = 2000000000 * 10** uint256(decimals); // 20% uint public saleStart = 0; uint public saleFinish = 0; string public constant name = "Kappi Token"; string public constant symbol = "KAPP"; address payable constant teamAddress = address(0x65AAe2A7dd8f03DC80EeAD4be797255bC5804351); mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event Burned(address from, uint256 value); function totalSupply() public view returns (uint256) { return initialSupply; } function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) { if (balances[msg.sender] >= value && value > 0) { balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } else { return false; } } function transferFrom(address from, address to, uint256 value) public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } constructor () public payable { balances[teamAddress] = initialSupply * 8 / 10; balances[address(this)] = initialSupply * 2 / 10; saleStart = 1557075600; // timestamp (06-05-2019) saleFinish = 1562346000; //timestamp (06-07-2019) } function () external payable { require(now > saleStart && now < saleFinish); require (msg.value>=10**18); // 1 ETH min require (soldTokens<hardCap); uint256 valueToPass = 10 ** uint256(decimals) * msg.value / initialPrice; soldTokens += valueToPass; if (balances[address(this)] >= valueToPass && valueToPass > 0) { balances[msg.sender] = balances[msg.sender] + valueToPass; balances[address(this)] = balances[address(this)] - valueToPass; emit Transfer(address(this), msg.sender, valueToPass); } teamAddress.transfer(msg.value); } function burnUnsold() public returns (bool success) { require(now > saleFinish); uint burningAmount = balances[address(this)]; initialSupply -= burningAmount; balances[address(this)] = 0; emit Burned(address(this), burningAmount); return true; } }
contract KappiToken is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 10000000000*10**uint256(decimals); uint256 public constant initialPrice = 4 * 10**13; // 1 ETH / 25000 Kappi uint256 soldTokens = 0; uint256 public constant hardCap = 2000000000 * 10** uint256(decimals); // 20% uint public saleStart = 0; uint public saleFinish = 0; string public constant name = "Kappi Token"; string public constant symbol = "KAPP"; address payable constant teamAddress = address(0x65AAe2A7dd8f03DC80EeAD4be797255bC5804351); mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event Burned(address from, uint256 value); function totalSupply() public view returns (uint256) { return initialSupply; } function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) { if (balances[msg.sender] >= value && value > 0) { balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } else { return false; } } <FILL_FUNCTION> function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } constructor () public payable { balances[teamAddress] = initialSupply * 8 / 10; balances[address(this)] = initialSupply * 2 / 10; saleStart = 1557075600; // timestamp (06-05-2019) saleFinish = 1562346000; //timestamp (06-07-2019) } function () external payable { require(now > saleStart && now < saleFinish); require (msg.value>=10**18); // 1 ETH min require (soldTokens<hardCap); uint256 valueToPass = 10 ** uint256(decimals) * msg.value / initialPrice; soldTokens += valueToPass; if (balances[address(this)] >= valueToPass && valueToPass > 0) { balances[msg.sender] = balances[msg.sender] + valueToPass; balances[address(this)] = balances[address(this)] - valueToPass; emit Transfer(address(this), msg.sender, valueToPass); } teamAddress.transfer(msg.value); } function burnUnsold() public returns (bool success) { require(now > saleFinish); uint burningAmount = balances[address(this)]; initialSupply -= burningAmount; balances[address(this)] = 0; emit Burned(address(this), burningAmount); return true; } }
if (balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) { balances[to] += value; balances[from] -= value; allowed[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } else { return false; }
function transferFrom(address from, address to, uint256 value) public returns (bool success)
function transferFrom(address from, address to, uint256 value) public returns (bool success)
71980
RefundVault
null
contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public {<FILL_FUNCTION_BODY> } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } }
contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); <FILL_FUNCTION> /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } }
require(_wallet != address(0)); wallet = _wallet; state = State.Active;
constructor(address _wallet) public
/** * @param _wallet Vault address */ constructor(address _wallet) public
42411
MamaToken
buyTokens
contract MamaToken is ERC20Interface, Owned, SafeMath { string public constant name = "MamaMutua"; string public constant symbol = "M2M"; uint32 public constant decimals = 18; uint public _rate = 600; uint256 public _totalSupply = 60000000 * (10 ** 18); address owner; // amount of raised money in Wei uint256 public weiRaised; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; uint public openingTime = 1527638401; // 30 May 2018 00:01 uint public closingTime = 1546214399; // 30 Dec 2018 23:59 constructor() public { balances[msg.sender] = _totalSupply; owner = msg.sender; emit Transfer(address(0), msg.sender, _totalSupply); } function burn(uint256 _amount) public onlyOwner returns (bool) { require(_amount <= balances[msg.sender]); balances[msg.sender] = safeSub(balances[msg.sender], _amount); _totalSupply = safeSub(_totalSupply, _amount); emit Transfer(msg.sender, address(0), _amount); return true; } function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { require(_totalSupply + _amount >= _totalSupply); // Overflow check _totalSupply = safeAdd(_totalSupply, _amount); balances[_to] = safeAdd(balances[_to], _amount); emit Transfer(address(0), _to, _amount); return true; } 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, uint256 tokens) public returns (bool success) { /* Check if sender has balance and for overflows */ require(balances[msg.sender] >= tokens && balances[to] + tokens >= balances[to]); // mitigates the ERC20 short address attack if(msg.data.length < (2 * 32) + 4) { revert(); } balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { // mitigates the ERC20 spend/approval race condition if (tokens != 0 && allowed[msg.sender][spender] != 0) { return false; } allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { // mitigates the ERC20 short address attack if(msg.data.length < (3 * 32) + 4) { revert(); } balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function () external payable { // Check ICO period require(block.timestamp >= openingTime && block.timestamp <= closingTime); buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable {<FILL_FUNCTION_BODY> } function forwardFunds(uint256 _weiAmount) internal { owner.transfer(_weiAmount); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract MamaToken is ERC20Interface, Owned, SafeMath { string public constant name = "MamaMutua"; string public constant symbol = "M2M"; uint32 public constant decimals = 18; uint public _rate = 600; uint256 public _totalSupply = 60000000 * (10 ** 18); address owner; // amount of raised money in Wei uint256 public weiRaised; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; uint public openingTime = 1527638401; // 30 May 2018 00:01 uint public closingTime = 1546214399; // 30 Dec 2018 23:59 constructor() public { balances[msg.sender] = _totalSupply; owner = msg.sender; emit Transfer(address(0), msg.sender, _totalSupply); } function burn(uint256 _amount) public onlyOwner returns (bool) { require(_amount <= balances[msg.sender]); balances[msg.sender] = safeSub(balances[msg.sender], _amount); _totalSupply = safeSub(_totalSupply, _amount); emit Transfer(msg.sender, address(0), _amount); return true; } function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { require(_totalSupply + _amount >= _totalSupply); // Overflow check _totalSupply = safeAdd(_totalSupply, _amount); balances[_to] = safeAdd(balances[_to], _amount); emit Transfer(address(0), _to, _amount); return true; } 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, uint256 tokens) public returns (bool success) { /* Check if sender has balance and for overflows */ require(balances[msg.sender] >= tokens && balances[to] + tokens >= balances[to]); // mitigates the ERC20 short address attack if(msg.data.length < (2 * 32) + 4) { revert(); } balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { // mitigates the ERC20 spend/approval race condition if (tokens != 0 && allowed[msg.sender][spender] != 0) { return false; } allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { // mitigates the ERC20 short address attack if(msg.data.length < (3 * 32) + 4) { revert(); } balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function () external payable { // Check ICO period require(block.timestamp >= openingTime && block.timestamp <= closingTime); buyTokens(msg.sender); } <FILL_FUNCTION> function forwardFunds(uint256 _weiAmount) internal { owner.transfer(_weiAmount); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
require(beneficiary != address(0)); require(beneficiary != 0x0); require(msg.value > 1 finney); uint256 weiAmount = msg.value; // update state weiRaised = safeAdd(weiRaised, weiAmount); // calculate token amount to be created uint256 tokensIssued = safeMul(_rate, weiAmount); // transfer tokens balances[owner] = safeSub(balances[owner], tokensIssued); balances[beneficiary] = safeAdd(balances[beneficiary], tokensIssued); emit Transfer(owner, beneficiary, tokensIssued); forwardFunds(weiAmount);
function buyTokens(address beneficiary) public payable
// low level token purchase function function buyTokens(address beneficiary) public payable
62292
CategoryManager
createCategory
contract CategoryManager is Ownable { /** * Content */ IexecODBLibCore.Category[] m_categories; /** * Event */ event CreateCategory( uint256 catid, string name, string description, uint256 workClockTimeRef); /** * Constructor */ constructor() public { } /** * Accessors */ function viewCategory(uint256 _catid) external view returns (IexecODBLibCore.Category memory category) { return m_categories[_catid]; } function countCategory() external view returns (uint256 count) { return m_categories.length; } /** * Methods */ function createCategory( string calldata name, string calldata description, uint256 workClockTimeRef) external onlyOwner returns (uint256) {<FILL_FUNCTION_BODY> } /** * TODO: move to struct based initialization ? * function createCategory(IexecODBLib.Category _category) public onlyOwner returns (uint256) { uint256 catid = m_categories.push(_category); emit CreateCategory( catid, _category.name, _category.description, _category.workClockTimeRef ); return catid; } */ }
contract CategoryManager is Ownable { /** * Content */ IexecODBLibCore.Category[] m_categories; /** * Event */ event CreateCategory( uint256 catid, string name, string description, uint256 workClockTimeRef); /** * Constructor */ constructor() public { } /** * Accessors */ function viewCategory(uint256 _catid) external view returns (IexecODBLibCore.Category memory category) { return m_categories[_catid]; } function countCategory() external view returns (uint256 count) { return m_categories.length; } <FILL_FUNCTION> /** * TODO: move to struct based initialization ? * function createCategory(IexecODBLib.Category _category) public onlyOwner returns (uint256) { uint256 catid = m_categories.push(_category); emit CreateCategory( catid, _category.name, _category.description, _category.workClockTimeRef ); return catid; } */ }
uint256 catid = m_categories.push(IexecODBLibCore.Category( name, description, workClockTimeRef )) - 1; emit CreateCategory( catid, name, description, workClockTimeRef ); return catid;
function createCategory( string calldata name, string calldata description, uint256 workClockTimeRef) external onlyOwner returns (uint256)
/** * Methods */ function createCategory( string calldata name, string calldata description, uint256 workClockTimeRef) external onlyOwner returns (uint256)
45913
KaiInu
approve
contract KaiInu is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "Kai Inu"; symbol = "KAI"; decimals = 9; _totalSupply = 100000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, 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); emit Transfer(from, to, tokens); return true; } }
contract KaiInu is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "Kai Inu"; symbol = "KAI"; decimals = 9; _totalSupply = 100000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, 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); emit Transfer(from, to, tokens); return true; } }
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true;
function approve(address spender, uint tokens) public returns (bool success)
function approve(address spender, uint tokens) public returns (bool success)
77918
Chedinja
openTrading
contract Chedinja is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Chedinja"; string private constant _symbol = "CHEDINJA"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x1af7E62271a7c78E5eAe3e0Ce1F66FEDf07Dc54a); _feeAddrWallet2 = payable(0x1af7E62271a7c78E5eAe3e0Ce1F66FEDf07Dc54a); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xd55FF395A7360be0c79D3556b0f65ef44b319575), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 10; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() {<FILL_FUNCTION_BODY> } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract Chedinja is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Chedinja"; string private constant _symbol = "CHEDINJA"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x1af7E62271a7c78E5eAe3e0Ce1F66FEDf07Dc54a); _feeAddrWallet2 = payable(0x1af7E62271a7c78E5eAe3e0Ce1F66FEDf07Dc54a); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xd55FF395A7360be0c79D3556b0f65ef44b319575), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 10; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } <FILL_FUNCTION> function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 50000000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
function openTrading() external onlyOwner()
function openTrading() external onlyOwner()
83332
GomicsGMC
unfreeze
contract GomicsGMC is ERC20 { string public constant name = "Gomics GMC"; string public constant symbol = "GMC"; uint8 public constant decimals = 18; uint256 public constant initialSupply = 500000000 * (10**uint256(decimals)); constructor() public { super._mint(msg.sender, initialSupply); owner = msg.sender; } address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); modifier onlyOwner() { require(msg.sender == owner, "Not 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), "Already owner"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function dropToken(address[] memory _receivers, uint256[] memory _values) public onlyOwner { require(_receivers.length != 0); require(_receivers.length == _values.length); for (uint256 i = 0; i < _receivers.length; i++) { transfer(_receivers[i], _values[i]); emit Transfer(msg.sender, _receivers[i], _values[i]); } } event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused, "Paused by owner"); _; } modifier whenPaused() { require(paused, "Not paused now"); _; } function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } event Frozen(address target); event Unfrozen(address target); mapping(address => bool) internal freezes; modifier whenNotFrozen() { require(!freezes[msg.sender], "Sender account is locked."); _; } function freeze(address _target) public onlyOwner { freezes[_target] = true; emit Frozen(_target); } function unfreeze(address _target) public onlyOwner {<FILL_FUNCTION_BODY> } function isFrozen(address _target) public view returns (bool) { return freezes[_target]; } function transfer(address _to, uint256 _value) public whenNotFrozen whenNotPaused returns (bool) { releaseLock(msg.sender); return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { require(!freezes[_from], "From account is locked."); releaseLock(_from); return super.transferFrom(_from, _to, _value); } event Mint(address indexed to, uint256 amount); function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { super._mint(_to, _amount); emit Mint(_to, _amount); return true; } event Burn(address indexed burner, uint256 value); function burn(address _who, uint256 _value) public onlyOwner { require(_value <= super.balanceOf(_who), "Balance is too small."); _burn(_who, _value); emit Burn(_who, _value); } struct LockInfo { uint256 releaseTime; uint256 balance; } mapping(address => LockInfo[]) internal lockInfo; event Lock(address indexed holder, uint256 value, uint256 releaseTime); event Unlock(address indexed holder, uint256 value); function balanceOf(address _holder) public view returns (uint256 balance) { uint256 lockedBalance = 0; for (uint256 i = 0; i < lockInfo[_holder].length; i++) { lockedBalance = lockedBalance.add(lockInfo[_holder][i].balance); } return super.balanceOf(_holder).add(lockedBalance); } function releaseLock(address _holder) internal { for (uint256 i = 0; i < lockInfo[_holder].length; i++) { if (lockInfo[_holder][i].releaseTime <= now) { _balances[_holder] = _balances[_holder].add( lockInfo[_holder][i].balance ); emit Unlock(_holder, lockInfo[_holder][i].balance); lockInfo[_holder][i].balance = 0; if (i != lockInfo[_holder].length - 1) { lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder] .length - 1]; i--; } lockInfo[_holder].length--; } } } function lockCount(address _holder) public view returns (uint256) { return lockInfo[_holder].length; } function lockState(address _holder, uint256 _idx) public view returns (uint256, uint256) { return ( lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance ); } function lock( address _holder, uint256 _amount, uint256 _releaseTime ) public onlyOwner { require(super.balanceOf(_holder) >= _amount, "Balance is too small."); _balances[_holder] = _balances[_holder].sub(_amount); lockInfo[_holder].push(LockInfo(_releaseTime, _amount)); emit Lock(_holder, _amount, _releaseTime); } function lockAfter( address _holder, uint256 _amount, uint256 _afterTime ) public onlyOwner { require(super.balanceOf(_holder) >= _amount, "Balance is too small."); _balances[_holder] = _balances[_holder].sub(_amount); lockInfo[_holder].push(LockInfo(now + _afterTime, _amount)); emit Lock(_holder, _amount, now + _afterTime); } function unlock(address _holder, uint256 i) public onlyOwner { require(i < lockInfo[_holder].length, "No lock information."); _balances[_holder] = _balances[_holder].add( lockInfo[_holder][i].balance ); emit Unlock(_holder, lockInfo[_holder][i].balance); lockInfo[_holder][i].balance = 0; if (i != lockInfo[_holder].length - 1) { lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1]; } lockInfo[_holder].length--; } function transferWithLock( address _to, uint256 _value, uint256 _releaseTime ) public onlyOwner returns (bool) { require(_to != address(0), "wrong address"); require(_value <= super.balanceOf(owner), "Not enough balance"); _balances[owner] = _balances[owner].sub(_value); lockInfo[_to].push(LockInfo(_releaseTime, _value)); emit Transfer(owner, _to, _value); emit Lock(_to, _value, _releaseTime); return true; } function transferWithLockAfter( address _to, uint256 _value, uint256 _afterTime ) public onlyOwner returns (bool) { require(_to != address(0), "wrong address"); require(_value <= super.balanceOf(owner), "Not enough balance"); _balances[owner] = _balances[owner].sub(_value); lockInfo[_to].push(LockInfo(now + _afterTime, _value)); emit Transfer(owner, _to, _value); emit Lock(_to, _value, now + _afterTime); return true; } function currentTime() public view returns (uint256) { return now; } function afterTime(uint256 _value) public view returns (uint256) { return now + _value; } }
contract GomicsGMC is ERC20 { string public constant name = "Gomics GMC"; string public constant symbol = "GMC"; uint8 public constant decimals = 18; uint256 public constant initialSupply = 500000000 * (10**uint256(decimals)); constructor() public { super._mint(msg.sender, initialSupply); owner = msg.sender; } address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); modifier onlyOwner() { require(msg.sender == owner, "Not 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), "Already owner"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function dropToken(address[] memory _receivers, uint256[] memory _values) public onlyOwner { require(_receivers.length != 0); require(_receivers.length == _values.length); for (uint256 i = 0; i < _receivers.length; i++) { transfer(_receivers[i], _values[i]); emit Transfer(msg.sender, _receivers[i], _values[i]); } } event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused, "Paused by owner"); _; } modifier whenPaused() { require(paused, "Not paused now"); _; } function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } event Frozen(address target); event Unfrozen(address target); mapping(address => bool) internal freezes; modifier whenNotFrozen() { require(!freezes[msg.sender], "Sender account is locked."); _; } function freeze(address _target) public onlyOwner { freezes[_target] = true; emit Frozen(_target); } <FILL_FUNCTION> function isFrozen(address _target) public view returns (bool) { return freezes[_target]; } function transfer(address _to, uint256 _value) public whenNotFrozen whenNotPaused returns (bool) { releaseLock(msg.sender); return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { require(!freezes[_from], "From account is locked."); releaseLock(_from); return super.transferFrom(_from, _to, _value); } event Mint(address indexed to, uint256 amount); function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { super._mint(_to, _amount); emit Mint(_to, _amount); return true; } event Burn(address indexed burner, uint256 value); function burn(address _who, uint256 _value) public onlyOwner { require(_value <= super.balanceOf(_who), "Balance is too small."); _burn(_who, _value); emit Burn(_who, _value); } struct LockInfo { uint256 releaseTime; uint256 balance; } mapping(address => LockInfo[]) internal lockInfo; event Lock(address indexed holder, uint256 value, uint256 releaseTime); event Unlock(address indexed holder, uint256 value); function balanceOf(address _holder) public view returns (uint256 balance) { uint256 lockedBalance = 0; for (uint256 i = 0; i < lockInfo[_holder].length; i++) { lockedBalance = lockedBalance.add(lockInfo[_holder][i].balance); } return super.balanceOf(_holder).add(lockedBalance); } function releaseLock(address _holder) internal { for (uint256 i = 0; i < lockInfo[_holder].length; i++) { if (lockInfo[_holder][i].releaseTime <= now) { _balances[_holder] = _balances[_holder].add( lockInfo[_holder][i].balance ); emit Unlock(_holder, lockInfo[_holder][i].balance); lockInfo[_holder][i].balance = 0; if (i != lockInfo[_holder].length - 1) { lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder] .length - 1]; i--; } lockInfo[_holder].length--; } } } function lockCount(address _holder) public view returns (uint256) { return lockInfo[_holder].length; } function lockState(address _holder, uint256 _idx) public view returns (uint256, uint256) { return ( lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance ); } function lock( address _holder, uint256 _amount, uint256 _releaseTime ) public onlyOwner { require(super.balanceOf(_holder) >= _amount, "Balance is too small."); _balances[_holder] = _balances[_holder].sub(_amount); lockInfo[_holder].push(LockInfo(_releaseTime, _amount)); emit Lock(_holder, _amount, _releaseTime); } function lockAfter( address _holder, uint256 _amount, uint256 _afterTime ) public onlyOwner { require(super.balanceOf(_holder) >= _amount, "Balance is too small."); _balances[_holder] = _balances[_holder].sub(_amount); lockInfo[_holder].push(LockInfo(now + _afterTime, _amount)); emit Lock(_holder, _amount, now + _afterTime); } function unlock(address _holder, uint256 i) public onlyOwner { require(i < lockInfo[_holder].length, "No lock information."); _balances[_holder] = _balances[_holder].add( lockInfo[_holder][i].balance ); emit Unlock(_holder, lockInfo[_holder][i].balance); lockInfo[_holder][i].balance = 0; if (i != lockInfo[_holder].length - 1) { lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1]; } lockInfo[_holder].length--; } function transferWithLock( address _to, uint256 _value, uint256 _releaseTime ) public onlyOwner returns (bool) { require(_to != address(0), "wrong address"); require(_value <= super.balanceOf(owner), "Not enough balance"); _balances[owner] = _balances[owner].sub(_value); lockInfo[_to].push(LockInfo(_releaseTime, _value)); emit Transfer(owner, _to, _value); emit Lock(_to, _value, _releaseTime); return true; } function transferWithLockAfter( address _to, uint256 _value, uint256 _afterTime ) public onlyOwner returns (bool) { require(_to != address(0), "wrong address"); require(_value <= super.balanceOf(owner), "Not enough balance"); _balances[owner] = _balances[owner].sub(_value); lockInfo[_to].push(LockInfo(now + _afterTime, _value)); emit Transfer(owner, _to, _value); emit Lock(_to, _value, now + _afterTime); return true; } function currentTime() public view returns (uint256) { return now; } function afterTime(uint256 _value) public view returns (uint256) { return now + _value; } }
freezes[_target] = false; emit Unfrozen(_target);
function unfreeze(address _target) public onlyOwner
function unfreeze(address _target) public onlyOwner
80915
Context
_msgSender
contract Context { function _msgSender() internal view returns (address payable) {<FILL_FUNCTION_BODY> } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
contract Context { <FILL_FUNCTION> function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
return msg.sender;
function _msgSender() internal view returns (address payable)
function _msgSender() internal view returns (address payable)
81081
ConvertLib
toUnixtime
contract ConvertLib { // .. since beginning of the year uint16[12] days_since = [ 11, 42, 70, 101, 131, 162, 192, 223, 254, 284, 315, 345 ]; function b32toString(bytes32 x) internal returns (string) { // gas usage: about 1K gas per char. bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function b32toHexString(bytes32 x) returns (string) { bytes memory b = new bytes(64); for (uint i = 0; i < 32; i++) { uint8 by = uint8(uint(x) / (2**(8*(31 - i)))); uint8 high = by/16; uint8 low = by - 16*high; if (high > 9) { high += 39; } if (low > 9) { low += 39; } b[2*i] = byte(high+48); b[2*i+1] = byte(low+48); } return string(b); } function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i<bresult.length; i++) { if ((bresult[i] >= 48)&&(bresult[i] <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) { decimals = true; } } if (_b > 0) { mint *= 10**_b; } return mint; } // the following function yields correct results in the time between 1.3.2016 and 28.02.2020, // so within the validity of the contract its correct. function toUnixtime(bytes32 _dayMonthYear) constant returns (uint unixtime) {<FILL_FUNCTION_BODY> } }
contract ConvertLib { // .. since beginning of the year uint16[12] days_since = [ 11, 42, 70, 101, 131, 162, 192, 223, 254, 284, 315, 345 ]; function b32toString(bytes32 x) internal returns (string) { // gas usage: about 1K gas per char. bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } function b32toHexString(bytes32 x) returns (string) { bytes memory b = new bytes(64); for (uint i = 0; i < 32; i++) { uint8 by = uint8(uint(x) / (2**(8*(31 - i)))); uint8 high = by/16; uint8 low = by - 16*high; if (high > 9) { high += 39; } if (low > 9) { low += 39; } b[2*i] = byte(high+48); b[2*i+1] = byte(low+48); } return string(b); } function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i<bresult.length; i++) { if ((bresult[i] >= 48)&&(bresult[i] <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) { decimals = true; } } if (_b > 0) { mint *= 10**_b; } return mint; } <FILL_FUNCTION> }
// _day_month_year = /dep/2016/09/10 bytes memory bDmy = bytes(b32toString(_dayMonthYear)); bytes memory temp2 = bytes(new string(2)); bytes memory temp4 = bytes(new string(4)); temp4[0] = bDmy[5]; temp4[1] = bDmy[6]; temp4[2] = bDmy[7]; temp4[3] = bDmy[8]; uint year = parseInt(string(temp4)); temp2[0] = bDmy[10]; temp2[1] = bDmy[11]; uint month = parseInt(string(temp2)); temp2[0] = bDmy[13]; temp2[1] = bDmy[14]; uint day = parseInt(string(temp2)); unixtime = ((year - 1970) * 365 + days_since[month-1] + day) * 86400;
function toUnixtime(bytes32 _dayMonthYear) constant returns (uint unixtime)
// the following function yields correct results in the time between 1.3.2016 and 28.02.2020, // so within the validity of the contract its correct. function toUnixtime(bytes32 _dayMonthYear) constant returns (uint unixtime)
10416
storer
storer
contract storer { address public owner; string public log; function storer() {<FILL_FUNCTION_BODY> } modifier onlyOwner { if (msg.sender != owner) throw; _; } function store(string _log) onlyOwner() { log = _log; } function kill() onlyOwner() { selfdestruct(owner); } /* 09.10.2017 transfert sequestre QOA 0xe26c87f3ec0ab4f93713e1b90f7176e2e75975776683f3877dbd536ed48f7e06 0x296e781bbb0179b032cbcc31e4b6cdab724b2773 0xf9da398b784d89f2ce604ed96b62f841407de477 -46.00000000 09.10.2017 transfert sequestre QOA 0xce314a0e530d791774347196a68c49ea2df1203cd933e483608eee3bae3b5daf 0x807a68ac406d14ef0c230f78d2ebe2e31b615351 0x51ccbd09a64082340ca526f706b98624f8e54940 -400.00000000 09.10.2017 transfert sequestre QOA 0x40dd89b2ec9884d7647cb7b0c6bbb5a6b7d5da2ffd2934891d19e55c7f2e9268 0xbb55b8bdde909840da6992226f786cd9ebb5e504 0x39993f9aa307dbc339b3832c3d027059b98d17a1 -71.27601354 09.10.2017 transfert sequestre QOA 0xea177ca25391a0179090a1fb3e1975e7b9f6c8fa4938d0c23da3c54e9ef21725 0x11e2d654b3e2046c0e388b3eebc1b134258fc33b 0x9de5e10cd47ce17f0dd00cd4b32470d0692ef9ae -71.90814623 09.10.2017 transfert sequestre QOA 0x44787fcf2f5c2589550fb80fe2d172487b27e43eaee0e063f300329301411008 0x8821f11be781846813674e68173742ac41a2df50 0x43fd9cc5e47230011c9835c634fbb62f1c511b7d -70.94260947 09.10.2017 transfert sequestre QOA 0x622863fb66051a8c60b0a59894444d79849453d3a851c90a6a9162359c4fc60e 0x2a069330bf9ab1fc73f55f941cbedd1fb76a445c 0xf49bb66ca67fdde87d83eb77a480d681dd678222 -72.09147030 09.10.2017 transfert sequestre QOA 0xa6ac6b7e019d9dad2d54d140371d5216a3b3f986863235b576696ee0d04000d1 0x48e2bb053a2a9f1c222295a5a99f1a11bbf320ac 0x8271b2e8cbe29396e9563229030c89679b9470db -121.98864614 09.10.2017 transfert sequestre QOA 0xffe4941f3b2564c149f5e7534a951f608a7d35553130ca43a516e61bb8631255 0x236f9f97e0e62388479bf9e5ba4889e46b0273c3 0x97bfe40199d6ba4c8acd57795d3a7d624b9aa14d -100.01000000 09.10.2017 transfert sequestre QOA 0xcf5dd5605513b8ae32eb0db2f5399172b11f68191ad5e05b6fe1a0124bd62daf 0x820b92a043ad40767196b6296b3f45b32289cbc2 0xa1cda043a5a72a1a5d13cb12aa9138c4f930d971 -20.00000000 09.10.2017 transfert sequestre QOA 0xf2a74f1e267054146ac0c432e6013e0682ca9b152048633adadadc52e12879ae 0x22b84d5ffea8b801c0422afe752377a64aa738c2 0xaea57f34d0f7c04bf6f29e4b91baf66955901035 -45.00000000 10.10.2017 transfert sequestre QOA 0x860dae67fb188d682f3beb0417bff1ebfe2d221c9632b59fff178e69951b4882 0x3d91e28898d2b5e968df2a17e0bedf29e30929ea 0x82ab4851dcc3e6f18c9e904e86aefedb13576cfe -132.48871900 10.10.2017 transfert sequestre QOA 0x8514ef4d8de728bd85d4d28281ab3ba2f18878bdedb077547f88cf2b8edc1d11 0xc8e99360d5b672d66610b0db0807611fe954ccf9 0x2ecd81e43c1f66185446f4af7dfeaa6aae249f55 -200.00000000 10.10.2017 transfert sequestre QOA 0x321df7e4183d6e36f47901eea9bb48e5ab43ca10be8d62edf368c8bbd3a0185f 0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be 0xd078b74a71ae8f1439a9825088f0f98da30951ea -99.99500000 10.10.2017 transfert sequestre QOA 0x2ed8044b2b9c92618de414ff59fcb6bbd5971f93a717e43be2587ec12285c12e 0xcab5efc6feeafcf9cd8a2142765fb9fafc5eb909 0x5baeac0a0417a05733884852aa068b706967e790 -254.74201230 10.10.2017 transfert sequestre QOA 0x585a0a92b58ac66b7869803bc0f82c06166e40ca917621654480957ba14adda9 0x5e40cb83db53bab573558ec7ea2d92959acebb8c 0x5baeac0a0417a05733884852aa068b706967e790 -119.99895000 10.10.2017 transfert sequestre QOA 0x4e6e337e6cbb3a672c216912b9293a64f608766e5b881b1c987f8596252cd145 0xb79ff15d64bdb69c51cfe2357cd112abfaf890ac 0x85d468b33263edab6da35992042f6c8cafc51608 -71.81983457 10.10.2017 transfert sequestre QOA 0x758eef1560b80cff63c06b3f80de3cfa9a0a306b3002f0813ec5fc8ac049ca96 0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98 0x576b225e7bd0db734a6f4747a4ccb8025ea12a5f -64.55400000 10.10.2017 transfert sequestre QOA 0xd2cbfce27fa1b083ffbf2921d57be0b3e6627017695d3a84fda45db7a5449e06 0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98 0x84b4f45901bbd39c734ba0ce3e5e7525f0c6a0ac -40.03636412 10.10.2017 transfert sequestre QOA 0xf245271f7c9855f2a1094fbe7dca860c12f85a6442e22be6b4ee30f89553060e 0xbaf5f755c0eef0795fab4e0a435cce59635f4b4a 0x767144057e13cc56a3ece780322995f8b7b9bcba -109.64711845 -2'112.49888411 */ }
contract storer { address public owner; string public log; <FILL_FUNCTION> modifier onlyOwner { if (msg.sender != owner) throw; _; } function store(string _log) onlyOwner() { log = _log; } function kill() onlyOwner() { selfdestruct(owner); } /* 09.10.2017 transfert sequestre QOA 0xe26c87f3ec0ab4f93713e1b90f7176e2e75975776683f3877dbd536ed48f7e06 0x296e781bbb0179b032cbcc31e4b6cdab724b2773 0xf9da398b784d89f2ce604ed96b62f841407de477 -46.00000000 09.10.2017 transfert sequestre QOA 0xce314a0e530d791774347196a68c49ea2df1203cd933e483608eee3bae3b5daf 0x807a68ac406d14ef0c230f78d2ebe2e31b615351 0x51ccbd09a64082340ca526f706b98624f8e54940 -400.00000000 09.10.2017 transfert sequestre QOA 0x40dd89b2ec9884d7647cb7b0c6bbb5a6b7d5da2ffd2934891d19e55c7f2e9268 0xbb55b8bdde909840da6992226f786cd9ebb5e504 0x39993f9aa307dbc339b3832c3d027059b98d17a1 -71.27601354 09.10.2017 transfert sequestre QOA 0xea177ca25391a0179090a1fb3e1975e7b9f6c8fa4938d0c23da3c54e9ef21725 0x11e2d654b3e2046c0e388b3eebc1b134258fc33b 0x9de5e10cd47ce17f0dd00cd4b32470d0692ef9ae -71.90814623 09.10.2017 transfert sequestre QOA 0x44787fcf2f5c2589550fb80fe2d172487b27e43eaee0e063f300329301411008 0x8821f11be781846813674e68173742ac41a2df50 0x43fd9cc5e47230011c9835c634fbb62f1c511b7d -70.94260947 09.10.2017 transfert sequestre QOA 0x622863fb66051a8c60b0a59894444d79849453d3a851c90a6a9162359c4fc60e 0x2a069330bf9ab1fc73f55f941cbedd1fb76a445c 0xf49bb66ca67fdde87d83eb77a480d681dd678222 -72.09147030 09.10.2017 transfert sequestre QOA 0xa6ac6b7e019d9dad2d54d140371d5216a3b3f986863235b576696ee0d04000d1 0x48e2bb053a2a9f1c222295a5a99f1a11bbf320ac 0x8271b2e8cbe29396e9563229030c89679b9470db -121.98864614 09.10.2017 transfert sequestre QOA 0xffe4941f3b2564c149f5e7534a951f608a7d35553130ca43a516e61bb8631255 0x236f9f97e0e62388479bf9e5ba4889e46b0273c3 0x97bfe40199d6ba4c8acd57795d3a7d624b9aa14d -100.01000000 09.10.2017 transfert sequestre QOA 0xcf5dd5605513b8ae32eb0db2f5399172b11f68191ad5e05b6fe1a0124bd62daf 0x820b92a043ad40767196b6296b3f45b32289cbc2 0xa1cda043a5a72a1a5d13cb12aa9138c4f930d971 -20.00000000 09.10.2017 transfert sequestre QOA 0xf2a74f1e267054146ac0c432e6013e0682ca9b152048633adadadc52e12879ae 0x22b84d5ffea8b801c0422afe752377a64aa738c2 0xaea57f34d0f7c04bf6f29e4b91baf66955901035 -45.00000000 10.10.2017 transfert sequestre QOA 0x860dae67fb188d682f3beb0417bff1ebfe2d221c9632b59fff178e69951b4882 0x3d91e28898d2b5e968df2a17e0bedf29e30929ea 0x82ab4851dcc3e6f18c9e904e86aefedb13576cfe -132.48871900 10.10.2017 transfert sequestre QOA 0x8514ef4d8de728bd85d4d28281ab3ba2f18878bdedb077547f88cf2b8edc1d11 0xc8e99360d5b672d66610b0db0807611fe954ccf9 0x2ecd81e43c1f66185446f4af7dfeaa6aae249f55 -200.00000000 10.10.2017 transfert sequestre QOA 0x321df7e4183d6e36f47901eea9bb48e5ab43ca10be8d62edf368c8bbd3a0185f 0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be 0xd078b74a71ae8f1439a9825088f0f98da30951ea -99.99500000 10.10.2017 transfert sequestre QOA 0x2ed8044b2b9c92618de414ff59fcb6bbd5971f93a717e43be2587ec12285c12e 0xcab5efc6feeafcf9cd8a2142765fb9fafc5eb909 0x5baeac0a0417a05733884852aa068b706967e790 -254.74201230 10.10.2017 transfert sequestre QOA 0x585a0a92b58ac66b7869803bc0f82c06166e40ca917621654480957ba14adda9 0x5e40cb83db53bab573558ec7ea2d92959acebb8c 0x5baeac0a0417a05733884852aa068b706967e790 -119.99895000 10.10.2017 transfert sequestre QOA 0x4e6e337e6cbb3a672c216912b9293a64f608766e5b881b1c987f8596252cd145 0xb79ff15d64bdb69c51cfe2357cd112abfaf890ac 0x85d468b33263edab6da35992042f6c8cafc51608 -71.81983457 10.10.2017 transfert sequestre QOA 0x758eef1560b80cff63c06b3f80de3cfa9a0a306b3002f0813ec5fc8ac049ca96 0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98 0x576b225e7bd0db734a6f4747a4ccb8025ea12a5f -64.55400000 10.10.2017 transfert sequestre QOA 0xd2cbfce27fa1b083ffbf2921d57be0b3e6627017695d3a84fda45db7a5449e06 0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98 0x84b4f45901bbd39c734ba0ce3e5e7525f0c6a0ac -40.03636412 10.10.2017 transfert sequestre QOA 0xf245271f7c9855f2a1094fbe7dca860c12f85a6442e22be6b4ee30f89553060e 0xbaf5f755c0eef0795fab4e0a435cce59635f4b4a 0x767144057e13cc56a3ece780322995f8b7b9bcba -109.64711845 -2'112.49888411 */ }
owner = msg.sender ;
function storer()
function storer()
30864
Airdrop
_getTokenAmount
contract Airdrop { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; address owner = 0x0; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; modifier isOwner { assert(owner == msg.sender); _; } /** * Event for token drop logging * @param sender who send the tokens * @param beneficiary who got the tokens * @param value weis sent * @param amount amount of tokens dropped */ event TokenDropped( address indexed sender, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _token Address of the token being sold */ constructor(ERC20 _token) public { require(_token != address(0)); owner = msg.sender; token = _token; } // ----------------------------------------- // External interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { sendAirDrops(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function sendAirDrops(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created // uint256 tokens = 50 * (10 ** 6); uint256 tokens = _getTokenAmount(weiAmount); _processAirdrop(_beneficiary, tokens); emit TokenDropped( msg.sender, _beneficiary, weiAmount, tokens ); } function collect(uint256 _weiAmount) isOwner public { address thisAddress = this; owner.transfer(thisAddress.balance); } function withdraw(uint256 _tokenAmount) isOwner public { token.safeTransfer(owner, _tokenAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount >= 1 * (10 ** 17)); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {<FILL_FUNCTION_BODY> } /** * @dev Source of tokens. Override this method to modify the way in which the action ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processAirdrop( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } }
contract Airdrop { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; address owner = 0x0; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; modifier isOwner { assert(owner == msg.sender); _; } /** * Event for token drop logging * @param sender who send the tokens * @param beneficiary who got the tokens * @param value weis sent * @param amount amount of tokens dropped */ event TokenDropped( address indexed sender, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _token Address of the token being sold */ constructor(ERC20 _token) public { require(_token != address(0)); owner = msg.sender; token = _token; } // ----------------------------------------- // External interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { sendAirDrops(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function sendAirDrops(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created // uint256 tokens = 50 * (10 ** 6); uint256 tokens = _getTokenAmount(weiAmount); _processAirdrop(_beneficiary, tokens); emit TokenDropped( msg.sender, _beneficiary, weiAmount, tokens ); } function collect(uint256 _weiAmount) isOwner public { address thisAddress = this; owner.transfer(thisAddress.balance); } function withdraw(uint256 _tokenAmount) isOwner public { token.safeTransfer(owner, _tokenAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount >= 1 * (10 ** 17)); } <FILL_FUNCTION> /** * @dev Source of tokens. Override this method to modify the way in which the action ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processAirdrop( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } }
uint256 seed = _weiAmount.div(1 * (10**9)); return seed.mul(33);
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256)
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256)
16257
ENBToken
withdrawEther
contract ENBToken is BurnableToken, MintableToken, PausableToken { // Public variables of the token string public name; string public symbol; // 等同于Wei的概念, decimals is the strongly suggested default, avoid changing it uint8 public decimals; function ENBToken() public { name = "EnermyBlock"; symbol = "ENB"; decimals = 18; totalSupply = 1000000000 * 10 ** uint256(decimals); // Allocate initial balance to the owner balances[msg.sender] = totalSupply; } // transfer balance to owner function withdrawEther() onlyOwner public {<FILL_FUNCTION_BODY> } // can accept ether function() payable public { } }
contract ENBToken is BurnableToken, MintableToken, PausableToken { // Public variables of the token string public name; string public symbol; // 等同于Wei的概念, decimals is the strongly suggested default, avoid changing it uint8 public decimals; function ENBToken() public { name = "EnermyBlock"; symbol = "ENB"; decimals = 18; totalSupply = 1000000000 * 10 ** uint256(decimals); // Allocate initial balance to the owner balances[msg.sender] = totalSupply; } <FILL_FUNCTION> // can accept ether function() payable public { } }
owner.transfer(this.balance);
function withdrawEther() onlyOwner public
// transfer balance to owner function withdrawEther() onlyOwner public
778
NFTeGG_Burner
burnERC721
contract NFTeGG_Burner is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; address constant eFAME = address(0xD821E91DB8aED33641ac5D122553cf10de49c8eF); address constant NFTeGG = address(0x10a7ecF97c46e3229fE1B801a5943153762e0cF0); // ctor constructor () public { } function burnNFTeGG(uint256 tokenid) external { address user = msg.sender; IERC721(NFTeGG).transferFrom(user, address(0), tokenid); } function burnERC721(address token, uint256 tokenid) external {<FILL_FUNCTION_BODY> } function burneFAME(uint256 value) external { address user = msg.sender; IERC20(eFAME).safeTransferFrom(user, address(0), value); } function burnERC20(address token, uint256 value) external { address user = msg.sender; IERC20(token).safeTransferFrom(user, address(0), value); } }
contract NFTeGG_Burner is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; address constant eFAME = address(0xD821E91DB8aED33641ac5D122553cf10de49c8eF); address constant NFTeGG = address(0x10a7ecF97c46e3229fE1B801a5943153762e0cF0); // ctor constructor () public { } function burnNFTeGG(uint256 tokenid) external { address user = msg.sender; IERC721(NFTeGG).transferFrom(user, address(0), tokenid); } <FILL_FUNCTION> function burneFAME(uint256 value) external { address user = msg.sender; IERC20(eFAME).safeTransferFrom(user, address(0), value); } function burnERC20(address token, uint256 value) external { address user = msg.sender; IERC20(token).safeTransferFrom(user, address(0), value); } }
address user = msg.sender; IERC721(token).transferFrom(user, address(0), tokenid);
function burnERC721(address token, uint256 tokenid) external
function burnERC721(address token, uint256 tokenid) external
77915
Pausable
pause
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } function paused() public view returns(bool) { return _paused; } modifier whenNotPaused() { require(!_paused); _; } modifier whenPaused() { require(_paused); _; } function pause() public onlyPauser whenNotPaused {<FILL_FUNCTION_BODY> } function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } }
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() internal { _paused = false; } function paused() public view returns(bool) { return _paused; } modifier whenNotPaused() { require(!_paused); _; } modifier whenPaused() { require(_paused); _; } <FILL_FUNCTION> function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } }
_paused = true; emit Paused(msg.sender);
function pause() public onlyPauser whenNotPaused
function pause() public onlyPauser whenNotPaused
53630
CustomToken
CustomToken
contract CustomToken is BaseToken, BurnToken, ICOToken { function CustomToken() public {<FILL_FUNCTION_BODY> } }
contract CustomToken is BaseToken, BurnToken, ICOToken { <FILL_FUNCTION> }
totalSupply = 10000000000000000000000000000; balanceOf[0xA16bEBFAA12E77Fe0c2676040743f260072EBC88] = totalSupply; name = 'PKGX'; symbol = 'PKGX'; decimals = 18; icoRatio = 100000; icoEndtime = 1573639200; icoSender = 0xA16bEBFAA12E77Fe0c2676040743f260072EBC88; icoHolder = 0xA16bEBFAA12E77Fe0c2676040743f260072EBC88;
function CustomToken() public
function CustomToken() public
22017
B26toBYB
transferFrom
contract B26toBYB is Ownable, ERC20{ using SafeMath for uint256; string _name; string _symbol; uint256 _totalSupply; uint256 _decimal; mapping(address => uint256) _balances; mapping(address => mapping (address => uint256)) _allowances; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); constructor() public { _name = "B26 to BYB"; _symbol = "B26toBYB"; _decimal = 18; _totalSupply = 26000 * 10 ** _decimal; _balances[msg.sender] = _totalSupply; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint256) { return _decimal; } function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address _tokenOwner) external view override returns (uint256) { return _balances[_tokenOwner]; } function transfer(address _to, uint256 _tokens) external override returns (bool) { _transfer(msg.sender, _to, _tokens); return true; } function _transfer(address _sender, address _recipient, uint256 _amount) internal { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); _balances[_sender] = _balances[_sender].safeSub(_amount); _balances[_recipient] = _balances[_recipient].safeAdd(_amount); emit Transfer(_sender, _recipient, _amount); } function allowance(address _tokenOwner, address _spender) external view override returns (uint256) { return _allowances[_tokenOwner][_spender]; } function approve(address _spender, uint256 _tokens) external override returns (bool) { _approve(msg.sender, _spender, _tokens); return true; } function _approve(address _owner, address _spender, uint256 _value) internal { require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); _allowances[_owner][_spender] = _value; emit Approval(_owner, _spender, _value); } function transferFrom(address _from, address _to, uint256 _tokens) external override returns (bool) {<FILL_FUNCTION_BODY> } // don't accept eth receive () external payable { revert(); } }
contract B26toBYB is Ownable, ERC20{ using SafeMath for uint256; string _name; string _symbol; uint256 _totalSupply; uint256 _decimal; mapping(address => uint256) _balances; mapping(address => mapping (address => uint256)) _allowances; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); constructor() public { _name = "B26 to BYB"; _symbol = "B26toBYB"; _decimal = 18; _totalSupply = 26000 * 10 ** _decimal; _balances[msg.sender] = _totalSupply; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint256) { return _decimal; } function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address _tokenOwner) external view override returns (uint256) { return _balances[_tokenOwner]; } function transfer(address _to, uint256 _tokens) external override returns (bool) { _transfer(msg.sender, _to, _tokens); return true; } function _transfer(address _sender, address _recipient, uint256 _amount) internal { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); _balances[_sender] = _balances[_sender].safeSub(_amount); _balances[_recipient] = _balances[_recipient].safeAdd(_amount); emit Transfer(_sender, _recipient, _amount); } function allowance(address _tokenOwner, address _spender) external view override returns (uint256) { return _allowances[_tokenOwner][_spender]; } function approve(address _spender, uint256 _tokens) external override returns (bool) { _approve(msg.sender, _spender, _tokens); return true; } function _approve(address _owner, address _spender, uint256 _value) internal { require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); _allowances[_owner][_spender] = _value; emit Approval(_owner, _spender, _value); } <FILL_FUNCTION> // don't accept eth receive () external payable { revert(); } }
_transfer(_from, _to, _tokens); _approve(_from, msg.sender, _allowances[_from][msg.sender].safeSub(_tokens)); return true;
function transferFrom(address _from, address _to, uint256 _tokens) external override returns (bool)
function transferFrom(address _from, address _to, uint256 _tokens) external override returns (bool)
1551
MAdvcedWoken
_transfer
contract MAdvcedWoken is owned, TokenERC20 { mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal {<FILL_FUNCTION_BODY> } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(address(0), address(this), mintedAmount); emit Transfer(address(this), target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract }
contract MAdvcedWoken is owned, TokenERC20 { mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} <FILL_FUNCTION> /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(address(0), address(this), mintedAmount); emit Transfer(address(this), target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract }
require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value);
function _transfer(address _from, address _to, uint _value) internal
/* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal
3310
BurnVendor
buy
contract BurnVendor { TOKEN public akitaToken; uint256 constant public tokensPerEth = 2662260000; uint256 constant public burnMultiplier = 13; address payable constant public gitcoinAddress = payable(0xde21F729137C5Af1b01d73aF1dC21eFfa2B8a0d6); address constant public burnAddress = 0xDead000000000000000000000000000000000d06; constructor(address akitaAddress) { akitaToken = TOKEN(akitaAddress); } receive() external payable { buy(); } event Buy(address who, uint256 value, uint256 amount, uint256 burn); function buy() public payable {<FILL_FUNCTION_BODY> } }
contract BurnVendor { TOKEN public akitaToken; uint256 constant public tokensPerEth = 2662260000; uint256 constant public burnMultiplier = 13; address payable constant public gitcoinAddress = payable(0xde21F729137C5Af1b01d73aF1dC21eFfa2B8a0d6); address constant public burnAddress = 0xDead000000000000000000000000000000000d06; constructor(address akitaAddress) { akitaToken = TOKEN(akitaAddress); } receive() external payable { buy(); } event Buy(address who, uint256 value, uint256 amount, uint256 burn); <FILL_FUNCTION> }
uint256 amountOfTokensToBuy = msg.value * tokensPerEth; uint256 amountOfTokensToBurn = amountOfTokensToBuy * burnMultiplier; akitaToken.transferFrom(gitcoinAddress, burnAddress, amountOfTokensToBurn); akitaToken.transferFrom(gitcoinAddress, msg.sender, amountOfTokensToBuy); (bool sent, ) = gitcoinAddress.call{value: msg.value}(""); require(sent, "Failed to send ETH to Gitcoin Multisig"); emit Buy(msg.sender, msg.value, amountOfTokensToBuy, amountOfTokensToBurn);
function buy() public payable
function buy() public payable
46156
SpringField
_rewards
contract SpringField is ERC20 { using SafeMath for uint256; IERC20 public token; uint256 public initialBlock; uint256 public totalBlocks; uint8 public decimals = 18; address[] stakers; string public name; string public symbol; struct stakeData { address staker; uint256 amount; uint256 blockNumber; uint256 uBlockNumber; uint256 rewards; } mapping(address => mapping(uint256 => stakeData)) public stakes; mapping(address => uint256) public stakeCount; constructor(IERC20 _token) { token = _token; name = "SpringField"; symbol = "ySIMP"; initialBlock = block.number; totalBlocks= 2389091; } function enter(uint256 _amount) public { bool available = false; stakes[msg.sender][stakeCount[msg.sender]] = stakeData( msg.sender, _amount, block.number, 0, 0 ); stakeCount[msg.sender] += 1; for(uint i=0;i<stakers.length;i++){ if(stakers[i]==msg.sender){ available=true; break; }else{ continue; } } if(!available){ stakers.push(msg.sender); } uint256 usersSushi = token.balanceOf(msg.sender); uint256 allowedSushi = token.allowance(msg.sender, address(this)); require(usersSushi >= _amount, "Insufficient Balance to Stake"); require(allowedSushi >= _amount, "Allowed balance is Insufficient"); token.transferFrom(msg.sender, address(this), _amount); _mint(msg.sender, _amount); } function getrewards() public { uint256 rewards =_rewards(msg.sender); stakes[msg.sender][0].rewards = stakes[msg.sender][0].rewards.add(rewards); token.transfer(msg.sender, rewards); } function unstake() public { uint256 stakeAmount = 0; for(uint i = 0; i < stakeCount[msg.sender]; i++){ if(stakes[msg.sender][i].uBlockNumber==0) {stakeAmount = stakeAmount.add(stakes[msg.sender][i].amount);} } uint256 reward = _rewards(msg.sender); stakes[msg.sender][0]=stakeData(msg.sender,stakes[msg.sender][0].amount,stakes[msg.sender][0].blockNumber,block.number,stakes[msg.sender][0].rewards.add(reward)); _burn(msg.sender, stakeAmount); token.transfer(msg.sender, reward.add(stakeAmount)); } function _rewards(address adrs) private view returns (uint256) {<FILL_FUNCTION_BODY> } function myReward(address adrs)public view returns (uint256){ return _rewards(adrs); } }
contract SpringField is ERC20 { using SafeMath for uint256; IERC20 public token; uint256 public initialBlock; uint256 public totalBlocks; uint8 public decimals = 18; address[] stakers; string public name; string public symbol; struct stakeData { address staker; uint256 amount; uint256 blockNumber; uint256 uBlockNumber; uint256 rewards; } mapping(address => mapping(uint256 => stakeData)) public stakes; mapping(address => uint256) public stakeCount; constructor(IERC20 _token) { token = _token; name = "SpringField"; symbol = "ySIMP"; initialBlock = block.number; totalBlocks= 2389091; } function enter(uint256 _amount) public { bool available = false; stakes[msg.sender][stakeCount[msg.sender]] = stakeData( msg.sender, _amount, block.number, 0, 0 ); stakeCount[msg.sender] += 1; for(uint i=0;i<stakers.length;i++){ if(stakers[i]==msg.sender){ available=true; break; }else{ continue; } } if(!available){ stakers.push(msg.sender); } uint256 usersSushi = token.balanceOf(msg.sender); uint256 allowedSushi = token.allowance(msg.sender, address(this)); require(usersSushi >= _amount, "Insufficient Balance to Stake"); require(allowedSushi >= _amount, "Allowed balance is Insufficient"); token.transferFrom(msg.sender, address(this), _amount); _mint(msg.sender, _amount); } function getrewards() public { uint256 rewards =_rewards(msg.sender); stakes[msg.sender][0].rewards = stakes[msg.sender][0].rewards.add(rewards); token.transfer(msg.sender, rewards); } function unstake() public { uint256 stakeAmount = 0; for(uint i = 0; i < stakeCount[msg.sender]; i++){ if(stakes[msg.sender][i].uBlockNumber==0) {stakeAmount = stakeAmount.add(stakes[msg.sender][i].amount);} } uint256 reward = _rewards(msg.sender); stakes[msg.sender][0]=stakeData(msg.sender,stakes[msg.sender][0].amount,stakes[msg.sender][0].blockNumber,block.number,stakes[msg.sender][0].rewards.add(reward)); _burn(msg.sender, stakeAmount); token.transfer(msg.sender, reward.add(stakeAmount)); } <FILL_FUNCTION> function myReward(address adrs)public view returns (uint256){ return _rewards(adrs); } }
uint256 currentReward = (block.number-initialBlock).mul(11000*10**18).div(totalBlocks); uint256 rewardRate; uint256 mySum; uint256 totalSum; for(uint i = 0; i < stakeCount[adrs]; i++){ if(stakes[adrs][i].uBlockNumber==0) {mySum = mySum.add((stakes[adrs][i].amount).mul(block.number-stakes[adrs][i].blockNumber));} else{ mySum = mySum.add((stakes[adrs][i].amount).mul(stakes[adrs][i].uBlockNumber-stakes[adrs][i].blockNumber)); } } for(uint i=0;i<stakers.length; i++){ for(uint j = 0; j< stakeCount[stakers[i]]; j++){ if(stakes[stakers[i]][i].uBlockNumber==0) {totalSum = totalSum.add((stakes[stakers[i]][i].amount).mul(block.number-stakes[stakers[i]][i].blockNumber));} else{ totalSum = totalSum.add((stakes[stakers[i]][i].amount).mul(stakes[stakers[i]][i].uBlockNumber-stakes[stakers[i]][i].blockNumber)); } } } rewardRate = mySum.div(totalSum); return currentReward.mul(rewardRate)-stakes[adrs][0].rewards;
function _rewards(address adrs) private view returns (uint256)
function _rewards(address adrs) private view returns (uint256)
15780
goodsToken
null
contract goodsToken is ERC20Burnable { string public name; string public symbol = "GOODS"; uint8 public decimals; constructor(string memory _name, uint256 amount, address owner) public {<FILL_FUNCTION_BODY> } }
contract goodsToken is ERC20Burnable { string public name; string public symbol = "GOODS"; uint8 public decimals; <FILL_FUNCTION> }
name = _name; _mint(owner, amount);
constructor(string memory _name, uint256 amount, address owner) public
constructor(string memory _name, uint256 amount, address owner) public
85373
PoolSetters
decrementBalanceOfBonded
contract PoolSetters is PoolState, PoolGetters { using SafeMath for uint256; /** * Global */ function pause() internal { _state.paused = true; } /** * Account */ function incrementBalanceOfBonded(address account, uint256 amount) internal { _state.accounts[account].bonded = _state.accounts[account].bonded.add( amount ); _state.balance.bonded = _state.balance.bonded.add(amount); } function decrementBalanceOfBonded( address account, uint256 amount, string memory reason ) internal {<FILL_FUNCTION_BODY> } function incrementBalanceOfStaged(address account, uint256 amount) internal { _state.accounts[account].staged = _state.accounts[account].staged.add( amount ); _state.balance.staged = _state.balance.staged.add(amount); } function decrementBalanceOfStaged( address account, uint256 amount, string memory reason ) internal { _state.accounts[account].staged = _state.accounts[account].staged.sub( amount, reason ); _state.balance.staged = _state.balance.staged.sub(amount, reason); } function incrementBalanceOfClaimable(address account, uint256 amount) internal { _state.accounts[account].claimable = _state.accounts[account] .claimable .add(amount); _state.balance.claimable = _state.balance.claimable.add(amount); } function decrementBalanceOfClaimable( address account, uint256 amount, string memory reason ) internal { _state.accounts[account].claimable = _state.accounts[account] .claimable .sub(amount, reason); _state.balance.claimable = _state.balance.claimable.sub(amount, reason); } function incrementBalanceOfPhantom(address account, uint256 amount) internal { _state.accounts[account].phantom = _state.accounts[account].phantom.add( amount ); _state.balance.phantom = _state.balance.phantom.add(amount); } function decrementBalanceOfPhantom( address account, uint256 amount, string memory reason ) internal { _state.accounts[account].phantom = _state.accounts[account].phantom.sub( amount, reason ); _state.balance.phantom = _state.balance.phantom.sub(amount, reason); } function unfreeze(address account) internal { _state.accounts[account].fluidUntil = epoch().add( Constants.getPoolExitLockupEpochs() ); } }
contract PoolSetters is PoolState, PoolGetters { using SafeMath for uint256; /** * Global */ function pause() internal { _state.paused = true; } /** * Account */ function incrementBalanceOfBonded(address account, uint256 amount) internal { _state.accounts[account].bonded = _state.accounts[account].bonded.add( amount ); _state.balance.bonded = _state.balance.bonded.add(amount); } <FILL_FUNCTION> function incrementBalanceOfStaged(address account, uint256 amount) internal { _state.accounts[account].staged = _state.accounts[account].staged.add( amount ); _state.balance.staged = _state.balance.staged.add(amount); } function decrementBalanceOfStaged( address account, uint256 amount, string memory reason ) internal { _state.accounts[account].staged = _state.accounts[account].staged.sub( amount, reason ); _state.balance.staged = _state.balance.staged.sub(amount, reason); } function incrementBalanceOfClaimable(address account, uint256 amount) internal { _state.accounts[account].claimable = _state.accounts[account] .claimable .add(amount); _state.balance.claimable = _state.balance.claimable.add(amount); } function decrementBalanceOfClaimable( address account, uint256 amount, string memory reason ) internal { _state.accounts[account].claimable = _state.accounts[account] .claimable .sub(amount, reason); _state.balance.claimable = _state.balance.claimable.sub(amount, reason); } function incrementBalanceOfPhantom(address account, uint256 amount) internal { _state.accounts[account].phantom = _state.accounts[account].phantom.add( amount ); _state.balance.phantom = _state.balance.phantom.add(amount); } function decrementBalanceOfPhantom( address account, uint256 amount, string memory reason ) internal { _state.accounts[account].phantom = _state.accounts[account].phantom.sub( amount, reason ); _state.balance.phantom = _state.balance.phantom.sub(amount, reason); } function unfreeze(address account) internal { _state.accounts[account].fluidUntil = epoch().add( Constants.getPoolExitLockupEpochs() ); } }
_state.accounts[account].bonded = _state.accounts[account].bonded.sub( amount, reason ); _state.balance.bonded = _state.balance.bonded.sub(amount, reason);
function decrementBalanceOfBonded( address account, uint256 amount, string memory reason ) internal
function decrementBalanceOfBonded( address account, uint256 amount, string memory reason ) internal
50699
CSTKDropToken
returnFrom
contract CSTKDropToken is ERC20, Owned { using SafeMath for uint256; string public symbol; string public name; uint256 public decimals; uint256 _totalSupply; bool public started; address public token; struct Level { uint256 price; uint256 available; } Level[] levels; mapping(address => uint256) balances; mapping(address => mapping(string => uint256)) orders; event TransferETH(address indexed from, address indexed to, uint256 eth); event Sell(address indexed to, uint256 tokens, uint256 eth); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(string _symbol, string _name, uint256 _supply, uint256 _decimals, address _token) public { symbol = _symbol; name = _name; decimals = _decimals; token = _token; _totalSupply = _supply; balances[owner] = _totalSupply; started = false; emit Transfer(address(0), owner, _totalSupply); } function destruct() public onlyOwner { ERC20 tokenInstance = ERC20(token); uint256 balance = tokenInstance.balanceOf(this); if (balance > 0) { tokenInstance.transfer(owner, balance); } selfdestruct(owner); } // ------------------------------------------------------------------------ // Changes the address of the supported token // ------------------------------------------------------------------------ function setToken(address newTokenAddress) public onlyOwner returns (bool success) { token = newTokenAddress; return true; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint256) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Changes the total supply value // // a new supply must be no less then the current supply // or the owner must have enough amount to cover supply reduction // ------------------------------------------------------------------------ function changeTotalSupply(uint256 newSupply) public onlyOwner returns (bool success) { require(newSupply >= 0 && ( newSupply >= _totalSupply || _totalSupply - newSupply <= balances[owner] )); uint256 diff = 0; if (newSupply >= _totalSupply) { diff = newSupply.sub(_totalSupply); balances[owner] = balances[owner].add(diff); emit Transfer(address(0), owner, diff); } else { diff = _totalSupply.sub(newSupply); balances[owner] = balances[owner].sub(diff); emit Transfer(owner, address(0), diff); } _totalSupply = newSupply; return true; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Start accept orders // ------------------------------------------------------------------------ function start() public onlyOwner { started = true; } // ------------------------------------------------------------------------ // Start accept orders // ------------------------------------------------------------------------ function stop() public onlyOwner { started = false; } // ------------------------------------------------------------------------ // Adds new Level to the levels array // ------------------------------------------------------------------------ function addLevel(uint256 price, uint256 available) public onlyOwner { levels.push(Level(price, available)); } // ------------------------------------------------------------------------ // Removes a level with specified price from the levels array // ------------------------------------------------------------------------ function removeLevel(uint256 price) public onlyOwner { if (levels.length < 1) { return; } Level[] memory tmp = levels; delete levels; for (uint i = 0; i < tmp.length; i++) { if (tmp[i].price != price) { levels.push(tmp[i]); } } } // ------------------------------------------------------------------------ // Replaces a particular level index by a new Level values // ------------------------------------------------------------------------ function replaceLevel(uint index, uint256 price, uint256 available) public onlyOwner { levels[index] = Level(price, available); } // ------------------------------------------------------------------------ // Clears the levels array // ------------------------------------------------------------------------ function clearLevels() public onlyOwner { delete levels; } // ------------------------------------------------------------------------ // Finds a level with specified price and returns an amount of available tokens on the level // ------------------------------------------------------------------------ function getLevelAmount(uint256 price) public view returns (uint256 available) { if (levels.length < 1) { return 0; } for (uint i = 0; i < levels.length; i++) { if (levels[i].price == price) { return levels[i].available; } } } // ------------------------------------------------------------------------ // Returns a Level by it's array index // ------------------------------------------------------------------------ function getLevelByIndex(uint index) public view returns (uint256 price, uint256 available) { price = levels[index].price; available = levels[index].available; } // ------------------------------------------------------------------------ // Returns a count of levels // ------------------------------------------------------------------------ function getLevelsCount() public view returns (uint) { return levels.length; } // ------------------------------------------------------------------------ // Returns a Level by it's array index // ------------------------------------------------------------------------ function getCurrentLevel() public view returns (uint256 price, uint256 available) { if (levels.length < 1) { return; } for (uint i = 0; i < levels.length; i++) { if (levels[i].available > 0) { price = levels[i].price; available = levels[i].available; break; } } } // ------------------------------------------------------------------------ // Get the order's balance of tokens for account `customer` // ------------------------------------------------------------------------ function orderTokensOf(address customer) public view returns (uint256 balance) { return orders[customer]['tokens']; } // ------------------------------------------------------------------------ // Get the order's balance of ETH for account `customer` // ------------------------------------------------------------------------ function orderEthOf(address customer) public view returns (uint256 balance) { return orders[customer]['eth']; } // ------------------------------------------------------------------------ // Delete customer's order // ------------------------------------------------------------------------ function cancelOrder(address customer) public onlyOwner returns (bool success) { orders[customer]['eth'] = 0; orders[customer]['tokens'] = 0; return true; } // ------------------------------------------------------------------------ // Checks the order values by the customer's address and sends required // promo tokens based on the received amount of `this` tokens and ETH // ------------------------------------------------------------------------ function _checkOrder(address customer) private returns (uint256 tokens, uint256 eth) { require(started); eth = 0; tokens = 0; if (getLevelsCount() <= 0 || orders[customer]['tokens'] <= 0 || orders[customer]['eth'] <= 0) { return; } ERC20 tokenInstance = ERC20(token); uint256 balance = tokenInstance.balanceOf(this); uint256 orderEth = orders[customer]['eth']; uint256 orderTokens = orders[customer]['tokens'] > balance ? balance : orders[customer]['tokens']; for (uint i = 0; i < levels.length; i++) { if (levels[i].available <= 0) { continue; } uint256 _tokens = (10**decimals) * orderEth / levels[i].price; // check if there enough tokens on the level if (_tokens > levels[i].available) { _tokens = levels[i].available; } // check the order tokens limit if (_tokens > orderTokens) { _tokens = orderTokens; } uint256 _eth = _tokens * levels[i].price / (10**decimals); levels[i].available -= _tokens; // accumulate total price and tokens eth += _eth; tokens += _tokens; // reduce remaining limits orderEth -= _eth; orderTokens -= _tokens; if (orderEth <= 0 || orderTokens <= 0 || levels[i].available > 0) { // order is calculated break; } } // charge required amount of the tokens and ETHs orders[customer]['tokens'] = orders[customer]['tokens'].sub(tokens); orders[customer]['eth'] = orders[customer]['eth'].sub(eth); tokenInstance.transfer(customer, tokens); emit Sell(customer, tokens, eth); } // ------------------------------------------------------------------------ // public entry point for the `_checkOrder` function // ------------------------------------------------------------------------ function checkOrder(address customer) public onlyOwner returns (uint256 tokens, uint256 eth) { return _checkOrder(customer); } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // - only owner is allowed to send tokens to any address // - not owners can transfer the balance only to owner's address // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public returns (bool success) { require(msg.sender == owner || to == owner || to == address(this)); address receiver = msg.sender == owner ? to : owner; balances[msg.sender] = balances[msg.sender].sub(tokens); balances[receiver] = balances[receiver].add(tokens); emit Transfer(msg.sender, receiver, tokens); if (receiver == owner) { orders[msg.sender]['tokens'] = orders[msg.sender]['tokens'].add(tokens); _checkOrder(msg.sender); } return true; } // ------------------------------------------------------------------------ // `allowance` is not allowed // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) { tokenOwner; spender; return uint256(0); } // ------------------------------------------------------------------------ // `approve` is not allowed // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { spender; tokens; return true; } // ------------------------------------------------------------------------ // `transferFrom` is not allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public returns (bool success) { from; to; tokens; return true; } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { owner.transfer(msg.value); emit TransferETH(msg.sender, address(this), msg.value); orders[msg.sender]['eth'] = orders[msg.sender]['eth'].add(msg.value); _checkOrder(msg.sender); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Owner can transfer out promo token // ------------------------------------------------------------------------ function transferToken(uint256 tokens) public onlyOwner returns (bool success) { return transferAnyERC20Token(token, tokens); } // ------------------------------------------------------------------------ // Owner can return specified amount from `tokenOwner` // ------------------------------------------------------------------------ function returnFrom(address tokenOwner, uint256 tokens) public onlyOwner returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Owner can return all tokens from `tokenOwner` // ------------------------------------------------------------------------ function nullifyFrom(address tokenOwner) public onlyOwner returns (bool success) { return returnFrom(tokenOwner, balances[tokenOwner]); } }
contract CSTKDropToken is ERC20, Owned { using SafeMath for uint256; string public symbol; string public name; uint256 public decimals; uint256 _totalSupply; bool public started; address public token; struct Level { uint256 price; uint256 available; } Level[] levels; mapping(address => uint256) balances; mapping(address => mapping(string => uint256)) orders; event TransferETH(address indexed from, address indexed to, uint256 eth); event Sell(address indexed to, uint256 tokens, uint256 eth); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(string _symbol, string _name, uint256 _supply, uint256 _decimals, address _token) public { symbol = _symbol; name = _name; decimals = _decimals; token = _token; _totalSupply = _supply; balances[owner] = _totalSupply; started = false; emit Transfer(address(0), owner, _totalSupply); } function destruct() public onlyOwner { ERC20 tokenInstance = ERC20(token); uint256 balance = tokenInstance.balanceOf(this); if (balance > 0) { tokenInstance.transfer(owner, balance); } selfdestruct(owner); } // ------------------------------------------------------------------------ // Changes the address of the supported token // ------------------------------------------------------------------------ function setToken(address newTokenAddress) public onlyOwner returns (bool success) { token = newTokenAddress; return true; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint256) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Changes the total supply value // // a new supply must be no less then the current supply // or the owner must have enough amount to cover supply reduction // ------------------------------------------------------------------------ function changeTotalSupply(uint256 newSupply) public onlyOwner returns (bool success) { require(newSupply >= 0 && ( newSupply >= _totalSupply || _totalSupply - newSupply <= balances[owner] )); uint256 diff = 0; if (newSupply >= _totalSupply) { diff = newSupply.sub(_totalSupply); balances[owner] = balances[owner].add(diff); emit Transfer(address(0), owner, diff); } else { diff = _totalSupply.sub(newSupply); balances[owner] = balances[owner].sub(diff); emit Transfer(owner, address(0), diff); } _totalSupply = newSupply; return true; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Start accept orders // ------------------------------------------------------------------------ function start() public onlyOwner { started = true; } // ------------------------------------------------------------------------ // Start accept orders // ------------------------------------------------------------------------ function stop() public onlyOwner { started = false; } // ------------------------------------------------------------------------ // Adds new Level to the levels array // ------------------------------------------------------------------------ function addLevel(uint256 price, uint256 available) public onlyOwner { levels.push(Level(price, available)); } // ------------------------------------------------------------------------ // Removes a level with specified price from the levels array // ------------------------------------------------------------------------ function removeLevel(uint256 price) public onlyOwner { if (levels.length < 1) { return; } Level[] memory tmp = levels; delete levels; for (uint i = 0; i < tmp.length; i++) { if (tmp[i].price != price) { levels.push(tmp[i]); } } } // ------------------------------------------------------------------------ // Replaces a particular level index by a new Level values // ------------------------------------------------------------------------ function replaceLevel(uint index, uint256 price, uint256 available) public onlyOwner { levels[index] = Level(price, available); } // ------------------------------------------------------------------------ // Clears the levels array // ------------------------------------------------------------------------ function clearLevels() public onlyOwner { delete levels; } // ------------------------------------------------------------------------ // Finds a level with specified price and returns an amount of available tokens on the level // ------------------------------------------------------------------------ function getLevelAmount(uint256 price) public view returns (uint256 available) { if (levels.length < 1) { return 0; } for (uint i = 0; i < levels.length; i++) { if (levels[i].price == price) { return levels[i].available; } } } // ------------------------------------------------------------------------ // Returns a Level by it's array index // ------------------------------------------------------------------------ function getLevelByIndex(uint index) public view returns (uint256 price, uint256 available) { price = levels[index].price; available = levels[index].available; } // ------------------------------------------------------------------------ // Returns a count of levels // ------------------------------------------------------------------------ function getLevelsCount() public view returns (uint) { return levels.length; } // ------------------------------------------------------------------------ // Returns a Level by it's array index // ------------------------------------------------------------------------ function getCurrentLevel() public view returns (uint256 price, uint256 available) { if (levels.length < 1) { return; } for (uint i = 0; i < levels.length; i++) { if (levels[i].available > 0) { price = levels[i].price; available = levels[i].available; break; } } } // ------------------------------------------------------------------------ // Get the order's balance of tokens for account `customer` // ------------------------------------------------------------------------ function orderTokensOf(address customer) public view returns (uint256 balance) { return orders[customer]['tokens']; } // ------------------------------------------------------------------------ // Get the order's balance of ETH for account `customer` // ------------------------------------------------------------------------ function orderEthOf(address customer) public view returns (uint256 balance) { return orders[customer]['eth']; } // ------------------------------------------------------------------------ // Delete customer's order // ------------------------------------------------------------------------ function cancelOrder(address customer) public onlyOwner returns (bool success) { orders[customer]['eth'] = 0; orders[customer]['tokens'] = 0; return true; } // ------------------------------------------------------------------------ // Checks the order values by the customer's address and sends required // promo tokens based on the received amount of `this` tokens and ETH // ------------------------------------------------------------------------ function _checkOrder(address customer) private returns (uint256 tokens, uint256 eth) { require(started); eth = 0; tokens = 0; if (getLevelsCount() <= 0 || orders[customer]['tokens'] <= 0 || orders[customer]['eth'] <= 0) { return; } ERC20 tokenInstance = ERC20(token); uint256 balance = tokenInstance.balanceOf(this); uint256 orderEth = orders[customer]['eth']; uint256 orderTokens = orders[customer]['tokens'] > balance ? balance : orders[customer]['tokens']; for (uint i = 0; i < levels.length; i++) { if (levels[i].available <= 0) { continue; } uint256 _tokens = (10**decimals) * orderEth / levels[i].price; // check if there enough tokens on the level if (_tokens > levels[i].available) { _tokens = levels[i].available; } // check the order tokens limit if (_tokens > orderTokens) { _tokens = orderTokens; } uint256 _eth = _tokens * levels[i].price / (10**decimals); levels[i].available -= _tokens; // accumulate total price and tokens eth += _eth; tokens += _tokens; // reduce remaining limits orderEth -= _eth; orderTokens -= _tokens; if (orderEth <= 0 || orderTokens <= 0 || levels[i].available > 0) { // order is calculated break; } } // charge required amount of the tokens and ETHs orders[customer]['tokens'] = orders[customer]['tokens'].sub(tokens); orders[customer]['eth'] = orders[customer]['eth'].sub(eth); tokenInstance.transfer(customer, tokens); emit Sell(customer, tokens, eth); } // ------------------------------------------------------------------------ // public entry point for the `_checkOrder` function // ------------------------------------------------------------------------ function checkOrder(address customer) public onlyOwner returns (uint256 tokens, uint256 eth) { return _checkOrder(customer); } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // - only owner is allowed to send tokens to any address // - not owners can transfer the balance only to owner's address // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public returns (bool success) { require(msg.sender == owner || to == owner || to == address(this)); address receiver = msg.sender == owner ? to : owner; balances[msg.sender] = balances[msg.sender].sub(tokens); balances[receiver] = balances[receiver].add(tokens); emit Transfer(msg.sender, receiver, tokens); if (receiver == owner) { orders[msg.sender]['tokens'] = orders[msg.sender]['tokens'].add(tokens); _checkOrder(msg.sender); } return true; } // ------------------------------------------------------------------------ // `allowance` is not allowed // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) { tokenOwner; spender; return uint256(0); } // ------------------------------------------------------------------------ // `approve` is not allowed // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { spender; tokens; return true; } // ------------------------------------------------------------------------ // `transferFrom` is not allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public returns (bool success) { from; to; tokens; return true; } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { owner.transfer(msg.value); emit TransferETH(msg.sender, address(this), msg.value); orders[msg.sender]['eth'] = orders[msg.sender]['eth'].add(msg.value); _checkOrder(msg.sender); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) { return ERC20(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Owner can transfer out promo token // ------------------------------------------------------------------------ function transferToken(uint256 tokens) public onlyOwner returns (bool success) { return transferAnyERC20Token(token, tokens); } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Owner can return all tokens from `tokenOwner` // ------------------------------------------------------------------------ function nullifyFrom(address tokenOwner) public onlyOwner returns (bool success) { return returnFrom(tokenOwner, balances[tokenOwner]); } }
balances[tokenOwner] = balances[tokenOwner].sub(tokens); balances[owner] = balances[owner].add(tokens); emit Transfer(tokenOwner, owner, tokens); return true;
function returnFrom(address tokenOwner, uint256 tokens) public onlyOwner returns (bool success)
// ------------------------------------------------------------------------ // Owner can return specified amount from `tokenOwner` // ------------------------------------------------------------------------ function returnFrom(address tokenOwner, uint256 tokens) public onlyOwner returns (bool success)
31652
NumbalwarToken
transfer
contract NumbalwarToken is ERC20Interface { string public name = "Numbalwar Building Token"; uint8 public decimals = 18; string public symbol = "NBT"; function NumbalwarToken ( uint256 _initialAmount ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; } function transfer(address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) public constant 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) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
contract NumbalwarToken is ERC20Interface { string public name = "Numbalwar Building Token"; uint8 public decimals = 18; string public symbol = "NBT"; function NumbalwarToken ( uint256 _initialAmount ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; } <FILL_FUNCTION> function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) public constant 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) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; }
function transfer(address _to, uint256 _value) public returns (bool success)
function transfer(address _to, uint256 _value) public returns (bool success)
75111
ADXToken
innerMint
contract ADXToken { using SafeMath for uint; // Constants string public constant name = "AdEx Network"; string public constant symbol = "ADX"; uint8 public constant decimals = 18; // Mutable variables uint public totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Approval(address indexed owner, address indexed spender, uint amount); event Transfer(address indexed from, address indexed to, uint amount); address public supplyController; address public immutable PREV_TOKEN; constructor(address supplyControllerAddr, address prevTokenAddr) public { supplyController = supplyControllerAddr; PREV_TOKEN = prevTokenAddr; } function balanceOf(address owner) external view returns (uint balance) { return balances[owner]; } function transfer(address to, uint amount) external returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(amount); balances[to] = balances[to].add(amount); emit Transfer(msg.sender, to, amount); return true; } function transferFrom(address from, address to, uint amount) external returns (bool success) { balances[from] = balances[from].sub(amount); allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount); balances[to] = balances[to].add(amount); emit Transfer(from, to, amount); return true; } function approve(address spender, uint amount) external returns (bool success) { allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function allowance(address owner, address spender) external view returns (uint remaining) { return allowed[owner][spender]; } // Supply control function innerMint(address owner, uint amount) internal {<FILL_FUNCTION_BODY> } function mint(address owner, uint amount) external { require(msg.sender == supplyController, 'NOT_SUPPLYCONTROLLER'); innerMint(owner, amount); } function changeSupplyController(address newSupplyController) external { require(msg.sender == supplyController, 'NOT_SUPPLYCONTROLLER'); supplyController = newSupplyController; } // Swapping: multiplier is 10**(18-4) // NOTE: Burning by sending to 0x00 is not possible with many ERC20 implementations, but this one is made specifically for the old ADX uint constant PREV_TO_CURRENT_TOKEN_MULTIPLIER = 100000000000000; function swap(uint prevTokenAmount) external { innerMint(msg.sender, prevTokenAmount.mul(PREV_TO_CURRENT_TOKEN_MULTIPLIER)); SafeERC20.transferFrom(PREV_TOKEN, msg.sender, address(0), prevTokenAmount); } }
contract ADXToken { using SafeMath for uint; // Constants string public constant name = "AdEx Network"; string public constant symbol = "ADX"; uint8 public constant decimals = 18; // Mutable variables uint public totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Approval(address indexed owner, address indexed spender, uint amount); event Transfer(address indexed from, address indexed to, uint amount); address public supplyController; address public immutable PREV_TOKEN; constructor(address supplyControllerAddr, address prevTokenAddr) public { supplyController = supplyControllerAddr; PREV_TOKEN = prevTokenAddr; } function balanceOf(address owner) external view returns (uint balance) { return balances[owner]; } function transfer(address to, uint amount) external returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(amount); balances[to] = balances[to].add(amount); emit Transfer(msg.sender, to, amount); return true; } function transferFrom(address from, address to, uint amount) external returns (bool success) { balances[from] = balances[from].sub(amount); allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount); balances[to] = balances[to].add(amount); emit Transfer(from, to, amount); return true; } function approve(address spender, uint amount) external returns (bool success) { allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function allowance(address owner, address spender) external view returns (uint remaining) { return allowed[owner][spender]; } <FILL_FUNCTION> function mint(address owner, uint amount) external { require(msg.sender == supplyController, 'NOT_SUPPLYCONTROLLER'); innerMint(owner, amount); } function changeSupplyController(address newSupplyController) external { require(msg.sender == supplyController, 'NOT_SUPPLYCONTROLLER'); supplyController = newSupplyController; } // Swapping: multiplier is 10**(18-4) // NOTE: Burning by sending to 0x00 is not possible with many ERC20 implementations, but this one is made specifically for the old ADX uint constant PREV_TO_CURRENT_TOKEN_MULTIPLIER = 100000000000000; function swap(uint prevTokenAmount) external { innerMint(msg.sender, prevTokenAmount.mul(PREV_TO_CURRENT_TOKEN_MULTIPLIER)); SafeERC20.transferFrom(PREV_TOKEN, msg.sender, address(0), prevTokenAmount); } }
totalSupply = totalSupply.add(amount); balances[owner] = balances[owner].add(amount); // Because of https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 emit Transfer(address(0), owner, amount);
function innerMint(address owner, uint amount) internal
// Supply control function innerMint(address owner, uint amount) internal
67691
RoboToken
null
contract RoboToken is ERC20, ERC20Detailed, ERC20Burnable { constructor () public ERC20Detailed("Robo Coin", "ROBO", 18) {<FILL_FUNCTION_BODY> } }
contract RoboToken is ERC20, ERC20Detailed, ERC20Burnable { <FILL_FUNCTION> }
_mint(msg.sender, 3000000000 * (10 ** uint256(decimals())));
constructor () public ERC20Detailed("Robo Coin", "ROBO", 18)
constructor () public ERC20Detailed("Robo Coin", "ROBO", 18)
19727
Owned
acceptOwnership
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public {<FILL_FUNCTION_BODY> } }
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } <FILL_FUNCTION> }
require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0);
function acceptOwnership() public
function acceptOwnership() public