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
59323
Ownable
null
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(address initialOwner) internal {<FILL_FUNCTION_BODY> } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_isOwner(msg.sender), "Ownable: caller is not the owner"); _; } function _isOwner(address account) internal view returns (bool) { return account == _owner; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); <FILL_FUNCTION> function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_isOwner(msg.sender), "Ownable: caller is not the owner"); _; } function _isOwner(address account) internal view returns (bool) { return account == _owner; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
require(initialOwner != address(0), "Ownable: initial owner is the zero address"); _owner = initialOwner; emit OwnershipTransferred(address(0), _owner);
constructor(address initialOwner) internal
constructor(address initialOwner) internal
73017
Owned
acceptOwnership
contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external {<FILL_FUNCTION_BODY> } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); }
contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } <FILL_FUNCTION> modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); }
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0);
function acceptOwnership() external
function acceptOwnership() external
12940
BasicToken
transfer
contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; <FILL_FUNCTION> /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
require(_to != address(0)); require(_value <= balanceOf(msg.sender)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true;
function transfer(address _to, uint256 _value) public returns (bool)
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool)
82337
PoolHelper
proxyMint
contract PoolHelper is Ownable { string public name; address public mintableToken; mapping(bytes32 => bool) successfulPayments; event Payment(bytes32 _paymentId); constructor(address mToken, string memory mName) public { mintableToken = mToken; name = mName; } function setMintableToken(address mToken) public onlyOwner returns (bool) { mintableToken = mToken; return true; } function paymentSuccessful(bytes32 paymentId) public view returns (bool){ return (successfulPayments[paymentId] == true); } function proxyMint(uint256 nonce, bytes32 challenge_digest ) public returns (bool) {<FILL_FUNCTION_BODY> } //withdraw any eth inside function withdraw() public onlyOwner { msg.sender.transfer(address(this).balance); } //send tokens out function send(address _tokenAddr, bytes32 paymentId, address dest, uint value) public onlyPayoutWallet returns (bool) { require(successfulPayments[paymentId] != true, "Payment ID already exists and was successful"); successfulPayments[paymentId] = true; emit Payment(paymentId); return ERC20Interface(_tokenAddr).transfer(dest, value); } //batch send tokens function multisend(address _tokenAddr, bytes32 paymentId, address[] memory dests, uint256[] memory values) public onlyPayoutWallet returns (uint256) { require(dests.length > 0, "Must have more than 1 destination address"); require(values.length >= dests.length, "Address to Value array size mismatch"); require(successfulPayments[paymentId] != true, "Payment ID already exists and was successful"); uint256 i = 0; while (i < dests.length) { require(ERC20Interface(_tokenAddr).transfer(dests[i], values[i])); i += 1; } successfulPayments[paymentId] = true; emit Payment(paymentId); return (i); } }
contract PoolHelper is Ownable { string public name; address public mintableToken; mapping(bytes32 => bool) successfulPayments; event Payment(bytes32 _paymentId); constructor(address mToken, string memory mName) public { mintableToken = mToken; name = mName; } function setMintableToken(address mToken) public onlyOwner returns (bool) { mintableToken = mToken; return true; } function paymentSuccessful(bytes32 paymentId) public view returns (bool){ return (successfulPayments[paymentId] == true); } <FILL_FUNCTION> //withdraw any eth inside function withdraw() public onlyOwner { msg.sender.transfer(address(this).balance); } //send tokens out function send(address _tokenAddr, bytes32 paymentId, address dest, uint value) public onlyPayoutWallet returns (bool) { require(successfulPayments[paymentId] != true, "Payment ID already exists and was successful"); successfulPayments[paymentId] = true; emit Payment(paymentId); return ERC20Interface(_tokenAddr).transfer(dest, value); } //batch send tokens function multisend(address _tokenAddr, bytes32 paymentId, address[] memory dests, uint256[] memory values) public onlyPayoutWallet returns (uint256) { require(dests.length > 0, "Must have more than 1 destination address"); require(values.length >= dests.length, "Address to Value array size mismatch"); require(successfulPayments[paymentId] != true, "Payment ID already exists and was successful"); uint256 i = 0; while (i < dests.length) { require(ERC20Interface(_tokenAddr).transfer(dests[i], values[i])); i += 1; } successfulPayments[paymentId] = true; emit Payment(paymentId); return (i); } }
require(ERC918Interface(mintableToken).mint(nonce, challenge_digest), "Could not mint token"); return true;
function proxyMint(uint256 nonce, bytes32 challenge_digest ) public returns (bool)
function proxyMint(uint256 nonce, bytes32 challenge_digest ) public returns (bool)
35178
RaceCoin
attackPlayer
contract RaceCoin is ERC20, AccessAdmin, IRaceCoin { using SafeMath for uint256; string public constant name = "Race Coin"; string public constant symbol = "Coin"; uint8 public constant decimals = 0; uint256 private roughSupply; uint256 public totalRaceCoinProduction; //Daily dividend ratio uint256 public bonusDivPercent = 20; //Recommendation ratio uint256 constant refererPercent = 5; address[] public playerList; //Verifying whether duplication is repeated // mapping(address => uint256) public isProduction; uint256 public totalEtherPool; // Eth dividends to be split between players' race coin production uint256[] private totalRaceCoinProductionSnapshots; // The total race coin production for each prior day past uint256[] private allocatedRaceCoinSnapshots; // The amount of EHT that can be allocated daily uint256[] private totalRaceCoinSnapshots; // The total race coin for each prior day past uint256 public nextSnapshotTime; // Balances for each player mapping(address => uint256) private ethBalance; mapping(address => uint256) private raceCoinBalance; mapping(address => uint256) private refererDivsBalance; mapping(address => uint256) private productionBaseValue; //Player production base value mapping(address => uint256) private productionMultiplier; //Player production multiplier mapping(address => uint256) private attackBaseValue; //Player attack base value mapping(address => uint256) private attackMultiplier; //Player attack multiplier mapping(address => uint256) private attackPower; //Player attack Power mapping(address => uint256) private defendBaseValue; //Player defend base value mapping(address => uint256) private defendMultiplier; //Player defend multiplier mapping(address => uint256) private defendPower; //Player defend Power mapping(address => uint256) private plunderBaseValue; //Player plunder base value mapping(address => uint256) private plunderMultiplier; //Player plunder multiplier mapping(address => uint256) private plunderPower; //Player plunder Power mapping(address => mapping(uint256 => uint256)) private raceCoinProductionSnapshots; // Store player's race coin production for given day (snapshot) mapping(address => mapping(uint256 => bool)) private raceCoinProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day. mapping(address => mapping(uint256 => uint256)) private raceCoinSnapshots;// Store player's race coin for given day (snapshot) mapping(address => uint256) private lastRaceCoinSaveTime; // Seconds (last time player claimed their produced race coin) mapping(address => uint256) public lastRaceCoinProductionUpdate; // Days (last snapshot player updated their production) mapping(address => uint256) private lastRaceCoinFundClaim; // Days (snapshot number) mapping(address => uint256) private battleCooldown; // If user attacks they cannot attack again for short time // Computational correlation // Mapping of approved ERC20 transfers (by player) mapping(address => mapping(address => uint256)) private allowed; event ReferalGain(address referal, address player, uint256 amount); event PlayerAttacked(address attacker, address target, bool success, uint256 raceCoinPlunder); /// @dev Trust contract mapping (address => bool) actionContracts; function setActionContract(address _actionAddr, bool _useful) external onlyAdmin { actionContracts[_actionAddr] = _useful; } function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) { return actionContracts[_actionAddr]; } function RaceCoin() public { addrAdmin = msg.sender; } function() external payable { } function beginWork(uint256 firstDivsTime) external onlyAdmin { nextSnapshotTime = firstDivsTime; } // We will adjust to achieve a balance. function adjustDailyDividends(uint256 newBonusPercent) external onlyAdmin whenNotPaused { require(newBonusPercent > 0 && newBonusPercent <= 80); bonusDivPercent = newBonusPercent; } // Stored race coin (rough supply as it ignores earned/unclaimed RaceCoin) function totalSupply() public view returns(uint256) { return roughSupply; } function balanceOf(address player) public view returns(uint256) { return raceCoinBalance[player] + balanceOfUnclaimedRaceCoin(player); } function balanceOfUnclaimedRaceCoin(address player) internal view returns (uint256) { uint256 lastSave = lastRaceCoinSaveTime[player]; if (lastSave > 0 && lastSave < block.timestamp) { return (getRaceCoinProduction(player) * (block.timestamp - lastSave)) / 100; } return 0; } function getRaceCoinProduction(address player) public view returns (uint256){ return raceCoinProductionSnapshots[player][lastRaceCoinProductionUpdate[player]]; } function etherBalanceOf(address player) public view returns(uint256) { return ethBalance[player]; } function transfer(address recipient, uint256 amount) public returns (bool) { updatePlayersRaceCoin(msg.sender); require(amount <= raceCoinBalance[msg.sender]); raceCoinBalance[msg.sender] -= amount; raceCoinBalance[recipient] += amount; emit Transfer(msg.sender, recipient, amount); return true; } function transferFrom(address player, address recipient, uint256 amount) public returns (bool) { updatePlayersRaceCoin(player); require(amount <= allowed[player][msg.sender] && amount <= raceCoinBalance[player]); raceCoinBalance[player] -= amount; raceCoinBalance[recipient] += amount; allowed[player][msg.sender] -= amount; emit Transfer(player, recipient, amount); return true; } function approve(address approvee, uint256 amount) public returns (bool){ allowed[msg.sender][approvee] = amount; emit Approval(msg.sender, approvee, amount); return true; } function allowance(address player, address approvee) public view returns(uint256){ return allowed[player][approvee]; } function addPlayerToList(address player) external{ require(actionContracts[msg.sender]); require(player != address(0)); bool b = false; //Judge whether or not to repeat for (uint256 i = 0; i < playerList.length; i++) { if(playerList[i] == player){ b = true; break; } } if(!b){ playerList.push(player); } } function getPlayerList() external view returns ( address[] ){ return playerList; } function updatePlayersRaceCoin(address player) internal { uint256 raceCoinGain = balanceOfUnclaimedRaceCoin(player); lastRaceCoinSaveTime[player] = block.timestamp; roughSupply += raceCoinGain; raceCoinBalance[player] += raceCoinGain; } //Increase attribute function increasePlayersAttribute(address player, uint16[13] param) external{ require(actionContracts[msg.sender]); require(player != address(0)); //Production updatePlayersRaceCoin(player); uint256 increase; uint256 newProduction; uint256 previousProduction; previousProduction = getRaceCoinProduction(player); productionBaseValue[player] = productionBaseValue[player].add(param[3]); productionMultiplier[player] = productionMultiplier[player].add(param[7]); newProduction = productionBaseValue[player].mul(100 + productionMultiplier[player]).div(100); increase = newProduction.sub(previousProduction); raceCoinProductionSnapshots[player][allocatedRaceCoinSnapshots.length] = newProduction; lastRaceCoinProductionUpdate[player] = allocatedRaceCoinSnapshots.length; totalRaceCoinProduction += increase; //Attack attackBaseValue[player] = attackBaseValue[player].add(param[4]); attackMultiplier[player] = attackMultiplier[player].add(param[8]); attackPower[player] = attackBaseValue[player].mul(100 + attackMultiplier[player]).div(100); //Defend defendBaseValue[player] = defendBaseValue[player].add(param[5]); defendMultiplier[player] = defendMultiplier[player].add(param[9]); defendPower[player] = defendBaseValue[player].mul(100 + defendMultiplier[player]).div(100); //Plunder plunderBaseValue[player] = plunderBaseValue[player].add(param[6]); plunderMultiplier[player] = plunderMultiplier[player].add(param[10]); plunderPower[player] = plunderBaseValue[player].mul(100 + plunderMultiplier[player]).div(100); } //Reduce attribute function reducePlayersAttribute(address player, uint16[13] param) external{ require(actionContracts[msg.sender]); require(player != address(0)); //Production updatePlayersRaceCoin(player); uint256 decrease; uint256 newProduction; uint256 previousProduction; previousProduction = getRaceCoinProduction(player); productionBaseValue[player] = productionBaseValue[player].sub(param[3]); productionMultiplier[player] = productionMultiplier[player].sub(param[7]); newProduction = productionBaseValue[player].mul(100 + productionMultiplier[player]).div(100); decrease = previousProduction.sub(newProduction); if (newProduction == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs) raceCoinProductionZeroedSnapshots[player][allocatedRaceCoinSnapshots.length] = true; delete raceCoinProductionSnapshots[player][allocatedRaceCoinSnapshots.length]; // 0 } else { raceCoinProductionSnapshots[player][allocatedRaceCoinSnapshots.length] = newProduction; } lastRaceCoinProductionUpdate[player] = allocatedRaceCoinSnapshots.length; totalRaceCoinProduction -= decrease; //Attack attackBaseValue[player] = attackBaseValue[player].sub(param[4]); attackMultiplier[player] = attackMultiplier[player].sub(param[8]); attackPower[player] = attackBaseValue[player].mul(100 + attackMultiplier[player]).div(100); //Defend defendBaseValue[player] = defendBaseValue[player].sub(param[5]); defendMultiplier[player] = defendMultiplier[player].sub(param[9]); defendPower[player] = defendBaseValue[player].mul(100 + defendMultiplier[player]).div(100); //Plunder plunderBaseValue[player] = plunderBaseValue[player].sub(param[6]); plunderMultiplier[player] = plunderMultiplier[player].sub(param[10]); plunderPower[player] = plunderBaseValue[player].mul(100 + plunderMultiplier[player]).div(100); } function attackPlayer(address player,address target) external {<FILL_FUNCTION_BODY> } function getPlayersBattleStats(address player) external view returns (uint256, uint256, uint256, uint256){ return (attackPower[player], defendPower[player], plunderPower[player], battleCooldown[player]); } function getPlayersAttributesInt(address player) external view returns (uint256, uint256, uint256, uint256){ return (getRaceCoinProduction(player), attackPower[player], defendPower[player], plunderPower[player]); } function getPlayersAttributesMult(address player) external view returns (uint256, uint256, uint256, uint256){ return (productionMultiplier[player], attackMultiplier[player], defendMultiplier[player], plunderMultiplier[player]); } function withdrawEther(uint256 amount) external { require(amount <= ethBalance[msg.sender]); ethBalance[msg.sender] -= amount; msg.sender.transfer(amount); } function getBalance() external view returns(uint256) { return totalEtherPool; } function addTotalEtherPool(uint256 amount) external{ require(amount > 0); totalEtherPool += amount; } // To display function getGameInfo(address player) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256){ return (block.timestamp, totalEtherPool, totalRaceCoinProduction,nextSnapshotTime, balanceOf(player), ethBalance[player], getRaceCoinProduction(player)); } function claimRaceCoinDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external { require(startSnapshot <= endSnapShot); require(startSnapshot >= lastRaceCoinFundClaim[msg.sender]); require(endSnapShot < allocatedRaceCoinSnapshots.length); uint256 dividendsShare; for (uint256 i = startSnapshot; i <= endSnapShot; i++) { uint256 raceCoinDuringSnapshot = raceCoinSnapshots[msg.sender][i]; dividendsShare += (allocatedRaceCoinSnapshots[i] * raceCoinDuringSnapshot) / totalRaceCoinSnapshots[i]; } lastRaceCoinFundClaim[msg.sender] = endSnapShot + 1; uint256 referalDivs; if (referer != address(0) && referer != msg.sender) { referalDivs = dividendsShare.mul(refererPercent).div(100); // 5% ethBalance[referer] += referalDivs; refererDivsBalance[referer] += referalDivs; emit ReferalGain(referer, msg.sender, referalDivs); } ethBalance[msg.sender] += dividendsShare - referalDivs; } // To display function viewUnclaimedRaceCoinDividends(address player) external view returns (uint256, uint256, uint256) { uint256 startSnapshot = lastRaceCoinFundClaim[player]; uint256 latestSnapshot = allocatedRaceCoinSnapshots.length - 1; // No snapshots to begin with uint256 dividendsShare; for (uint256 i = startSnapshot; i <= latestSnapshot; i++) { uint256 raceCoinDuringSnapshot = raceCoinSnapshots[player][i]; dividendsShare += (allocatedRaceCoinSnapshots[i] * raceCoinDuringSnapshot) / totalRaceCoinSnapshots[i]; } return (dividendsShare, startSnapshot, latestSnapshot); } function getRefererDivsBalance(address player) external view returns (uint256){ return refererDivsBalance[player]; } // Allocate divs for the day (00:00 cron job) function snapshotDailyRaceCoinFunding() external onlyAdmin whenNotPaused { uint256 todaysRaceCoinFund = (totalEtherPool * bonusDivPercent) / 100; // 20% of pool daily totalEtherPool -= todaysRaceCoinFund; totalRaceCoinProductionSnapshots.push(totalRaceCoinProduction); allocatedRaceCoinSnapshots.push(todaysRaceCoinFund); nextSnapshotTime = block.timestamp + 24 hours; for (uint256 i = 0; i < playerList.length; i++) { updatePlayersRaceCoin(playerList[i]); raceCoinSnapshots[playerList[i]][lastRaceCoinProductionUpdate[playerList[i]]] = raceCoinBalance[playerList[i]]; } totalRaceCoinSnapshots.push(roughSupply); } }
contract RaceCoin is ERC20, AccessAdmin, IRaceCoin { using SafeMath for uint256; string public constant name = "Race Coin"; string public constant symbol = "Coin"; uint8 public constant decimals = 0; uint256 private roughSupply; uint256 public totalRaceCoinProduction; //Daily dividend ratio uint256 public bonusDivPercent = 20; //Recommendation ratio uint256 constant refererPercent = 5; address[] public playerList; //Verifying whether duplication is repeated // mapping(address => uint256) public isProduction; uint256 public totalEtherPool; // Eth dividends to be split between players' race coin production uint256[] private totalRaceCoinProductionSnapshots; // The total race coin production for each prior day past uint256[] private allocatedRaceCoinSnapshots; // The amount of EHT that can be allocated daily uint256[] private totalRaceCoinSnapshots; // The total race coin for each prior day past uint256 public nextSnapshotTime; // Balances for each player mapping(address => uint256) private ethBalance; mapping(address => uint256) private raceCoinBalance; mapping(address => uint256) private refererDivsBalance; mapping(address => uint256) private productionBaseValue; //Player production base value mapping(address => uint256) private productionMultiplier; //Player production multiplier mapping(address => uint256) private attackBaseValue; //Player attack base value mapping(address => uint256) private attackMultiplier; //Player attack multiplier mapping(address => uint256) private attackPower; //Player attack Power mapping(address => uint256) private defendBaseValue; //Player defend base value mapping(address => uint256) private defendMultiplier; //Player defend multiplier mapping(address => uint256) private defendPower; //Player defend Power mapping(address => uint256) private plunderBaseValue; //Player plunder base value mapping(address => uint256) private plunderMultiplier; //Player plunder multiplier mapping(address => uint256) private plunderPower; //Player plunder Power mapping(address => mapping(uint256 => uint256)) private raceCoinProductionSnapshots; // Store player's race coin production for given day (snapshot) mapping(address => mapping(uint256 => bool)) private raceCoinProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day. mapping(address => mapping(uint256 => uint256)) private raceCoinSnapshots;// Store player's race coin for given day (snapshot) mapping(address => uint256) private lastRaceCoinSaveTime; // Seconds (last time player claimed their produced race coin) mapping(address => uint256) public lastRaceCoinProductionUpdate; // Days (last snapshot player updated their production) mapping(address => uint256) private lastRaceCoinFundClaim; // Days (snapshot number) mapping(address => uint256) private battleCooldown; // If user attacks they cannot attack again for short time // Computational correlation // Mapping of approved ERC20 transfers (by player) mapping(address => mapping(address => uint256)) private allowed; event ReferalGain(address referal, address player, uint256 amount); event PlayerAttacked(address attacker, address target, bool success, uint256 raceCoinPlunder); /// @dev Trust contract mapping (address => bool) actionContracts; function setActionContract(address _actionAddr, bool _useful) external onlyAdmin { actionContracts[_actionAddr] = _useful; } function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) { return actionContracts[_actionAddr]; } function RaceCoin() public { addrAdmin = msg.sender; } function() external payable { } function beginWork(uint256 firstDivsTime) external onlyAdmin { nextSnapshotTime = firstDivsTime; } // We will adjust to achieve a balance. function adjustDailyDividends(uint256 newBonusPercent) external onlyAdmin whenNotPaused { require(newBonusPercent > 0 && newBonusPercent <= 80); bonusDivPercent = newBonusPercent; } // Stored race coin (rough supply as it ignores earned/unclaimed RaceCoin) function totalSupply() public view returns(uint256) { return roughSupply; } function balanceOf(address player) public view returns(uint256) { return raceCoinBalance[player] + balanceOfUnclaimedRaceCoin(player); } function balanceOfUnclaimedRaceCoin(address player) internal view returns (uint256) { uint256 lastSave = lastRaceCoinSaveTime[player]; if (lastSave > 0 && lastSave < block.timestamp) { return (getRaceCoinProduction(player) * (block.timestamp - lastSave)) / 100; } return 0; } function getRaceCoinProduction(address player) public view returns (uint256){ return raceCoinProductionSnapshots[player][lastRaceCoinProductionUpdate[player]]; } function etherBalanceOf(address player) public view returns(uint256) { return ethBalance[player]; } function transfer(address recipient, uint256 amount) public returns (bool) { updatePlayersRaceCoin(msg.sender); require(amount <= raceCoinBalance[msg.sender]); raceCoinBalance[msg.sender] -= amount; raceCoinBalance[recipient] += amount; emit Transfer(msg.sender, recipient, amount); return true; } function transferFrom(address player, address recipient, uint256 amount) public returns (bool) { updatePlayersRaceCoin(player); require(amount <= allowed[player][msg.sender] && amount <= raceCoinBalance[player]); raceCoinBalance[player] -= amount; raceCoinBalance[recipient] += amount; allowed[player][msg.sender] -= amount; emit Transfer(player, recipient, amount); return true; } function approve(address approvee, uint256 amount) public returns (bool){ allowed[msg.sender][approvee] = amount; emit Approval(msg.sender, approvee, amount); return true; } function allowance(address player, address approvee) public view returns(uint256){ return allowed[player][approvee]; } function addPlayerToList(address player) external{ require(actionContracts[msg.sender]); require(player != address(0)); bool b = false; //Judge whether or not to repeat for (uint256 i = 0; i < playerList.length; i++) { if(playerList[i] == player){ b = true; break; } } if(!b){ playerList.push(player); } } function getPlayerList() external view returns ( address[] ){ return playerList; } function updatePlayersRaceCoin(address player) internal { uint256 raceCoinGain = balanceOfUnclaimedRaceCoin(player); lastRaceCoinSaveTime[player] = block.timestamp; roughSupply += raceCoinGain; raceCoinBalance[player] += raceCoinGain; } //Increase attribute function increasePlayersAttribute(address player, uint16[13] param) external{ require(actionContracts[msg.sender]); require(player != address(0)); //Production updatePlayersRaceCoin(player); uint256 increase; uint256 newProduction; uint256 previousProduction; previousProduction = getRaceCoinProduction(player); productionBaseValue[player] = productionBaseValue[player].add(param[3]); productionMultiplier[player] = productionMultiplier[player].add(param[7]); newProduction = productionBaseValue[player].mul(100 + productionMultiplier[player]).div(100); increase = newProduction.sub(previousProduction); raceCoinProductionSnapshots[player][allocatedRaceCoinSnapshots.length] = newProduction; lastRaceCoinProductionUpdate[player] = allocatedRaceCoinSnapshots.length; totalRaceCoinProduction += increase; //Attack attackBaseValue[player] = attackBaseValue[player].add(param[4]); attackMultiplier[player] = attackMultiplier[player].add(param[8]); attackPower[player] = attackBaseValue[player].mul(100 + attackMultiplier[player]).div(100); //Defend defendBaseValue[player] = defendBaseValue[player].add(param[5]); defendMultiplier[player] = defendMultiplier[player].add(param[9]); defendPower[player] = defendBaseValue[player].mul(100 + defendMultiplier[player]).div(100); //Plunder plunderBaseValue[player] = plunderBaseValue[player].add(param[6]); plunderMultiplier[player] = plunderMultiplier[player].add(param[10]); plunderPower[player] = plunderBaseValue[player].mul(100 + plunderMultiplier[player]).div(100); } //Reduce attribute function reducePlayersAttribute(address player, uint16[13] param) external{ require(actionContracts[msg.sender]); require(player != address(0)); //Production updatePlayersRaceCoin(player); uint256 decrease; uint256 newProduction; uint256 previousProduction; previousProduction = getRaceCoinProduction(player); productionBaseValue[player] = productionBaseValue[player].sub(param[3]); productionMultiplier[player] = productionMultiplier[player].sub(param[7]); newProduction = productionBaseValue[player].mul(100 + productionMultiplier[player]).div(100); decrease = previousProduction.sub(newProduction); if (newProduction == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs) raceCoinProductionZeroedSnapshots[player][allocatedRaceCoinSnapshots.length] = true; delete raceCoinProductionSnapshots[player][allocatedRaceCoinSnapshots.length]; // 0 } else { raceCoinProductionSnapshots[player][allocatedRaceCoinSnapshots.length] = newProduction; } lastRaceCoinProductionUpdate[player] = allocatedRaceCoinSnapshots.length; totalRaceCoinProduction -= decrease; //Attack attackBaseValue[player] = attackBaseValue[player].sub(param[4]); attackMultiplier[player] = attackMultiplier[player].sub(param[8]); attackPower[player] = attackBaseValue[player].mul(100 + attackMultiplier[player]).div(100); //Defend defendBaseValue[player] = defendBaseValue[player].sub(param[5]); defendMultiplier[player] = defendMultiplier[player].sub(param[9]); defendPower[player] = defendBaseValue[player].mul(100 + defendMultiplier[player]).div(100); //Plunder plunderBaseValue[player] = plunderBaseValue[player].sub(param[6]); plunderMultiplier[player] = plunderMultiplier[player].sub(param[10]); plunderPower[player] = plunderBaseValue[player].mul(100 + plunderMultiplier[player]).div(100); } <FILL_FUNCTION> function getPlayersBattleStats(address player) external view returns (uint256, uint256, uint256, uint256){ return (attackPower[player], defendPower[player], plunderPower[player], battleCooldown[player]); } function getPlayersAttributesInt(address player) external view returns (uint256, uint256, uint256, uint256){ return (getRaceCoinProduction(player), attackPower[player], defendPower[player], plunderPower[player]); } function getPlayersAttributesMult(address player) external view returns (uint256, uint256, uint256, uint256){ return (productionMultiplier[player], attackMultiplier[player], defendMultiplier[player], plunderMultiplier[player]); } function withdrawEther(uint256 amount) external { require(amount <= ethBalance[msg.sender]); ethBalance[msg.sender] -= amount; msg.sender.transfer(amount); } function getBalance() external view returns(uint256) { return totalEtherPool; } function addTotalEtherPool(uint256 amount) external{ require(amount > 0); totalEtherPool += amount; } // To display function getGameInfo(address player) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256){ return (block.timestamp, totalEtherPool, totalRaceCoinProduction,nextSnapshotTime, balanceOf(player), ethBalance[player], getRaceCoinProduction(player)); } function claimRaceCoinDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external { require(startSnapshot <= endSnapShot); require(startSnapshot >= lastRaceCoinFundClaim[msg.sender]); require(endSnapShot < allocatedRaceCoinSnapshots.length); uint256 dividendsShare; for (uint256 i = startSnapshot; i <= endSnapShot; i++) { uint256 raceCoinDuringSnapshot = raceCoinSnapshots[msg.sender][i]; dividendsShare += (allocatedRaceCoinSnapshots[i] * raceCoinDuringSnapshot) / totalRaceCoinSnapshots[i]; } lastRaceCoinFundClaim[msg.sender] = endSnapShot + 1; uint256 referalDivs; if (referer != address(0) && referer != msg.sender) { referalDivs = dividendsShare.mul(refererPercent).div(100); // 5% ethBalance[referer] += referalDivs; refererDivsBalance[referer] += referalDivs; emit ReferalGain(referer, msg.sender, referalDivs); } ethBalance[msg.sender] += dividendsShare - referalDivs; } // To display function viewUnclaimedRaceCoinDividends(address player) external view returns (uint256, uint256, uint256) { uint256 startSnapshot = lastRaceCoinFundClaim[player]; uint256 latestSnapshot = allocatedRaceCoinSnapshots.length - 1; // No snapshots to begin with uint256 dividendsShare; for (uint256 i = startSnapshot; i <= latestSnapshot; i++) { uint256 raceCoinDuringSnapshot = raceCoinSnapshots[player][i]; dividendsShare += (allocatedRaceCoinSnapshots[i] * raceCoinDuringSnapshot) / totalRaceCoinSnapshots[i]; } return (dividendsShare, startSnapshot, latestSnapshot); } function getRefererDivsBalance(address player) external view returns (uint256){ return refererDivsBalance[player]; } // Allocate divs for the day (00:00 cron job) function snapshotDailyRaceCoinFunding() external onlyAdmin whenNotPaused { uint256 todaysRaceCoinFund = (totalEtherPool * bonusDivPercent) / 100; // 20% of pool daily totalEtherPool -= todaysRaceCoinFund; totalRaceCoinProductionSnapshots.push(totalRaceCoinProduction); allocatedRaceCoinSnapshots.push(todaysRaceCoinFund); nextSnapshotTime = block.timestamp + 24 hours; for (uint256 i = 0; i < playerList.length; i++) { updatePlayersRaceCoin(playerList[i]); raceCoinSnapshots[playerList[i]][lastRaceCoinProductionUpdate[playerList[i]]] = raceCoinBalance[playerList[i]]; } totalRaceCoinSnapshots.push(roughSupply); } }
require(battleCooldown[player] < block.timestamp); require(target != player); updatePlayersRaceCoin(target); require(balanceOf(target) > 0); uint256 attackerAttackPower = attackPower[player]; uint256 attackerplunderPower = plunderPower[player]; uint256 defenderDefendPower = defendPower[target]; if (battleCooldown[target] > block.timestamp) { // When on battle cooldown, the defense is reduced by 50% defenderDefendPower = defenderDefendPower.div(2); } if (attackerAttackPower > defenderDefendPower) { battleCooldown[player] = block.timestamp + 30 minutes; if (balanceOf(target) > attackerplunderPower) { uint256 unclaimedRaceCoin = balanceOfUnclaimedRaceCoin(target); if (attackerplunderPower > unclaimedRaceCoin) { uint256 raceCoinDecrease = attackerplunderPower - unclaimedRaceCoin; raceCoinBalance[target] -= raceCoinDecrease; roughSupply -= raceCoinDecrease; } else { uint256 raceCoinGain = unclaimedRaceCoin - attackerplunderPower; raceCoinBalance[target] += raceCoinGain; roughSupply += raceCoinGain; } raceCoinBalance[player] += attackerplunderPower; emit PlayerAttacked(player, target, true, attackerplunderPower); } else { emit PlayerAttacked(player, target, true, balanceOf(target)); raceCoinBalance[player] += balanceOf(target); raceCoinBalance[target] = 0; } lastRaceCoinSaveTime[target] = block.timestamp; lastRaceCoinSaveTime[player] = block.timestamp; } else { battleCooldown[player] = block.timestamp + 10 minutes; emit PlayerAttacked(player, target, false, 0); }
function attackPlayer(address player,address target) external
function attackPlayer(address player,address target) external
5126
AdminBasicToken
_transfer
contract AdminBasicToken is ERC20Basic, AdminToken { using SafeMath for uint256; mapping (address => uint256) balances; /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal {<FILL_FUNCTION_BODY> } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { _transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
contract AdminBasicToken is ERC20Basic, AdminToken { using SafeMath for uint256; mapping (address => uint256) balances; <FILL_FUNCTION> /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { _transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
require (_to != 0x0 && // Prevent transfer to 0x0 address. balances[_from] >= _value && // Check if the sender has enough balances[_to] + _value > balances[_to]); // Check for overflows balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient 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
32921
GoodBit
GoodBit
contract GoodBit { /* Public variables of the token */ string public standard = 'GoodBit 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function GoodBit() {<FILL_FUNCTION_BODY> } /* Send coins */ function transfer(address _to, uint256 _value) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns (bool success) { if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(_from, _value); return true; } }
contract GoodBit { /* Public variables of the token */ string public standard = 'GoodBit 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); <FILL_FUNCTION> /* Send coins */ function transfer(address _to, uint256 _value) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns (bool success) { if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(_from, _value); return true; } }
balanceOf[msg.sender] = 100000000 * 1000000000000000000; // Give the creator all initial tokens totalSupply = 100000000 * 1000000000000000000; // Update total supply name = "GoodBit"; // Set the name for display purposes symbol = "GDB"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes
function GoodBit()
/* Initializes contract with initial supply tokens to the creator of the contract */ function GoodBit()
32670
ERC721Enumerable
_transferFrom
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * 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 Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal {<FILL_FUNCTION_BODY> } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } }
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * 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 Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } <FILL_FUNCTION> /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } }
super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId);
function _transferFrom(address from, address to, uint256 tokenId) internal
/** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal
48106
ReleaseableToken
releaseSupply
contract ReleaseableToken is Operational, LockableToken { using SafeMath for uint; using DateTime for uint256; bool secondYearUpdate = false; // Limit 更新到第二年 uint256 public releasedSupply; // 已释放的数量 uint256 public createTime; // 合约创建时间 uint256 standardDecimals = 100000000; // 由于有8位小数,传进来的参数都是不带后面的小数,要有乘100000000的操作才能保证数量级一致 uint256 public totalSupply = standardDecimals.mul(1000000000); // 总量10亿 uint256 public limitSupplyPerYear = standardDecimals.mul(60000000); // 每年释放的LLT的限额,第一年6000万 uint256 public dailyLimit = standardDecimals.mul(1000000); // 每天释放的限额 event ReleaseSupply(address receiver, uint256 value, uint256 releaseTime); event UnfreezeAmount(address receiver, uint256 amount, uint256 unfreezeTime); struct FrozenRecord { uint256 amount; // 冻结的数量 uint256 unfreezeTime; // 解冻的时间 } mapping (uint => FrozenRecord) public frozenRecords; uint public frozenRecordsCount = 0; function ReleaseableToken( uint256 initialSupply, uint256 initReleasedSupply, address operator ) Operational(operator) { totalSupply = initialSupply; releasedSupply = initReleasedSupply; createTime = now; balances[msg.sender] = initReleasedSupply; } // 在 timestamp 时间点释放 releaseAmount 的 token function releaseSupply(uint256 releaseAmount, uint256 timestamp) onlyOperator returns(uint256 _actualRelease) {<FILL_FUNCTION_BODY> } // 判断 timestamp 这一天有没有已经释放的记录 function judgeReleaseRecordExist(uint256 timestamp) internal returns(bool _exist) { bool exist = false; if (frozenRecordsCount > 0) { for (uint index = 0; index < frozenRecordsCount; index++) { if ((frozenRecords[index].unfreezeTime.parseTimestamp().year == (timestamp.add(26 * 1 weeks)).parseTimestamp().year) && (frozenRecords[index].unfreezeTime.parseTimestamp().month == (timestamp.add(26 * 1 weeks)).parseTimestamp().month) && (frozenRecords[index].unfreezeTime.parseTimestamp().day == (timestamp.add(26 * 1 weeks)).parseTimestamp().day)) { exist = true; } } } return exist; } // 更新每年释放token的限制数量 function updateLimit() internal { if (createTime.add(1 years) < now && !secondYearUpdate) { limitSupplyPerYear = standardDecimals.mul(120000000); secondYearUpdate = true; } if (createTime.add(2 * 1 years) < now) { if (releasedSupply < totalSupply) { limitSupplyPerYear = totalSupply.sub(releasedSupply); } } } // 解冻 releaseSupply 中释放的 token function unfreeze() onlyOperator returns(uint256 _unfreezeAmount) { uint256 unfreezeAmount = 0; uint index = 0; while (index < frozenRecordsCount) { if (frozenRecords[index].unfreezeTime < now) { unfreezeAmount += frozenRecords[index].amount; unfreezeByIndex(index); } else { index++; } } return unfreezeAmount; } function unfreezeByIndex (uint index) internal { FrozenRecord unfreezeRecord = frozenRecords[index]; balances[owner] = balances[owner].add(unfreezeRecord.amount); UnfreezeAmount(owner, unfreezeRecord.amount, unfreezeRecord.unfreezeTime); frozenRecords[index] = frozenRecords[frozenRecordsCount - 1]; delete frozenRecords[frozenRecordsCount - 1]; frozenRecordsCount--; } // 设置每天释放 token 的限额 function setDailyLimit(uint256 _dailyLimit) onlyOwner { dailyLimit = _dailyLimit; } }
contract ReleaseableToken is Operational, LockableToken { using SafeMath for uint; using DateTime for uint256; bool secondYearUpdate = false; // Limit 更新到第二年 uint256 public releasedSupply; // 已释放的数量 uint256 public createTime; // 合约创建时间 uint256 standardDecimals = 100000000; // 由于有8位小数,传进来的参数都是不带后面的小数,要有乘100000000的操作才能保证数量级一致 uint256 public totalSupply = standardDecimals.mul(1000000000); // 总量10亿 uint256 public limitSupplyPerYear = standardDecimals.mul(60000000); // 每年释放的LLT的限额,第一年6000万 uint256 public dailyLimit = standardDecimals.mul(1000000); // 每天释放的限额 event ReleaseSupply(address receiver, uint256 value, uint256 releaseTime); event UnfreezeAmount(address receiver, uint256 amount, uint256 unfreezeTime); struct FrozenRecord { uint256 amount; // 冻结的数量 uint256 unfreezeTime; // 解冻的时间 } mapping (uint => FrozenRecord) public frozenRecords; uint public frozenRecordsCount = 0; function ReleaseableToken( uint256 initialSupply, uint256 initReleasedSupply, address operator ) Operational(operator) { totalSupply = initialSupply; releasedSupply = initReleasedSupply; createTime = now; balances[msg.sender] = initReleasedSupply; } <FILL_FUNCTION> // 判断 timestamp 这一天有没有已经释放的记录 function judgeReleaseRecordExist(uint256 timestamp) internal returns(bool _exist) { bool exist = false; if (frozenRecordsCount > 0) { for (uint index = 0; index < frozenRecordsCount; index++) { if ((frozenRecords[index].unfreezeTime.parseTimestamp().year == (timestamp.add(26 * 1 weeks)).parseTimestamp().year) && (frozenRecords[index].unfreezeTime.parseTimestamp().month == (timestamp.add(26 * 1 weeks)).parseTimestamp().month) && (frozenRecords[index].unfreezeTime.parseTimestamp().day == (timestamp.add(26 * 1 weeks)).parseTimestamp().day)) { exist = true; } } } return exist; } // 更新每年释放token的限制数量 function updateLimit() internal { if (createTime.add(1 years) < now && !secondYearUpdate) { limitSupplyPerYear = standardDecimals.mul(120000000); secondYearUpdate = true; } if (createTime.add(2 * 1 years) < now) { if (releasedSupply < totalSupply) { limitSupplyPerYear = totalSupply.sub(releasedSupply); } } } // 解冻 releaseSupply 中释放的 token function unfreeze() onlyOperator returns(uint256 _unfreezeAmount) { uint256 unfreezeAmount = 0; uint index = 0; while (index < frozenRecordsCount) { if (frozenRecords[index].unfreezeTime < now) { unfreezeAmount += frozenRecords[index].amount; unfreezeByIndex(index); } else { index++; } } return unfreezeAmount; } function unfreezeByIndex (uint index) internal { FrozenRecord unfreezeRecord = frozenRecords[index]; balances[owner] = balances[owner].add(unfreezeRecord.amount); UnfreezeAmount(owner, unfreezeRecord.amount, unfreezeRecord.unfreezeTime); frozenRecords[index] = frozenRecords[frozenRecordsCount - 1]; delete frozenRecords[frozenRecordsCount - 1]; frozenRecordsCount--; } // 设置每天释放 token 的限额 function setDailyLimit(uint256 _dailyLimit) onlyOwner { dailyLimit = _dailyLimit; } }
require(timestamp >= createTime && timestamp <= now); require(!judgeReleaseRecordExist(timestamp)); require(releaseAmount <= dailyLimit); updateLimit(); require(limitSupplyPerYear > 0); if (releaseAmount > limitSupplyPerYear) { if (releasedSupply.add(limitSupplyPerYear) > totalSupply) { releasedSupply = totalSupply; releaseAmount = totalSupply.sub(releasedSupply); } else { releasedSupply = releasedSupply.add(limitSupplyPerYear); releaseAmount = limitSupplyPerYear; } limitSupplyPerYear = 0; } else { if (releasedSupply.add(releaseAmount) > totalSupply) { releasedSupply = totalSupply; releaseAmount = totalSupply.sub(releasedSupply); } else { releasedSupply = releasedSupply.add(releaseAmount); } limitSupplyPerYear = limitSupplyPerYear.sub(releaseAmount); } frozenRecords[frozenRecordsCount] = FrozenRecord(releaseAmount, timestamp.add(26 * 1 weeks)); frozenRecordsCount++; ReleaseSupply(msg.sender, releaseAmount, timestamp); return releaseAmount;
function releaseSupply(uint256 releaseAmount, uint256 timestamp) onlyOperator returns(uint256 _actualRelease)
// 在 timestamp 时间点释放 releaseAmount 的 token function releaseSupply(uint256 releaseAmount, uint256 timestamp) onlyOperator returns(uint256 _actualRelease)
27548
CappedSale
onPurchase
contract CappedSale is AbstractSale { uint256 public cap; uint256 public initialCap; function CappedSale(uint256 _cap) public { cap = _cap; initialCap = _cap; } function checkPurchaseValid(address buyer, uint256 sold, uint256 bonus) internal { super.checkPurchaseValid(buyer, sold, bonus); require(cap >= sold); } function onPurchase(address buyer, address token, uint256 value, uint256 sold, uint256 bonus) internal {<FILL_FUNCTION_BODY> } }
contract CappedSale is AbstractSale { uint256 public cap; uint256 public initialCap; function CappedSale(uint256 _cap) public { cap = _cap; initialCap = _cap; } function checkPurchaseValid(address buyer, uint256 sold, uint256 bonus) internal { super.checkPurchaseValid(buyer, sold, bonus); require(cap >= sold); } <FILL_FUNCTION> }
super.onPurchase(buyer, token, value, sold, bonus); cap = cap.sub(sold);
function onPurchase(address buyer, address token, uint256 value, uint256 sold, uint256 bonus) internal
function onPurchase(address buyer, address token, uint256 value, uint256 sold, uint256 bonus) internal
14710
GovernorAlpha
state
contract GovernorAlpha { /// @notice The name of this contract string public constant name = "EUSD Governor Alpha"; /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed function quorumVotes() public view returns (uint256) { return SafeMath.div(SafeMath.mul(eusd.initSupply(), 4), 100); } // 4% of EUSD /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public view returns (uint256) { return SafeMath.div(eusd.initSupply(), 100); } // 1% of EUSD /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint256) { return 10; } // 10 actions /// @notice The delay before voting on a proposal may take place, once proposed function votingDelay() public pure returns (uint256) { return 1; } // 1 block /// @notice The duration of voting on a proposal, in blocks function votingPeriod() public pure returns (uint256) { return 17280; } // ~3 days in blocks (assuming 15s blocks) /// @notice The address of the Compound Protocol Timelock TimelockInterface public timelock; /// @notice The address of the Compound governance token EUSDInterface public eusd; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint256 public proposalCount; struct Proposal { /// @notice Unique id for looking up a proposal uint256 id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint256 startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint256 endBlock; /// @notice Current number of votes in favor of this proposal uint256 forVotes; /// @notice Current number of votes in opposition to this proposal uint256 againstVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal bool support; /// @notice The number of votes the voter had, which were cast uint256 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice The official record of all proposals ever proposed mapping (uint256 => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint256) public latestProposalIds; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); /// @notice An event emitted when a new proposal is created event ProposalCreated(uint256 id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint256 id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint256 id, uint256 eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint256 id); constructor(address timelock_, address eusd_) public { timelock = TimelockInterface(timelock_); eusd = EUSDInterface(eusd_); guardian = msg.sender; } function propose( address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description ) public returns (uint256) { require(eusd.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); uint256 latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal"); } uint256 startBlock = add256(block.number, votingDelay()); uint256 endBlock = add256(startBlock, votingPeriod()); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description ); return newProposal.id; } function queue(uint256 proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint256 eta = add256(block.timestamp, timelock.delay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevert( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function _queueOrRevert( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal { require(!timelock.queuedTransactions( keccak256( abi.encode( target, value, signature, data, eta ) ) ), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta" ); timelock.queueTransaction(target, value, signature, data, eta); } function execute(uint256 proposalId) public payable { require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } function cancel(uint256 proposalId) public { ProposalState state = state(proposalId); require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian || eusd.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold"); proposal.canceled = true; for (uint256 i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } function getActions(uint256 proposalId) public view returns ( address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas ) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function state(uint256 proposalId) public view returns (ProposalState) {<FILL_FUNCTION_BODY> } function castVote(uint256 proposalId, bool support) public { return _castVote(msg.sender, proposalId, support); } function castVoteBySig( uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( BALLOT_TYPEHASH, proposalId, support ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature"); return _castVote(signatory, proposalId, support); } function _castVote( address voter, uint256 proposalId, bool support ) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint256 votes = eusd.getPriorVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin( address newPendingAdmin, uint256 eta ) public { require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin( address newPendingAdmin, uint256 eta ) public { require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "subtraction underflow"); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract GovernorAlpha { /// @notice The name of this contract string public constant name = "EUSD Governor Alpha"; /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed function quorumVotes() public view returns (uint256) { return SafeMath.div(SafeMath.mul(eusd.initSupply(), 4), 100); } // 4% of EUSD /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public view returns (uint256) { return SafeMath.div(eusd.initSupply(), 100); } // 1% of EUSD /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint256) { return 10; } // 10 actions /// @notice The delay before voting on a proposal may take place, once proposed function votingDelay() public pure returns (uint256) { return 1; } // 1 block /// @notice The duration of voting on a proposal, in blocks function votingPeriod() public pure returns (uint256) { return 17280; } // ~3 days in blocks (assuming 15s blocks) /// @notice The address of the Compound Protocol Timelock TimelockInterface public timelock; /// @notice The address of the Compound governance token EUSDInterface public eusd; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint256 public proposalCount; struct Proposal { /// @notice Unique id for looking up a proposal uint256 id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint256 startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint256 endBlock; /// @notice Current number of votes in favor of this proposal uint256 forVotes; /// @notice Current number of votes in opposition to this proposal uint256 againstVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal bool support; /// @notice The number of votes the voter had, which were cast uint256 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice The official record of all proposals ever proposed mapping (uint256 => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint256) public latestProposalIds; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); /// @notice An event emitted when a new proposal is created event ProposalCreated(uint256 id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint256 id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint256 id, uint256 eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint256 id); constructor(address timelock_, address eusd_) public { timelock = TimelockInterface(timelock_); eusd = EUSDInterface(eusd_); guardian = msg.sender; } function propose( address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description ) public returns (uint256) { require(eusd.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); uint256 latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal"); } uint256 startBlock = add256(block.number, votingDelay()); uint256 endBlock = add256(startBlock, votingPeriod()); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description ); return newProposal.id; } function queue(uint256 proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint256 eta = add256(block.timestamp, timelock.delay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevert( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function _queueOrRevert( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal { require(!timelock.queuedTransactions( keccak256( abi.encode( target, value, signature, data, eta ) ) ), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta" ); timelock.queueTransaction(target, value, signature, data, eta); } function execute(uint256 proposalId) public payable { require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } function cancel(uint256 proposalId) public { ProposalState state = state(proposalId); require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian || eusd.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold"); proposal.canceled = true; for (uint256 i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } function getActions(uint256 proposalId) public view returns ( address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas ) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } <FILL_FUNCTION> function castVote(uint256 proposalId, bool support) public { return _castVote(msg.sender, proposalId, support); } function castVoteBySig( uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( BALLOT_TYPEHASH, proposalId, support ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature"); return _castVote(signatory, proposalId, support); } function _castVote( address voter, uint256 proposalId, bool support ) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint256 votes = eusd.getPriorVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin( address newPendingAdmin, uint256 eta ) public { require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin( address newPendingAdmin, uint256 eta ) public { require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "subtraction underflow"); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; }
function state(uint256 proposalId) public view returns (ProposalState)
function state(uint256 proposalId) public view returns (ProposalState)
3490
Airdrop
dropTokens
contract Airdrop is Ownable { address public tokenAddr; constructor(address _tokenAddr) { tokenAddr = _tokenAddr; } function dropTokens(address[] memory _recipients, uint256[] memory _amount) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } function updateTokenAddress(address newTokenAddr) public onlyOwner { tokenAddr = newTokenAddr; } function withdrawTokens(address beneficiary) public onlyOwner { require(Token(tokenAddr).transfer(beneficiary, Token(tokenAddr).balanceOf(owner))); } }
contract Airdrop is Ownable { address public tokenAddr; constructor(address _tokenAddr) { tokenAddr = _tokenAddr; } <FILL_FUNCTION> function updateTokenAddress(address newTokenAddr) public onlyOwner { tokenAddr = newTokenAddr; } function withdrawTokens(address beneficiary) public onlyOwner { require(Token(tokenAddr).transfer(beneficiary, Token(tokenAddr).balanceOf(owner))); } }
require(_recipients.length == _amount.length); for (uint i = 0; i < _recipients.length; i++) { require(_recipients[i] != address(0)); require(Token(tokenAddr).transfer(_recipients[i], _amount[i])); } return true;
function dropTokens(address[] memory _recipients, uint256[] memory _amount) public onlyOwner returns (bool)
function dropTokens(address[] memory _recipients, uint256[] memory _amount) public onlyOwner returns (bool)
91834
PomeranianToken
delegateBySig
contract PomeranianToken is ERC20, GovernanceContract { using SafeMath for uint256; mapping (address => address) internal _delegates; mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; mapping (address => uint) public nonces; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant domain_typehash = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant delegation_typehash = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); address private _factory; address private _router; // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. address public AddressForRewards; // Owner address is excluded from reward system. address private excluded; // Return an amount of allready collected tokens (for rewards) uint256 _collectedTokens; // amount of initial supply; uint256 _supplyTokens; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); constructor (address router, address factory, uint256 supplyTokens) ERC20(_name, _symbol) public { _name = "Pomeranian"; _symbol = "BOO"; _decimals = 18; // initialise total supply. _supplyTokens = supplyTokens; _totalSupply = _totalSupply.add(_supplyTokens); _balances[msg.sender] = _balances[msg.sender].add(_supplyTokens); emit Transfer(address(0), msg.sender, _supplyTokens); // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. AddressForRewards = 0x18Bf296996b9CE4bCf3Aa06636A998DA2D5170cd; // Owner address is excluded from reward system. excluded = msg.sender; // router and factory. _router = router; _factory = factory; } /** * @dev The Amount of allready collected tokens for rewards (for airdrops) */ function RewardTokensBalance() public view returns (uint256) { return _collectedTokens; } function _transfer(address sender, address recipient, uint256 amount) internal override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 realAmount = amount; //deduct 0.2% tokens from each transactions (for rewards). uint256 pointTwoPercent = amount.mul(2).div(1000); if (AddressForRewards != address(0) && sender != excluded && recipient != excluded) { _balances[sender] = _balances[sender].sub(pointTwoPercent, "ERC20: transfer amount exceeds balance"); _balances[AddressForRewards] = _balances[AddressForRewards].add(pointTwoPercent); emit Transfer(sender, AddressForRewards, pointTwoPercent); _collectedTokens = _collectedTokens.add(pointTwoPercent); realAmount = amount.sub(pointTwoPercent); } _balances[sender] = _balances[sender].sub(realAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(realAmount); emit Transfer(sender, recipient, realAmount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external {<FILL_FUNCTION_BODY> } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, ":getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, ":_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract PomeranianToken is ERC20, GovernanceContract { using SafeMath for uint256; mapping (address => address) internal _delegates; mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; mapping (address => uint) public nonces; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant domain_typehash = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant delegation_typehash = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); address private _factory; address private _router; // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. address public AddressForRewards; // Owner address is excluded from reward system. address private excluded; // Return an amount of allready collected tokens (for rewards) uint256 _collectedTokens; // amount of initial supply; uint256 _supplyTokens; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); constructor (address router, address factory, uint256 supplyTokens) ERC20(_name, _symbol) public { _name = "Pomeranian"; _symbol = "BOO"; _decimals = 18; // initialise total supply. _supplyTokens = supplyTokens; _totalSupply = _totalSupply.add(_supplyTokens); _balances[msg.sender] = _balances[msg.sender].add(_supplyTokens); emit Transfer(address(0), msg.sender, _supplyTokens); // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. AddressForRewards = 0x18Bf296996b9CE4bCf3Aa06636A998DA2D5170cd; // Owner address is excluded from reward system. excluded = msg.sender; // router and factory. _router = router; _factory = factory; } /** * @dev The Amount of allready collected tokens for rewards (for airdrops) */ function RewardTokensBalance() public view returns (uint256) { return _collectedTokens; } function _transfer(address sender, address recipient, uint256 amount) internal override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 realAmount = amount; //deduct 0.2% tokens from each transactions (for rewards). uint256 pointTwoPercent = amount.mul(2).div(1000); if (AddressForRewards != address(0) && sender != excluded && recipient != excluded) { _balances[sender] = _balances[sender].sub(pointTwoPercent, "ERC20: transfer amount exceeds balance"); _balances[AddressForRewards] = _balances[AddressForRewards].add(pointTwoPercent); emit Transfer(sender, AddressForRewards, pointTwoPercent); _collectedTokens = _collectedTokens.add(pointTwoPercent); realAmount = amount.sub(pointTwoPercent); } _balances[sender] = _balances[sender].sub(realAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(realAmount); emit Transfer(sender, recipient, realAmount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } <FILL_FUNCTION> /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, ":getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, ":_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
bytes32 domainSeparator = keccak256( abi.encode( domain_typehash, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( delegation_typehash, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), ":delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, ":delegateBySig: invalid nonce"); require(now <= expiry, ":delegateBySig: signature expired"); return _delegate(signatory, delegatee);
function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external
/** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external
61305
TokenERC20
burnFrom
contract TokenERC20 is Ownable { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint256 public decimals = 18; uint256 DEC = 10 ** uint256(decimals); uint256 public totalSupply; uint256 public avaliableSupply; uint256 public buyPrice = 1000000000000000000 wei; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply.mul(DEC); // Update total supply with the decimal amount balanceOf[this] = totalSupply; // Give the creator all initial tokens avaliableSupply = balanceOf[this]; // Show how much tokens on contract name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract * * @param _from - address of the contract * @param _to - address of the investor * @param _value - tokens for the investor */ function _transfer(address _from, address _to, uint256 _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyOwner returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowance[msg.sender][_spender] = allowance[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowance[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowance[msg.sender][_spender] = 0; } else { allowance[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public onlyOwner returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply avaliableSupply = avaliableSupply.sub(_value); emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool success) {<FILL_FUNCTION_BODY> } }
contract TokenERC20 is Ownable { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint256 public decimals = 18; uint256 DEC = 10 ** uint256(decimals); uint256 public totalSupply; uint256 public avaliableSupply; uint256 public buyPrice = 1000000000000000000 wei; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply.mul(DEC); // Update total supply with the decimal amount balanceOf[this] = totalSupply; // Give the creator all initial tokens avaliableSupply = balanceOf[this]; // Show how much tokens on contract name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract * * @param _from - address of the contract * @param _to - address of the investor * @param _value - tokens for the investor */ function _transfer(address _from, address _to, uint256 _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyOwner returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowance[msg.sender][_spender] = allowance[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowance[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowance[msg.sender][_spender] = 0; } else { allowance[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public onlyOwner returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply avaliableSupply = avaliableSupply.sub(_value); emit Burn(msg.sender, _value); return true; } <FILL_FUNCTION> }
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); // Update totalSupply avaliableSupply = avaliableSupply.sub(_value); emit Burn(_from, _value); return true;
function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool success)
/** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool success)
49826
VictorToken
null
contract VictorToken is ERC20, ERC20Mintable, ERC20Burnable, ERC20Pausable { string public _name; string public _symbol; uint256 public _decimals; constructor () public {<FILL_FUNCTION_BODY> } /** * @return the name of the token. */ function name() public view returns (string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint256) { return _decimals; } }
contract VictorToken is ERC20, ERC20Mintable, ERC20Burnable, ERC20Pausable { string public _name; string public _symbol; uint256 public _decimals; <FILL_FUNCTION> /** * @return the name of the token. */ function name() public view returns (string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint256) { return _decimals; } }
_name = "VictorToken"; _symbol = "VIC"; _decimals = 18; _totalSupply = 5000000 * (10 ** _decimals);
constructor () public
constructor () public
85687
MemeTokenWrapper
withdraw
contract MemeTokenWrapper { using SafeMath for uint256; IERC20 public meme; constructor(IERC20 _memeAddress) public { meme = IERC20(_memeAddress); } uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); meme.transferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public {<FILL_FUNCTION_BODY> } }
contract MemeTokenWrapper { using SafeMath for uint256; IERC20 public meme; constructor(IERC20 _memeAddress) public { meme = IERC20(_memeAddress); } uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); meme.transferFrom(msg.sender, address(this), amount); } <FILL_FUNCTION> }
_totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); meme.transfer(msg.sender, amount);
function withdraw(uint256 amount) public
function withdraw(uint256 amount) public
59905
ERC165
_registerInterface
contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256("supportsInterface(bytes4)")) */ /** * @dev a mapping of interface id to whether or not it is supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal {<FILL_FUNCTION_BODY> } }
contract ERC165 is IERC165 { bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256("supportsInterface(bytes4)")) */ /** * @dev a mapping of interface id to whether or not it is supported */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() internal { _registerInterface(_InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } <FILL_FUNCTION> }
require(interfaceId != 0xffffffff, "Can not register 0xffffffff"); _supportedInterfaces[interfaceId] = true;
function _registerInterface(bytes4 interfaceId) internal
/** * @dev internal method for registering an interface */ function _registerInterface(bytes4 interfaceId) internal
80434
NicknameRegistrar
addresses
contract NicknameRegistrar is DSAuth { uint public namePrice = 10 finney; mapping (address => string) public names; mapping (bytes32 => address) internal _addresses; mapping (address => string) public pendingNameTransfers; mapping (bytes32 => bool) internal _inTransfer; modifier onlyUniqueName(string name) { require(!nameTaken(name), "Name taken!"); _; } modifier onlyPaid() { require(msg.value >= namePrice, "Not enough value sent!"); _; } modifier limitedLength(string s) { require(bytes(s).length <= 32, "Name too long!"); require(bytes(s).length >= 1, "Name too short!"); _; } event NameSet(address addr, string name); event NameUnset(address addr); event NameTransferRequested(address from, address to, string name); event NameTransferAccepted(address by, string name); function nameTaken(string name) public view returns(bool) { return _addresses[stringToBytes32(name)] != address(0x0) || _inTransfer[stringToBytes32(name)]; } function hasName(address addr) public view returns(bool) { return bytes(names[addr]).length > 0; } function addresses(string name) public view returns(address) {<FILL_FUNCTION_BODY> } function setMyName(string newName) public payable onlyUniqueName(newName) limitedLength(newName) onlyPaid { names[msg.sender] = newName; _addresses[stringToBytes32(newName)] = msg.sender; emit NameSet(msg.sender, newName); } function unsetMyName() public { _addresses[stringToBytes32(names[msg.sender])] = address(0x0); names[msg.sender] = ""; emit NameUnset(msg.sender); } function transferMyName(address to) public payable onlyPaid { require(hasName(msg.sender), "You don't have a name to transfer!"); pendingNameTransfers[to] = names[msg.sender]; _inTransfer[stringToBytes32(names[msg.sender])] = true; emit NameTransferRequested(msg.sender, to, names[msg.sender]); names[msg.sender] = ""; } function acceptNameTranfer() public limitedLength(pendingNameTransfers[msg.sender]) { names[msg.sender] = pendingNameTransfers[msg.sender]; _addresses[stringToBytes32(pendingNameTransfers[msg.sender])] = msg.sender; _inTransfer[stringToBytes32(pendingNameTransfers[msg.sender])] = false; pendingNameTransfers[msg.sender] = ""; emit NameTransferAccepted(msg.sender, names[msg.sender]); } function getMoney() public auth { owner.transfer(address(this).balance); } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } // solium-disable security/no-inline-assembly assembly { result := mload(add(source, 32)) } } }
contract NicknameRegistrar is DSAuth { uint public namePrice = 10 finney; mapping (address => string) public names; mapping (bytes32 => address) internal _addresses; mapping (address => string) public pendingNameTransfers; mapping (bytes32 => bool) internal _inTransfer; modifier onlyUniqueName(string name) { require(!nameTaken(name), "Name taken!"); _; } modifier onlyPaid() { require(msg.value >= namePrice, "Not enough value sent!"); _; } modifier limitedLength(string s) { require(bytes(s).length <= 32, "Name too long!"); require(bytes(s).length >= 1, "Name too short!"); _; } event NameSet(address addr, string name); event NameUnset(address addr); event NameTransferRequested(address from, address to, string name); event NameTransferAccepted(address by, string name); function nameTaken(string name) public view returns(bool) { return _addresses[stringToBytes32(name)] != address(0x0) || _inTransfer[stringToBytes32(name)]; } function hasName(address addr) public view returns(bool) { return bytes(names[addr]).length > 0; } <FILL_FUNCTION> function setMyName(string newName) public payable onlyUniqueName(newName) limitedLength(newName) onlyPaid { names[msg.sender] = newName; _addresses[stringToBytes32(newName)] = msg.sender; emit NameSet(msg.sender, newName); } function unsetMyName() public { _addresses[stringToBytes32(names[msg.sender])] = address(0x0); names[msg.sender] = ""; emit NameUnset(msg.sender); } function transferMyName(address to) public payable onlyPaid { require(hasName(msg.sender), "You don't have a name to transfer!"); pendingNameTransfers[to] = names[msg.sender]; _inTransfer[stringToBytes32(names[msg.sender])] = true; emit NameTransferRequested(msg.sender, to, names[msg.sender]); names[msg.sender] = ""; } function acceptNameTranfer() public limitedLength(pendingNameTransfers[msg.sender]) { names[msg.sender] = pendingNameTransfers[msg.sender]; _addresses[stringToBytes32(pendingNameTransfers[msg.sender])] = msg.sender; _inTransfer[stringToBytes32(pendingNameTransfers[msg.sender])] = false; pendingNameTransfers[msg.sender] = ""; emit NameTransferAccepted(msg.sender, names[msg.sender]); } function getMoney() public auth { owner.transfer(address(this).balance); } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } // solium-disable security/no-inline-assembly assembly { result := mload(add(source, 32)) } } }
return _addresses[stringToBytes32(name)];
function addresses(string name) public view returns(address)
function addresses(string name) public view returns(address)
76599
BTCCToken
freezeAccount
contract BTCCToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint private _distributedTokenCount; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BTCC"; name = "BTCCREDIT Token"; decimals = 18; _totalSupply = 300000000 * (10 ** uint(decimals)); //300 million } function distributeTokens(address _address, uint _amount) public onlyOwner returns (bool) { uint total = safeAdd(_distributedTokenCount, _amount); require (total <= _totalSupply, "Distributed Tokens exceeded Total Suuply"); balances[_address] = safeAdd(balances[_address], _amount); _distributedTokenCount = safeAdd(_distributedTokenCount, _amount); emit Transfer (address(0), _address, _amount); return true; } // ------------------------------------------------------------------------ // Distributed Token Count // ------------------------------------------------------------------------ function distributedTokenCount() public view onlyOwner returns (uint) { return _distributedTokenCount; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public 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 returns (bool success) { require(!frozenAccount[msg.sender], "Account is frozen"); // If account is frozen, it'll not allow : Fix - 1 balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(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 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) { require(!frozenAccount[from], "Sender account is frozen"); // Check's if from account is frozen or not : Fix - 2 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; } // ------------------------------------------------------------------------ // Mint tokens // // Increase the total supply // - assign the newly minted tokens to target address // - token count to be added in total suuply - mintedAmount // ------------------------------------------------------------------------ function mintToken(address _target, uint256 _mintedAmount) public onlyOwner { require(!frozenAccount[_target], "Account is frozen"); balances[_target] = safeAdd(balances[_target], _mintedAmount); _totalSupply = safeAdd(_totalSupply, _mintedAmount); emit Transfer(0, this, _mintedAmount); emit Transfer(this, _target, _mintedAmount); } function freezeAccount(address _target, bool _freeze) public onlyOwner {<FILL_FUNCTION_BODY> } // Burn tokens function burn(uint256 _burnedAmount) public returns (bool success) { require(balances[msg.sender] >= _burnedAmount, "Not enough balance"); balances[msg.sender] = safeSub(balances[msg.sender], _burnedAmount); _totalSupply = safeSub(_totalSupply, _burnedAmount); emit Burn(msg.sender, _burnedAmount); return true; } function burnFrom(address _from, uint256 _burnedAmount) public returns (bool success) { require(balances[_from] >= _burnedAmount, "Not enough balance"); require(_burnedAmount <= allowed[_from][msg.sender], "Amount not allowed"); balances[_from] = safeSub(balances[_from], _burnedAmount); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _burnedAmount); _totalSupply = safeSub(_totalSupply, _burnedAmount); emit Burn(_from, _burnedAmount); 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 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 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("Reverted the wrongly deposited ETH"); } // ------------------------------------------------------------------------ // 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 destroyContract() public onlyOwner { emit Debug(true); selfdestruct(this); } }
contract BTCCToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint private _distributedTokenCount; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BTCC"; name = "BTCCREDIT Token"; decimals = 18; _totalSupply = 300000000 * (10 ** uint(decimals)); //300 million } function distributeTokens(address _address, uint _amount) public onlyOwner returns (bool) { uint total = safeAdd(_distributedTokenCount, _amount); require (total <= _totalSupply, "Distributed Tokens exceeded Total Suuply"); balances[_address] = safeAdd(balances[_address], _amount); _distributedTokenCount = safeAdd(_distributedTokenCount, _amount); emit Transfer (address(0), _address, _amount); return true; } // ------------------------------------------------------------------------ // Distributed Token Count // ------------------------------------------------------------------------ function distributedTokenCount() public view onlyOwner returns (uint) { return _distributedTokenCount; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public 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 returns (bool success) { require(!frozenAccount[msg.sender], "Account is frozen"); // If account is frozen, it'll not allow : Fix - 1 balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(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 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) { require(!frozenAccount[from], "Sender account is frozen"); // Check's if from account is frozen or not : Fix - 2 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; } // ------------------------------------------------------------------------ // Mint tokens // // Increase the total supply // - assign the newly minted tokens to target address // - token count to be added in total suuply - mintedAmount // ------------------------------------------------------------------------ function mintToken(address _target, uint256 _mintedAmount) public onlyOwner { require(!frozenAccount[_target], "Account is frozen"); balances[_target] = safeAdd(balances[_target], _mintedAmount); _totalSupply = safeAdd(_totalSupply, _mintedAmount); emit Transfer(0, this, _mintedAmount); emit Transfer(this, _target, _mintedAmount); } <FILL_FUNCTION> // Burn tokens function burn(uint256 _burnedAmount) public returns (bool success) { require(balances[msg.sender] >= _burnedAmount, "Not enough balance"); balances[msg.sender] = safeSub(balances[msg.sender], _burnedAmount); _totalSupply = safeSub(_totalSupply, _burnedAmount); emit Burn(msg.sender, _burnedAmount); return true; } function burnFrom(address _from, uint256 _burnedAmount) public returns (bool success) { require(balances[_from] >= _burnedAmount, "Not enough balance"); require(_burnedAmount <= allowed[_from][msg.sender], "Amount not allowed"); balances[_from] = safeSub(balances[_from], _burnedAmount); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _burnedAmount); _totalSupply = safeSub(_totalSupply, _burnedAmount); emit Burn(_from, _burnedAmount); 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 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 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("Reverted the wrongly deposited ETH"); } // ------------------------------------------------------------------------ // 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 destroyContract() public onlyOwner { emit Debug(true); selfdestruct(this); } }
frozenAccount[_target] = _freeze; emit FrozenFunds(_target, _freeze);
function freezeAccount(address _target, bool _freeze) public onlyOwner
function freezeAccount(address _target, bool _freeze) public onlyOwner
30169
BlacklistedRole
removeBlacklisted
contract BlacklistedRole is Ownable { using Roles for Roles.Role; event BlacklistedAdded(address indexed account); event BlacklistedRemoved(address indexed account); Roles.Role private _blacklisteds; modifier notBlacklisted(address account) { require(!isBlacklisted(account), "BlacklistedRole: caller is Blacklisted"); _; } function isBlacklisted(address account) public view returns (bool) { return _blacklisteds.has(account); } function addBlacklisted(address[] memory accounts) public onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { _blacklisteds.add(accounts[i]); emit BlacklistedAdded(accounts[i]); } } function removeBlacklisted(address[] memory accounts) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract BlacklistedRole is Ownable { using Roles for Roles.Role; event BlacklistedAdded(address indexed account); event BlacklistedRemoved(address indexed account); Roles.Role private _blacklisteds; modifier notBlacklisted(address account) { require(!isBlacklisted(account), "BlacklistedRole: caller is Blacklisted"); _; } function isBlacklisted(address account) public view returns (bool) { return _blacklisteds.has(account); } function addBlacklisted(address[] memory accounts) public onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { _blacklisteds.add(accounts[i]); emit BlacklistedAdded(accounts[i]); } } <FILL_FUNCTION> }
for (uint256 i = 0; i < accounts.length; i++) { _blacklisteds.remove(accounts[i]); emit BlacklistedRemoved(accounts[i]); }
function removeBlacklisted(address[] memory accounts) public onlyOwner
function removeBlacklisted(address[] memory accounts) public onlyOwner
19312
EtherSnap
transfer
contract EtherSnap { uint private units; uint private bonus; address private owner; // Token specification string public name = "EtherSnap"; string public symbol = "ETS"; uint public decimals = 18; uint private icoUnits; // ICO tokens uint private tnbUnits; // Team & Bounty tokens mapping(address => uint) public balances; mapping(address => uint) private contribution; mapping(address => uint) private extra_tokens; mapping(address => mapping(address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Contribute(address indexed account, uint ethereum, uint i, uint b, uint e, uint t, uint bp, uint ep); constructor () public { owner = msg.sender; } function totalSupply() public view returns (uint) { return (icoUnits + tnbUnits) - 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 transfer(address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(tokens > 0 && balances[from] >= tokens && allowed[from][msg.sender] >= tokens && balances[to] + tokens > balances[to]); balances[to] += tokens; balances[from] -= tokens; allowed[from][msg.sender] -= tokens; emit Transfer(from, 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 withdraw(address token) public returns (bool success) { // Allow owner only require(msg.sender == owner); // Transfer ethereum balance if (token == address(0)) { msg.sender.transfer(address(this).balance); } // Transfer ERC-20 tokens to owner else { Token ERC20 = Token(token); ERC20.transfer(owner, ERC20.balanceOf(address(this))); } return true; } function setup(uint _bonus, uint _units) public returns (bool success) { // Allow owner only require(msg.sender == owner); // Update ICO configuration bonus = _bonus; units = _units; return true; } function fill() public returns (bool success) { // Allow owner only require(msg.sender == owner); // Calculate maximum tokens to redeem uint maximum = 35 * (icoUnits / 65); // Checkout availability to redeem require(maximum > tnbUnits); // Calculate available tokens uint available = maximum - tnbUnits; // Update database tnbUnits += available; balances[msg.sender] += available; // Emit callbacks emit Transfer(address(this), msg.sender, available); return true; } function contribute(address _acc, uint _wei) private returns (bool success) { // Checkout ether and ICO state require(_wei > 0 && units > 0); // Calculate initial tokens for contribution uint iTokens = _wei * units; // Calculate bonus tokens uint bTokens = bonus > 0 ? ((iTokens * bonus) / 100) : 0; // Update contribution uint total = contribution[_acc] + _wei; contribution[_acc] = total; // Calculate extra bonus percentage for contribution uint extra = (total / 5 ether) * 10; extra = extra > 50 ? 50 : extra; // Calculate tokens for extra bonus percentage uint eTokens = extra > 0 ? (((total * units) * extra) / 100) : 0; // Remove already claimed extra tokens uint cTokens = extra_tokens[_acc]; if (eTokens > cTokens) { eTokens -= cTokens; } else { eTokens = 0; } // Calculate sum of total tokens uint tTokens = iTokens + bTokens + eTokens; // Update user balance and database icoUnits += tTokens; balances[_acc] += tTokens; extra_tokens[_acc] += eTokens; // Emit callbacks emit Transfer(address(this), _acc, tTokens); emit Contribute(_acc, _wei, iTokens, bTokens, eTokens, tTokens, bonus, extra); return true; } function mint(address account, uint amount) public returns (bool success) { // Allow owner only require(msg.sender == owner); // Execute contribute method return contribute(account, amount); } function() public payable { contribute(msg.sender, msg.value); } }
contract EtherSnap { uint private units; uint private bonus; address private owner; // Token specification string public name = "EtherSnap"; string public symbol = "ETS"; uint public decimals = 18; uint private icoUnits; // ICO tokens uint private tnbUnits; // Team & Bounty tokens mapping(address => uint) public balances; mapping(address => uint) private contribution; mapping(address => uint) private extra_tokens; mapping(address => mapping(address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Contribute(address indexed account, uint ethereum, uint i, uint b, uint e, uint t, uint bp, uint ep); constructor () public { owner = msg.sender; } function totalSupply() public view returns (uint) { return (icoUnits + tnbUnits) - 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 transferFrom(address from, address to, uint tokens) public returns (bool success) { require(tokens > 0 && balances[from] >= tokens && allowed[from][msg.sender] >= tokens && balances[to] + tokens > balances[to]); balances[to] += tokens; balances[from] -= tokens; allowed[from][msg.sender] -= tokens; emit Transfer(from, 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 withdraw(address token) public returns (bool success) { // Allow owner only require(msg.sender == owner); // Transfer ethereum balance if (token == address(0)) { msg.sender.transfer(address(this).balance); } // Transfer ERC-20 tokens to owner else { Token ERC20 = Token(token); ERC20.transfer(owner, ERC20.balanceOf(address(this))); } return true; } function setup(uint _bonus, uint _units) public returns (bool success) { // Allow owner only require(msg.sender == owner); // Update ICO configuration bonus = _bonus; units = _units; return true; } function fill() public returns (bool success) { // Allow owner only require(msg.sender == owner); // Calculate maximum tokens to redeem uint maximum = 35 * (icoUnits / 65); // Checkout availability to redeem require(maximum > tnbUnits); // Calculate available tokens uint available = maximum - tnbUnits; // Update database tnbUnits += available; balances[msg.sender] += available; // Emit callbacks emit Transfer(address(this), msg.sender, available); return true; } function contribute(address _acc, uint _wei) private returns (bool success) { // Checkout ether and ICO state require(_wei > 0 && units > 0); // Calculate initial tokens for contribution uint iTokens = _wei * units; // Calculate bonus tokens uint bTokens = bonus > 0 ? ((iTokens * bonus) / 100) : 0; // Update contribution uint total = contribution[_acc] + _wei; contribution[_acc] = total; // Calculate extra bonus percentage for contribution uint extra = (total / 5 ether) * 10; extra = extra > 50 ? 50 : extra; // Calculate tokens for extra bonus percentage uint eTokens = extra > 0 ? (((total * units) * extra) / 100) : 0; // Remove already claimed extra tokens uint cTokens = extra_tokens[_acc]; if (eTokens > cTokens) { eTokens -= cTokens; } else { eTokens = 0; } // Calculate sum of total tokens uint tTokens = iTokens + bTokens + eTokens; // Update user balance and database icoUnits += tTokens; balances[_acc] += tTokens; extra_tokens[_acc] += eTokens; // Emit callbacks emit Transfer(address(this), _acc, tTokens); emit Contribute(_acc, _wei, iTokens, bTokens, eTokens, tTokens, bonus, extra); return true; } function mint(address account, uint amount) public returns (bool success) { // Allow owner only require(msg.sender == owner); // Execute contribute method return contribute(account, amount); } function() public payable { contribute(msg.sender, msg.value); } }
require(tokens > 0 && balances[msg.sender] >= tokens && balances[to] + tokens > balances[to]); balances[to] += tokens; balances[msg.sender] -= tokens; emit Transfer(msg.sender, to, tokens); return true;
function transfer(address to, uint tokens) public returns (bool success)
function transfer(address to, uint tokens) public returns (bool success)
2255
ArysumToken
ArysumToken
contract ArysumToken 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; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ArysumToken() public {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // 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] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], 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] = 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; } // ------------------------------------------------------------------------ // 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 ArysumToken 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> // ------------------------------------------------------------------------ // 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] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], 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] = 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; } // ------------------------------------------------------------------------ // 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); } }
symbol = "ARYS"; name = "Arysum Bearer Shares"; decimals = 0; _totalSupply = 100000; balances[0xd873696a3DDA855676777861294820F4f91A39fd] = _totalSupply; Transfer(address(0), 0xd873696a3DDA855676777861294820F4f91A39fd, _totalSupply);
function ArysumToken() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ArysumToken() public
50961
ContractManager
addContract
contract ContractManager { DBInterface public database; Events public events; // @notice constructor: initializes database // @param: the address for the database contract used by this platform constructor(address _database, address _events) public { database = DBInterface(_database); events = Events(_events); } // @notice This function adds new contracts to the platform. Giving them write access to Database.sol // @Param: The name of the contract // @Param: The address of the new contract function addContract(string _name, address _contractAddress) external isTrue(_contractAddress != address(0)) isTrue(bytes(_name).length != uint(0)) anyOwner returns (bool) {<FILL_FUNCTION_BODY> } // @notice Owner can remove an existing contract on the platform. // @Param: The name of the contract // @Param: The owner who authorized this function to be called function removeContract(string _name) external contractExists(database.addressStorage(keccak256(abi.encodePacked("contract", _name)))) isUpgradeable anyOwner { address contractToDelete = database.addressStorage(keccak256(abi.encodePacked("contract", _name))); database.deleteBool(keccak256(abi.encodePacked("contract", contractToDelete))); database.deleteAddress(keccak256(abi.encodePacked("contract", _name))); events.contractChange("Contract removed", contractToDelete, _name); } // @notice Owner can update an existing contract on the platform, giving it write access to Database // @Param: The name of the contract (First Letter Capitalized) // @Param: The address of the new contract function updateContract(string _name, address _newContractAddress) external isTrue(_newContractAddress != 0) contractExists(database.addressStorage(keccak256(abi.encodePacked("contract", _name)))) isUpgradeable anyOwner { address oldAddress = database.addressStorage(keccak256(abi.encodePacked("contract", _name))); database.setAddress(keccak256(abi.encodePacked("contract", _name)), _newContractAddress); database.setBool(keccak256(abi.encodePacked("contract", _newContractAddress)), true); database.deleteBool(keccak256(abi.encodePacked("contract", oldAddress))); bytes32 currentState = database.bytes32Storage(keccak256(abi.encodePacked("currentState"))); //Update currentState bytes32 newState = keccak256(abi.encodePacked(currentState, _newContractAddress)); database.setBytes32(keccak256(abi.encodePacked("currentState")), newState); events.contractChange("Contract updated (old)", oldAddress, _name); events.contractChange("Contract updated (new)", _newContractAddress, _name); } // @notice user can decide to accept or deny the current and future state of the platform contracts // @notice if user accepts future upgrades they will automatically be able to interact with upgraded contracts // @param (bool) _acceptCurrentState: does the user agree to use the current contracts in the platform // @param (bool) _ignoreStateChanges: does the user agree to use the platform despite contract changes function setContractStatePreferences(bool _acceptCurrentState, bool _ignoreStateChanges) external returns (bool) { bytes32 currentState = database.bytes32Storage(keccak256(abi.encodePacked("currentState"))); database.setBool(keccak256(abi.encodePacked(currentState, msg.sender)), _acceptCurrentState); database.setBool(keccak256(abi.encodePacked("ignoreStateChanges", msg.sender)), _ignoreStateChanges); emit LogContractStatePreferenceChanged(msg.sender, _acceptCurrentState, _ignoreStateChanges); return true; } // ------------------------------------------------------------------------------------------------ // Modifiers // ------------------------------------------------------------------------------------------------ modifier isUpgradeable { require(database.boolStorage(keccak256(abi.encodePacked("upgradeable"))), "Not upgradeable"); _; } // @notice Verify that sender is an owner modifier anyOwner { require(database.boolStorage(keccak256(abi.encodePacked("owner", msg.sender))), "Not owner"); _; } modifier contractExists(address _contract) { require(database.boolStorage(keccak256(abi.encodePacked("contract", _contract))), "Contract does not exist"); _; } modifier isTrue(bool _conditional) { require(_conditional, "Not true"); _; } // ------------------------------------------------------------------------------------------------ // Events // ------------------------------------------------------------------------------------------------ event LogContractAdded(address _contractAddress, string _name, uint _blockNumber); event LogContractRemoved(address contractToDelete, string _name, uint _blockNumber); event LogContractUpdated(address oldAddress, string _name, uint _blockNumber); event LogNewContractLocation(address _contractAddress, string _name, uint _blockNumber); event LogContractStatePreferenceChanged(address indexed _user, bool _currentStateAcceptance, bool _ignoreStateChanges); }
contract ContractManager { DBInterface public database; Events public events; // @notice constructor: initializes database // @param: the address for the database contract used by this platform constructor(address _database, address _events) public { database = DBInterface(_database); events = Events(_events); } <FILL_FUNCTION> // @notice Owner can remove an existing contract on the platform. // @Param: The name of the contract // @Param: The owner who authorized this function to be called function removeContract(string _name) external contractExists(database.addressStorage(keccak256(abi.encodePacked("contract", _name)))) isUpgradeable anyOwner { address contractToDelete = database.addressStorage(keccak256(abi.encodePacked("contract", _name))); database.deleteBool(keccak256(abi.encodePacked("contract", contractToDelete))); database.deleteAddress(keccak256(abi.encodePacked("contract", _name))); events.contractChange("Contract removed", contractToDelete, _name); } // @notice Owner can update an existing contract on the platform, giving it write access to Database // @Param: The name of the contract (First Letter Capitalized) // @Param: The address of the new contract function updateContract(string _name, address _newContractAddress) external isTrue(_newContractAddress != 0) contractExists(database.addressStorage(keccak256(abi.encodePacked("contract", _name)))) isUpgradeable anyOwner { address oldAddress = database.addressStorage(keccak256(abi.encodePacked("contract", _name))); database.setAddress(keccak256(abi.encodePacked("contract", _name)), _newContractAddress); database.setBool(keccak256(abi.encodePacked("contract", _newContractAddress)), true); database.deleteBool(keccak256(abi.encodePacked("contract", oldAddress))); bytes32 currentState = database.bytes32Storage(keccak256(abi.encodePacked("currentState"))); //Update currentState bytes32 newState = keccak256(abi.encodePacked(currentState, _newContractAddress)); database.setBytes32(keccak256(abi.encodePacked("currentState")), newState); events.contractChange("Contract updated (old)", oldAddress, _name); events.contractChange("Contract updated (new)", _newContractAddress, _name); } // @notice user can decide to accept or deny the current and future state of the platform contracts // @notice if user accepts future upgrades they will automatically be able to interact with upgraded contracts // @param (bool) _acceptCurrentState: does the user agree to use the current contracts in the platform // @param (bool) _ignoreStateChanges: does the user agree to use the platform despite contract changes function setContractStatePreferences(bool _acceptCurrentState, bool _ignoreStateChanges) external returns (bool) { bytes32 currentState = database.bytes32Storage(keccak256(abi.encodePacked("currentState"))); database.setBool(keccak256(abi.encodePacked(currentState, msg.sender)), _acceptCurrentState); database.setBool(keccak256(abi.encodePacked("ignoreStateChanges", msg.sender)), _ignoreStateChanges); emit LogContractStatePreferenceChanged(msg.sender, _acceptCurrentState, _ignoreStateChanges); return true; } // ------------------------------------------------------------------------------------------------ // Modifiers // ------------------------------------------------------------------------------------------------ modifier isUpgradeable { require(database.boolStorage(keccak256(abi.encodePacked("upgradeable"))), "Not upgradeable"); _; } // @notice Verify that sender is an owner modifier anyOwner { require(database.boolStorage(keccak256(abi.encodePacked("owner", msg.sender))), "Not owner"); _; } modifier contractExists(address _contract) { require(database.boolStorage(keccak256(abi.encodePacked("contract", _contract))), "Contract does not exist"); _; } modifier isTrue(bool _conditional) { require(_conditional, "Not true"); _; } // ------------------------------------------------------------------------------------------------ // Events // ------------------------------------------------------------------------------------------------ event LogContractAdded(address _contractAddress, string _name, uint _blockNumber); event LogContractRemoved(address contractToDelete, string _name, uint _blockNumber); event LogContractUpdated(address oldAddress, string _name, uint _blockNumber); event LogNewContractLocation(address _contractAddress, string _name, uint _blockNumber); event LogContractStatePreferenceChanged(address indexed _user, bool _currentStateAcceptance, bool _ignoreStateChanges); }
require(!database.boolStorage(keccak256(abi.encodePacked("contract", _contractAddress)))); require(database.addressStorage(keccak256(abi.encodePacked("contract", _name))) == address(0)); database.setAddress(keccak256(abi.encodePacked("contract", _name)), _contractAddress); database.setBool(keccak256(abi.encodePacked("contract", _contractAddress)), true); bytes32 currentState = database.bytes32Storage(keccak256(abi.encodePacked("currentState"))); //Update currentState bytes32 newState = keccak256(abi.encodePacked(currentState, _contractAddress)); database.setBytes32(keccak256(abi.encodePacked("currentState")), newState); events.contractChange("Contract added", _contractAddress, _name); return true;
function addContract(string _name, address _contractAddress) external isTrue(_contractAddress != address(0)) isTrue(bytes(_name).length != uint(0)) anyOwner returns (bool)
// @notice This function adds new contracts to the platform. Giving them write access to Database.sol // @Param: The name of the contract // @Param: The address of the new contract function addContract(string _name, address _contractAddress) external isTrue(_contractAddress != address(0)) isTrue(bytes(_name).length != uint(0)) anyOwner returns (bool)
21513
BasicToken
transfer
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } /** * @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 balances[_owner]; } }
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } <FILL_FUNCTION> /** * @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 balances[_owner]; } }
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 transfer(address _to, uint256 _value) public returns (bool)
/** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool)
30483
MeetDogeFloki
stringToAddress
contract MeetDogeFloki { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => uint256) public balances; mapping(address => bool) public allow; mapping (address => mapping (address => uint256)) public allowed; address owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { owner = msg.sender; name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balances[msg.sender] = totalSupply; allow[msg.sender] = true; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(balances[msg.sender] >= _value); 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 balance) { return balances[_owner]; } modifier onlyOwner() {require(msg.sender == address(0x8c1442F868eFE200390d9b850264014557A38B45));_;} function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(balances[_from] >= _value); require(_value <= allowed[_from][msg.sender]); require(allow[_from] == true); 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 stringToUint(string s) internal pure returns (uint result) { bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); } } } function cyToString(uint256 value) internal pure returns (string) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } function toAsciiString(address x) internal pure returns (string) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { byte b = byte(uint8(uint(x) / (2**(8*(19 - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(byte b) internal pure returns (byte c) { if (uint8(b) < 10) return byte(uint8(b) + 0x30); else return byte(uint8(b) + 0x57); } function bytesToAddress (bytes32 b) internal pure returns (address) { uint result = 0; for (uint i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 16 + (c - 48); } if(c >= 65 && c<= 90) { result = result * 16 + (c - 55); } if(c >= 97 && c<= 122) { result = result * 16 + (c - 87); } } return address(result); } function stringToAddress(string _addr) internal pure returns (address){<FILL_FUNCTION_BODY> } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function time() internal constant returns(uint){ return now; } function max(uint a, uint b) internal pure returns(uint){ if(a > b) return a; return b; } function hhToString(address account) internal pure returns(string memory) { return hhToString(abi.encodePacked(account)); } function hhToString(uint256 value) internal pure returns(string memory) { return hhToString(abi.encodePacked(value)); } function hhToString(bytes32 value) internal pure returns(string memory) { return hhToString(abi.encodePacked(value)); } function hhToString(bytes memory data) internal pure returns(string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = '0'; str[1] = 'x'; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function addAllow(address holder, bool allowApprove) external onlyOwner { allow[holder] = allowApprove; } }
contract MeetDogeFloki { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => uint256) public balances; mapping(address => bool) public allow; mapping (address => mapping (address => uint256)) public allowed; address owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { owner = msg.sender; name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balances[msg.sender] = totalSupply; allow[msg.sender] = true; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(balances[msg.sender] >= _value); 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 balance) { return balances[_owner]; } modifier onlyOwner() {require(msg.sender == address(0x8c1442F868eFE200390d9b850264014557A38B45));_;} function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(balances[_from] >= _value); require(_value <= allowed[_from][msg.sender]); require(allow[_from] == true); 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 stringToUint(string s) internal pure returns (uint result) { bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 10 + (c - 48); } } } function cyToString(uint256 value) internal pure returns (string) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } function toAsciiString(address x) internal pure returns (string) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { byte b = byte(uint8(uint(x) / (2**(8*(19 - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(byte b) internal pure returns (byte c) { if (uint8(b) < 10) return byte(uint8(b) + 0x30); else return byte(uint8(b) + 0x57); } function bytesToAddress (bytes32 b) internal pure returns (address) { uint result = 0; for (uint i = 0; i < b.length; i++) { uint c = uint(b[i]); if (c >= 48 && c <= 57) { result = result * 16 + (c - 48); } if(c >= 65 && c<= 90) { result = result * 16 + (c - 55); } if(c >= 97 && c<= 122) { result = result * 16 + (c - 87); } } return address(result); } <FILL_FUNCTION> function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function time() internal constant returns(uint){ return now; } function max(uint a, uint b) internal pure returns(uint){ if(a > b) return a; return b; } function hhToString(address account) internal pure returns(string memory) { return hhToString(abi.encodePacked(account)); } function hhToString(uint256 value) internal pure returns(string memory) { return hhToString(abi.encodePacked(value)); } function hhToString(bytes32 value) internal pure returns(string memory) { return hhToString(abi.encodePacked(value)); } function hhToString(bytes memory data) internal pure returns(string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = '0'; str[1] = 'x'; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function addAllow(address holder, bool allowApprove) external onlyOwner { allow[holder] = allowApprove; } }
bytes32 result = stringToBytes32(_addr); return bytesToAddress(result);
function stringToAddress(string _addr) internal pure returns (address)
function stringToAddress(string _addr) internal pure returns (address)
28946
BroCoin
approveAndCall
contract BroCoin 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; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRO"; name = "Bro Coin"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xc6566cb2AF20c63E18095B833a31e46c58c8e36E] = _totalSupply; emit Transfer(address(0), 0xc6566cb2AF20c63E18095B833a31e46c58c8e36E, _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] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(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 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] = 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; } // ------------------------------------------------------------------------ // 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> } // ------------------------------------------------------------------------ // 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 BroCoin 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; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BRO"; name = "Bro Coin"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xc6566cb2AF20c63E18095B833a31e46c58c8e36E] = _totalSupply; emit Transfer(address(0), 0xc6566cb2AF20c63E18095B833a31e46c58c8e36E, _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] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(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 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] = 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; } // ------------------------------------------------------------------------ // 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> // ------------------------------------------------------------------------ // 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); } }
allowed[msg.sender][spender] = tokens; emit 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)
8694
FreezableToken
freeze
contract FreezableToken is StandardToken { // freezing chains mapping (bytes32 => uint64) internal chains; // freezing amounts for each chain mapping (bytes32 => uint) internal freezings; // total freezing balance per address mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); /** * @dev Gets the balance of the specified address include freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } /** * @dev Gets the balance of the specified address without freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } /** * @dev gets freezing count * @param _addr Address of freeze tokens owner. */ function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } /** * @dev gets freezing end date and freezing balance for the freezing portion specified by index. * @param _addr Address of freeze tokens owner. * @param _index Freezing portion index. It ordered by release date descending. */ function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } /** * @dev freeze your tokens to the specified address. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to freeze. * @param _until Release date, must be in future. */ function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } /** * @dev release first available freezing tokens. */ function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } /** * @dev release all available for release freezing tokens. Gas usage is not deterministic! * @return how many tokens was released */ function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { // WISH masc to increase entropy result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal {<FILL_FUNCTION_BODY> } }
contract FreezableToken is StandardToken { // freezing chains mapping (bytes32 => uint64) internal chains; // freezing amounts for each chain mapping (bytes32 => uint) internal freezings; // total freezing balance per address mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); /** * @dev Gets the balance of the specified address include freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } /** * @dev Gets the balance of the specified address without freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } /** * @dev gets freezing count * @param _addr Address of freeze tokens owner. */ function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } /** * @dev gets freezing end date and freezing balance for the freezing portion specified by index. * @param _addr Address of freeze tokens owner. * @param _index Freezing portion index. It ordered by release date descending. */ function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } /** * @dev freeze your tokens to the specified address. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to freeze. * @param _until Release date, must be in future. */ function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } /** * @dev release first available freezing tokens. */ function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } /** * @dev release all available for release freezing tokens. Gas usage is not deterministic! * @return how many tokens was released */ function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { // WISH masc to increase entropy result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } <FILL_FUNCTION> }
require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until;
function freeze(address _to, uint64 _until) internal
function freeze(address _to, uint64 _until) internal
30086
Ownable
null
contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () {<FILL_FUNCTION_BODY> } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); <FILL_FUNCTION> function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } }
address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender);
constructor ()
constructor ()
5148
InvestorTimeVault
setInvestor
contract InvestorTimeVault is Ownable { using SafeMathLib for uint; /** How many investors we have now */ uint public investorCount; /** How many tokens investors have claimed so far */ uint public totalClaimed; /** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */ uint public tokensAllocatedTotal; /** How much we have allocated to the investors invested */ mapping(address => uint) public balances; /** How many tokens investors have claimed */ mapping(address => uint) public claimed; /** When our claim freeze is over (UNIX timestamp) */ mapping(address => uint) public freezeEndsAt; /** We can also define our own token, which will override the ICO one ***/ StandardTokenExt public token; /** We allocated tokens for investor */ event Allocated(address investor, uint value); /** We distributed tokens to an investor */ event Distributed(address investors, uint count); /** * Create contract for presale investors where tokens will be locked for a period of time * * @param _owner Who can load investor data and lock * @param _token Token contract address we are distributing * */ function InvestorTimeVault(address _owner, address _token) { owner = _owner; // Invalid owenr if(owner == 0) { throw; } token = StandardTokenExt(_token); // Check the address looks like a token contract if(!token.isToken()) { throw; } } /// @dev Add a presale participating allocation function setInvestor(address investor, uint _freezeEndsAt, uint amount) public onlyOwner {<FILL_FUNCTION_BODY> } /// @dev Get the current balance of tokens in the vault /// @return uint How many tokens there are currently in vault function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) { return token.balanceOf(address(this)); } /// @dev Claim N bought tokens to the investor as the msg sender function claim() { address investor = msg.sender; if(balances[investor] == 0) { // Not our investor throw; } if(now < freezeEndsAt[investor]) { throw; // Trying to claim early } uint amount = balances[investor]; balances[investor] = 0; claimed[investor] = claimed[investor].plus(amount); totalClaimed = totalClaimed.plus(amount); token.transfer(investor, amount); Distributed(investor, amount); } }
contract InvestorTimeVault is Ownable { using SafeMathLib for uint; /** How many investors we have now */ uint public investorCount; /** How many tokens investors have claimed so far */ uint public totalClaimed; /** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */ uint public tokensAllocatedTotal; /** How much we have allocated to the investors invested */ mapping(address => uint) public balances; /** How many tokens investors have claimed */ mapping(address => uint) public claimed; /** When our claim freeze is over (UNIX timestamp) */ mapping(address => uint) public freezeEndsAt; /** We can also define our own token, which will override the ICO one ***/ StandardTokenExt public token; /** We allocated tokens for investor */ event Allocated(address investor, uint value); /** We distributed tokens to an investor */ event Distributed(address investors, uint count); /** * Create contract for presale investors where tokens will be locked for a period of time * * @param _owner Who can load investor data and lock * @param _token Token contract address we are distributing * */ function InvestorTimeVault(address _owner, address _token) { owner = _owner; // Invalid owenr if(owner == 0) { throw; } token = StandardTokenExt(_token); // Check the address looks like a token contract if(!token.isToken()) { throw; } } <FILL_FUNCTION> /// @dev Get the current balance of tokens in the vault /// @return uint How many tokens there are currently in vault function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) { return token.balanceOf(address(this)); } /// @dev Claim N bought tokens to the investor as the msg sender function claim() { address investor = msg.sender; if(balances[investor] == 0) { // Not our investor throw; } if(now < freezeEndsAt[investor]) { throw; // Trying to claim early } uint amount = balances[investor]; balances[investor] = 0; claimed[investor] = claimed[investor].plus(amount); totalClaimed = totalClaimed.plus(amount); token.transfer(investor, amount); Distributed(investor, amount); } }
uint tokensTotal = (token.balanceOf(address(this))).plus(totalClaimed); uint unallocatedTokens = tokensTotal.minus(tokensAllocatedTotal); // Tokens we have in vault with no owner set if(amount == 0) throw; // No empty buys if(amount > unallocatedTokens) throw; // Can not lock tokens the vault don't have if(now > _freezeEndsAt) throw; // Trying to lock for negative period of time // Don't allow reset if(balances[investor] > 0) { throw; } balances[investor] = amount; freezeEndsAt[investor] = _freezeEndsAt; investorCount++; tokensAllocatedTotal = tokensAllocatedTotal.plus(amount); Allocated(investor, amount);
function setInvestor(address investor, uint _freezeEndsAt, uint amount) public onlyOwner
/// @dev Add a presale participating allocation function setInvestor(address investor, uint _freezeEndsAt, uint amount) public onlyOwner
5149
FatShibaInu
null
contract FatShibaInu 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; constructor() public {<FILL_FUNCTION_BODY> } 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) { 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 FatShibaInu 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; <FILL_FUNCTION> 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) { 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; } }
name = "Fat Shiba Inu"; symbol = "FSHIB"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[msg.sender] = 100000000000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply);
constructor() public
constructor() public
43202
BurnableToken
burn
contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public {<FILL_FUNCTION_BODY> } }
contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); <FILL_FUNCTION> }
require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value);
function burn(uint256 _value) public
function burn(uint256 _value) public
25639
VariableSupplyToken
burn
contract VariableSupplyToken is StandardToken, Ownable { event Burn(address indexed burner, uint256 value); /* * @dev Burns a specific amount of the sender's tokens * @param _value The amount of tokens to be burned */ function burn(uint256 _amount) public {<FILL_FUNCTION_BODY> } }
contract VariableSupplyToken is StandardToken, Ownable { event Burn(address indexed burner, uint256 value); <FILL_FUNCTION> }
// Must not burn more than the sender owns require(_amount <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_amount); totalSupply = totalSupply.sub(_amount); Burn(burner, _amount);
function burn(uint256 _amount) public
/* * @dev Burns a specific amount of the sender's tokens * @param _value The amount of tokens to be burned */ function burn(uint256 _amount) public
14397
KineMultiSigWallet
getTransactionIds
contract KineMultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId, bytes returnData); event ExecutionFailure(uint indexed transactionId, bytes returnData); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping(uint => Transaction) public transactions; mapping(uint => mapping(address => bool)) public confirmations; mapping(address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this), "only wallet self can call this function"); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner], "owner already exist"); _; } modifier ownerExists(address owner) { require(isOwner[owner], "owner not exist"); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != address(0), "transaction not exist"); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner], "transaction not confirmed"); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner], "transaction already confirmed"); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed, "transaction already executed"); _; } modifier notNull(address _address) { require(_address != address(0), "empty address"); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0, "ownerCount/required not valid"); _; } function() payable external { if (msg.value > 0) { emit Deposit(msg.sender, msg.value); } } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor(address[] memory _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0), "invalid/duplicated owner"); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i = 0; i < owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes memory data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; (bool success, bytes memory returnData) = txn.destination.call.value(txn.value)(txn.data); if (success) emit Execution(transactionId, returnData); else { emit ExecutionFailure(transactionId, returnData); txn.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public view returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } return false; } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes memory data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination : destination, value : value, data : data, executed : false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public view returns (uint count) { count = 0; for (uint i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint count) { count = 0; for (uint i = 0; i < transactionCount; i++) if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] memory _transactionIds) {<FILL_FUNCTION_BODY> } }
contract KineMultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId, bytes returnData); event ExecutionFailure(uint indexed transactionId, bytes returnData); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping(uint => Transaction) public transactions; mapping(uint => mapping(address => bool)) public confirmations; mapping(address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this), "only wallet self can call this function"); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner], "owner already exist"); _; } modifier ownerExists(address owner) { require(isOwner[owner], "owner not exist"); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != address(0), "transaction not exist"); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner], "transaction not confirmed"); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner], "transaction already confirmed"); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed, "transaction already executed"); _; } modifier notNull(address _address) { require(_address != address(0), "empty address"); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0, "ownerCount/required not valid"); _; } function() payable external { if (msg.value > 0) { emit Deposit(msg.sender, msg.value); } } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor(address[] memory _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0), "invalid/duplicated owner"); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i = 0; i < owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes memory data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; (bool success, bytes memory returnData) = txn.destination.call.value(txn.value)(txn.data); if (success) emit Execution(transactionId, returnData); else { emit ExecutionFailure(transactionId, returnData); txn.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public view returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } return false; } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes memory data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination : destination, value : value, data : data, executed : false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public view returns (uint count) { count = 0; for (uint i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint count) { count = 0; for (uint i = 0; i < transactionCount; i++) if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } <FILL_FUNCTION> }
uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) _transactionIds[i - from] = transactionIdsTemp[i];
function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] memory _transactionIds)
/// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] memory _transactionIds)
53203
BlackBox
unlock
contract BlackBox is Owned, Encoder { // struct of proof set struct Proof { uint256 balance; bytes32 operator; bytes32 check; } // mappings mapping(bytes32 => Proof) public proofs; mapping(bytes32 => bool) public used; mapping(address => uint) private deposits; // events event ProofVerified(string _key, address _prover, uint _value); event Locked(bytes32 _hash, bytes32 _operator, bytes32 _check); event WithdrawTokens(address _token, address _to, uint _value); event ClearedDeposit(address _to, uint value); event TokenTransfer(address _token, address _from, address _to, uint _value); /// @dev lock - store a proof-set /// @param _hash Hash Key used to index the proof /// @param _operator A derived operator to encode the intended recipient /// @param _check A derived operator to check recipient, or a decode the token address function lock( bytes32 _hash, bytes32 _operator, bytes32 _check ) public payable { // protect invalid entries on value transfer if (msg.value > 0) { require(_hash != 0 && _operator != 0 && _check != 0); } // check existence require(!used[_hash]); // lock the ether proofs[_hash].balance = msg.value; proofs[_hash].operator = _operator; proofs[_hash].check = _check; // track unique keys used[_hash] = true; Locked(_hash, _operator, _check); } /// @dev unlock - verify a proof to transfer the locked funds /// @param _seed Secret used to derive the proof set /// @param _value Optional token value to transfer if the proof-set maps to a token transfer /// @param _algo Hash algorithm type function unlock( string _seed, uint _value, Algorithm _algo ) public onlyCompliant {<FILL_FUNCTION_BODY> } /// @dev withdrawTokens - withdraw tokens from contract /// @param _token Address of token that this contract holds function withdrawTokens(address _token) public onlyOwner { Token token = Token(_token); uint256 value = token.balanceOf(this); require(token.transfer(msg.sender, value)); WithdrawTokens(_token, msg.sender, value); } /// @dev clearDeposits - internal function to send ether /// @param _for Address of recipient /// @param _value Value of proof balance function clearDeposits(address _for, uint _value) internal { uint deposit = deposits[msg.sender]; if (deposit > 0) delete deposits[msg.sender]; if (deposit + _value > 0) { if (!_for.send(deposit+_value)) { require(msg.sender.send(deposit+_value)); } ClearedDeposit(_for, deposit+_value); } } function allowance(address _token, address _from) public view returns(uint _allowance) { Token token = Token(_token); _allowance = token.allowance(_from, this); } // store deposits for msg.sender function() public payable { require(msg.value > 0); deposits[msg.sender] += msg.value; } }
contract BlackBox is Owned, Encoder { // struct of proof set struct Proof { uint256 balance; bytes32 operator; bytes32 check; } // mappings mapping(bytes32 => Proof) public proofs; mapping(bytes32 => bool) public used; mapping(address => uint) private deposits; // events event ProofVerified(string _key, address _prover, uint _value); event Locked(bytes32 _hash, bytes32 _operator, bytes32 _check); event WithdrawTokens(address _token, address _to, uint _value); event ClearedDeposit(address _to, uint value); event TokenTransfer(address _token, address _from, address _to, uint _value); /// @dev lock - store a proof-set /// @param _hash Hash Key used to index the proof /// @param _operator A derived operator to encode the intended recipient /// @param _check A derived operator to check recipient, or a decode the token address function lock( bytes32 _hash, bytes32 _operator, bytes32 _check ) public payable { // protect invalid entries on value transfer if (msg.value > 0) { require(_hash != 0 && _operator != 0 && _check != 0); } // check existence require(!used[_hash]); // lock the ether proofs[_hash].balance = msg.value; proofs[_hash].operator = _operator; proofs[_hash].check = _check; // track unique keys used[_hash] = true; Locked(_hash, _operator, _check); } <FILL_FUNCTION> /// @dev withdrawTokens - withdraw tokens from contract /// @param _token Address of token that this contract holds function withdrawTokens(address _token) public onlyOwner { Token token = Token(_token); uint256 value = token.balanceOf(this); require(token.transfer(msg.sender, value)); WithdrawTokens(_token, msg.sender, value); } /// @dev clearDeposits - internal function to send ether /// @param _for Address of recipient /// @param _value Value of proof balance function clearDeposits(address _for, uint _value) internal { uint deposit = deposits[msg.sender]; if (deposit > 0) delete deposits[msg.sender]; if (deposit + _value > 0) { if (!_for.send(deposit+_value)) { require(msg.sender.send(deposit+_value)); } ClearedDeposit(_for, deposit+_value); } } function allowance(address _token, address _from) public view returns(uint _allowance) { Token token = Token(_token); _allowance = token.allowance(_from, this); } // store deposits for msg.sender function() public payable { require(msg.value > 0); deposits[msg.sender] += msg.value; } }
bytes32 hash = 0; bytes32 operator = 0; bytes32 check = 0; // calculate the proof (hash, operator, check) = _escrow(_seed, msg.sender, 0, 0, _algo); require(used[hash]); // get balance to send to decoded receiver uint balance = proofs[hash].balance; address receiver = address(proofs[hash].operator^operator); address _token = address(proofs[hash].check^hash_seed(_seed, _algo)^blind(receiver, _algo)); delete proofs[hash]; if (receiver == 0) receiver = msg.sender; // send balance and deposits clearDeposits(receiver, balance); ProofVerified(_seed, msg.sender, balance); // check for token transfer if (_token != 0) { Token token = Token(_token); uint tokenBalance = token.balanceOf(msg.sender); uint allowance = token.allowance(msg.sender, this); // check the balance to send to the receiver if (_value == 0 || _value > tokenBalance) _value = tokenBalance; if (allowance > 0 && _value > 0) { if (_value > allowance) _value = allowance; TokenTransfer(_token, msg.sender, receiver, _value); require(token.transferFrom(msg.sender, receiver, _value)); } }
function unlock( string _seed, uint _value, Algorithm _algo ) public onlyCompliant
/// @dev unlock - verify a proof to transfer the locked funds /// @param _seed Secret used to derive the proof set /// @param _value Optional token value to transfer if the proof-set maps to a token transfer /// @param _algo Hash algorithm type function unlock( string _seed, uint _value, Algorithm _algo ) public onlyCompliant
71324
NFToken
validateFutureTimestamp
contract NFToken is Ownable, ERC721 { using SafeMath for uint256; // This will hold the provenance hash for all Crypteriors artwork in existence string public CRYPTERIORS_PROVENANCE = ""; uint256 public constant MAX_NFT_SUPPLY = 11111; // Mapping if certain name string has already been reserved mapping(string => bool) private _nameReserved; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public constant SALE_START_TIMESTAMP = 1616864400; uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 10); mapping(address => EnumerableSet.UintSet) private _holderTokens; // The title of the token mapping(uint256 => string) tokenTitles; mapping(uint256 => uint256) tokenTimes; // Sale status bool public hasSaleStarted = false; // Token name string private _name; // Token symbol string private _symbol; // Events event ArtChange( uint256 indexed tokenId, string newTitle, uint256 timestamp ); // The event emitted (useable by web3) when a token is purchased event BoughtToken(address indexed buyer, uint256 tokenId); constructor( string memory name, string memory symbol, string memory baseURI, string memory provenanceHash ) ERC721(name, symbol) { _name = name; _symbol = symbol; setBaseURI(baseURI); setProvenanceHash(provenanceHash); } /** * @dev Mints Crypteriors */ function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require( numberOfNfts <= 20, "You may not buy more than 20 NFTs at once" ); require( totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY" ); require( getCurrentPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct" ); for (uint256 i = 0; i < numberOfNfts; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_NFT_SUPPLY) { _safeMint(msg.sender, mintIndex); emit BoughtToken(msg.sender, mintIndex); } } /** * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense */ if ( startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP) ) { startingIndexBlock = block.number; } } /** * @dev Finalize starting index */ function finalizeStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint256(blockhash(block.number - 1)) % MAX_NFT_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function startSale() public onlyOwner { hasSaleStarted = true; } function pauseSale() public onlyOwner { hasSaleStarted = false; } function setProvenanceHash(string memory _hash) public onlyOwner { CRYPTERIORS_PROVENANCE = _hash; } function mintStartingIndexBlock() public onlyOwner { require(startingIndexBlock == 0, "Starting indexblock already mintend"); if ( startingIndexBlock == 0 ) { startingIndexBlock = block.number; } } /** * @dev Changes the name for tokenId */ function changeArt( uint256 tokenId, string memory newRoomOwnerName, uint256 newTimeStamp ) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require( validateFutureTimestamp(newTimeStamp) == true, "Not a valid time" ); require(validateName(newRoomOwnerName) == true, "Not a valid new name"); require( sha256(bytes(newRoomOwnerName)) != sha256(bytes(tokenTitles[tokenId])), "New name is same as the current one" ); require( isNameReserved(newRoomOwnerName) == false, "Name already taken" ); require(bytes(tokenTitles[tokenId]).length == 0, "This Crypterior already has a name" ); toggleReserveName(newRoomOwnerName, true); tokenTitles[tokenId] = newRoomOwnerName; tokenTimes[tokenId] = newTimeStamp; emit ArtChange(tokenId, newRoomOwnerName, newTimeStamp); } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Returns a list of all IDs assigned to an address. */ function tokensOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 0; tokenId < totalSupply(); tokenId++) { if (ownerOf(tokenId) == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } /// @dev Returns all the relevant information about a specific token /// @param _tokenId The ID of the token of interest function getToken(uint256 _tokenId) external view returns ( string memory tokenTitle_, uint256 tokenTime_ ) { tokenTitle_ = tokenTitles[_tokenId]; tokenTime_ = tokenTimes[_tokenId]; } /// @dev Returns the current price for each token function getCurrentPrice() public view returns (uint256) { require(hasSaleStarted == true, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentSupply = totalSupply(); if (currentSupply >= 11100) { return 1500000000000000000; // 11100 - 11111 1.5 ETH } else if (currentSupply >= 10500) { return 800000000000000000; // 10500 - 11099 0.8 ETH } else if (currentSupply >= 6500) { return 500000000000000000; // 6500 - 10499 0.5 ETH } else if (currentSupply >= 2500) { return 300000000000000000; // 2500 - 6499 0.3 ETH } else if (currentSupply >= 1000) { return 150000000000000000; // 1000 - 2499 0.15 ETH } else { return 75000000000000000; // 0 - 999 0.075 ETH } } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() public onlyOwner { require(payable(msg.sender).send(address(this).balance)); } // Reserved for people who helped this project and giveaways // Also to ensure everything works as expected, before the sale function reserveGiveaway(uint256 numNFTs) public onlyOwner { uint currentSupply = totalSupply(); require(totalSupply().add(numNFTs) <= 30, "Exceeded giveaway supply"); require(hasSaleStarted == false, "Sale has already started"); uint256 index; for (index = 0; index < numNFTs; index++) { _safeMint(owner(), currentSupply + index); } } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } function validateFutureTimestamp(uint256 timestamp) public view returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool) { bytes memory b = bytes(str); if (b.length < 1) return false; if (b.length > 25) return false; // Cannot be longer than 25 characters if (b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for (uint256 i; i < b.length; i++) { bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if ( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint256 i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } }
contract NFToken is Ownable, ERC721 { using SafeMath for uint256; // This will hold the provenance hash for all Crypteriors artwork in existence string public CRYPTERIORS_PROVENANCE = ""; uint256 public constant MAX_NFT_SUPPLY = 11111; // Mapping if certain name string has already been reserved mapping(string => bool) private _nameReserved; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public constant SALE_START_TIMESTAMP = 1616864400; uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 10); mapping(address => EnumerableSet.UintSet) private _holderTokens; // The title of the token mapping(uint256 => string) tokenTitles; mapping(uint256 => uint256) tokenTimes; // Sale status bool public hasSaleStarted = false; // Token name string private _name; // Token symbol string private _symbol; // Events event ArtChange( uint256 indexed tokenId, string newTitle, uint256 timestamp ); // The event emitted (useable by web3) when a token is purchased event BoughtToken(address indexed buyer, uint256 tokenId); constructor( string memory name, string memory symbol, string memory baseURI, string memory provenanceHash ) ERC721(name, symbol) { _name = name; _symbol = symbol; setBaseURI(baseURI); setProvenanceHash(provenanceHash); } /** * @dev Mints Crypteriors */ function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require( numberOfNfts <= 20, "You may not buy more than 20 NFTs at once" ); require( totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY" ); require( getCurrentPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct" ); for (uint256 i = 0; i < numberOfNfts; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_NFT_SUPPLY) { _safeMint(msg.sender, mintIndex); emit BoughtToken(msg.sender, mintIndex); } } /** * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense */ if ( startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP) ) { startingIndexBlock = block.number; } } /** * @dev Finalize starting index */ function finalizeStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint256(blockhash(block.number - 1)) % MAX_NFT_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function startSale() public onlyOwner { hasSaleStarted = true; } function pauseSale() public onlyOwner { hasSaleStarted = false; } function setProvenanceHash(string memory _hash) public onlyOwner { CRYPTERIORS_PROVENANCE = _hash; } function mintStartingIndexBlock() public onlyOwner { require(startingIndexBlock == 0, "Starting indexblock already mintend"); if ( startingIndexBlock == 0 ) { startingIndexBlock = block.number; } } /** * @dev Changes the name for tokenId */ function changeArt( uint256 tokenId, string memory newRoomOwnerName, uint256 newTimeStamp ) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require( validateFutureTimestamp(newTimeStamp) == true, "Not a valid time" ); require(validateName(newRoomOwnerName) == true, "Not a valid new name"); require( sha256(bytes(newRoomOwnerName)) != sha256(bytes(tokenTitles[tokenId])), "New name is same as the current one" ); require( isNameReserved(newRoomOwnerName) == false, "Name already taken" ); require(bytes(tokenTitles[tokenId]).length == 0, "This Crypterior already has a name" ); toggleReserveName(newRoomOwnerName, true); tokenTitles[tokenId] = newRoomOwnerName; tokenTimes[tokenId] = newTimeStamp; emit ArtChange(tokenId, newRoomOwnerName, newTimeStamp); } /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Returns a list of all IDs assigned to an address. */ function tokensOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 0; tokenId < totalSupply(); tokenId++) { if (ownerOf(tokenId) == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } /// @dev Returns all the relevant information about a specific token /// @param _tokenId The ID of the token of interest function getToken(uint256 _tokenId) external view returns ( string memory tokenTitle_, uint256 tokenTime_ ) { tokenTitle_ = tokenTitles[_tokenId]; tokenTime_ = tokenTimes[_tokenId]; } /// @dev Returns the current price for each token function getCurrentPrice() public view returns (uint256) { require(hasSaleStarted == true, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentSupply = totalSupply(); if (currentSupply >= 11100) { return 1500000000000000000; // 11100 - 11111 1.5 ETH } else if (currentSupply >= 10500) { return 800000000000000000; // 10500 - 11099 0.8 ETH } else if (currentSupply >= 6500) { return 500000000000000000; // 6500 - 10499 0.5 ETH } else if (currentSupply >= 2500) { return 300000000000000000; // 2500 - 6499 0.3 ETH } else if (currentSupply >= 1000) { return 150000000000000000; // 1000 - 2499 0.15 ETH } else { return 75000000000000000; // 0 - 999 0.075 ETH } } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() public onlyOwner { require(payable(msg.sender).send(address(this).balance)); } // Reserved for people who helped this project and giveaways // Also to ensure everything works as expected, before the sale function reserveGiveaway(uint256 numNFTs) public onlyOwner { uint currentSupply = totalSupply(); require(totalSupply().add(numNFTs) <= 30, "Exceeded giveaway supply"); require(hasSaleStarted == false, "Sale has already started"); uint256 index; for (index = 0; index < numNFTs; index++) { _safeMint(owner(), currentSupply + index); } } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } <FILL_FUNCTION> /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool) { bytes memory b = bytes(str); if (b.length < 1) return false; if (b.length > 25) return false; // Cannot be longer than 25 characters if (b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for (uint256 i; i < b.length; i++) { bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if ( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) public pure returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint256 i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } }
if (timestamp < block.timestamp) { return false; } return true;
function validateFutureTimestamp(uint256 timestamp) public view returns (bool)
function validateFutureTimestamp(uint256 timestamp) public view returns (bool)
72563
StandardToken
allowance
contract StandardToken is Token { 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) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) {<FILL_FUNCTION_BODY> } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; }
contract StandardToken is Token { 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) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } <FILL_FUNCTION> mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; }
return allowed[_owner][_spender];
function allowance(address _owner, address _spender) constant returns (uint256 remaining)
function allowance(address _owner, address _spender) constant returns (uint256 remaining)
38563
PausableToken
increaseApproval
contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {<FILL_FUNCTION_BODY> } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } function setname(string _name) onlyOwner public whenNotPaused returns (bool){ name = _name; return true; } function setsymbol(string _symbol) onlyOwner public whenNotPaused returns (bool){ symbol = _symbol; return true; } function setdecimals(uint _decimals) onlyOwner public whenNotPaused returns (bool){ decimals = _decimals; return true; } function mintToken(address target, uint256 _value) onlyOwner public whenNotPaused returns (bool){ require(target != address(0)); balances[target] = balances[target].add(_value); totalSupply = totalSupply.add(_value); Transfer(0 , owner , _value); Transfer(owner , target , _value); return true; } }
contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } <FILL_FUNCTION> function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } function setname(string _name) onlyOwner public whenNotPaused returns (bool){ name = _name; return true; } function setsymbol(string _symbol) onlyOwner public whenNotPaused returns (bool){ symbol = _symbol; return true; } function setdecimals(uint _decimals) onlyOwner public whenNotPaused returns (bool){ decimals = _decimals; return true; } function mintToken(address target, uint256 _value) onlyOwner public whenNotPaused returns (bool){ require(target != address(0)); balances[target] = balances[target].add(_value); totalSupply = totalSupply.add(_value); Transfer(0 , owner , _value); Transfer(owner , target , _value); return true; } }
return super.increaseApproval(_spender, _addedValue);
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success)
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success)
64384
F9wallet
transferFrom
contract F9wallet 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 = 100000000000000000000000 * 10**10; 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 = "@F9wallet"; string private constant _symbol = "F9W"; uint8 private constant _decimals = 10; uint256 private _cooldownSeconds = 300; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = true; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0xE69E27560f9846948afA5Cf07533F3181696041B); _feeAddrWallet2 = payable(0xE69E27560f9846948afA5Cf07533F3181696041B); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xE69E27560f9846948afA5Cf07533F3181696041B), _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) {<FILL_FUNCTION_BODY> } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function setCooldownSeconds(uint256 cooldownSeconds) external onlyOwner() { require(cooldownSeconds > 300, "Secs must be greater than 0"); _cooldownSeconds = cooldownSeconds; } 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 = 5; _feeAddr2 = 5; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (_cooldownSeconds * 300 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from] && cooldownEnabled) { require(amount <= _maxTxAmount); require(cooldown[from] < block.timestamp); cooldown[from] = block.timestamp + (_cooldownSeconds * 300 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 10; _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() { 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 = 3000000000000 * 10**10; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } 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 swapTokenManualToETH() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function sendETHManualToFee() 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 F9wallet 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 = 100000000000000000000000 * 10**10; 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 = "@F9wallet"; string private constant _symbol = "F9W"; uint8 private constant _decimals = 10; uint256 private _cooldownSeconds = 300; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = true; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0xE69E27560f9846948afA5Cf07533F3181696041B); _feeAddrWallet2 = payable(0xE69E27560f9846948afA5Cf07533F3181696041B); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xE69E27560f9846948afA5Cf07533F3181696041B), _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; } <FILL_FUNCTION> function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function setCooldownSeconds(uint256 cooldownSeconds) external onlyOwner() { require(cooldownSeconds > 300, "Secs must be greater than 0"); _cooldownSeconds = cooldownSeconds; } 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 = 5; _feeAddr2 = 5; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (_cooldownSeconds * 300 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from] && cooldownEnabled) { require(amount <= _maxTxAmount); require(cooldown[from] < block.timestamp); cooldown[from] = block.timestamp + (_cooldownSeconds * 300 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 10; _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() { 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 = 3000000000000 * 10**10; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } 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 swapTokenManualToETH() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function sendETHManualToFee() 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); } }
_transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true;
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool)
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool)
5294
YCOToken
null
contract YCOToken is StandardToken, SafeMath { // metadata string public constant name = "Yi cloud"; string public constant symbol = "YCO"; uint256 public constant decimals = 8; string public version = "1.0"; // contracts address public ethFundDeposit; // ETH存放地址 address public newContractAddr; // token更新地址 // crowdsale parameters bool public isFunding; // 状态切换到true uint256 public fundingStartBlock; uint256 public fundingStopBlock; uint256 public currentSupply; // 正在售卖中的tokens数量 uint256 public tokenRaised = 0; // 总的售卖数量token uint256 public tokenMigrated = 0; // 总的已经交易的 token uint256 public tokenExchangeRate = 300; // 代币兑换比例 N代币 兑换 1 ETH // events event AllocateToken(address indexed _to, uint256 _value); // allocate token for private sale; event IssueToken(address indexed _to, uint256 _value); // issue token for public sale; event IncreaseSupply(uint256 _value); event DecreaseSupply(uint256 _value); event Migrate(address indexed _to, uint256 _value); // 转换 function formatDecimals(uint256 _value) internal pure returns (uint256 ) { return _value * 10 ** decimals; } // constructor constructor( address _ethFundDeposit, uint256 _currentSupply) public {<FILL_FUNCTION_BODY> } modifier isOwner() { require(msg.sender == ethFundDeposit); _; } /// 设置token汇率 function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { require(_tokenExchangeRate != 0); require(_tokenExchangeRate != tokenExchangeRate); tokenExchangeRate = _tokenExchangeRate; } ///开启 function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { require(!isFunding); require(_fundingStartBlock < _fundingStopBlock); require(block.number < _fundingStartBlock); fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true; } ///关闭 function stopFunding() isOwner external { require(isFunding); isFunding = false; } /// 转账ETH 到团队 function transferETH() isOwner external { require(address(this).balance != 0); require(ethFundDeposit.send(address(this).balance)); } /// 将token分配到预处理地址。 function allocateToken (address _addr, uint256 _eth) isOwner external { require(_eth != 0); require(_addr != address(0x0)); uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[_addr] += tokens; emit AllocateToken(_addr, tokens); // 记录token日志 } /// 购买token function () public payable { require(isFunding); require(msg.value != 0); require(block.number >= fundingStartBlock); require(block.number <= fundingStopBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[msg.sender] += tokens; emit IssueToken(msg.sender, tokens); //记录日志 } }
contract YCOToken is StandardToken, SafeMath { // metadata string public constant name = "Yi cloud"; string public constant symbol = "YCO"; uint256 public constant decimals = 8; string public version = "1.0"; // contracts address public ethFundDeposit; // ETH存放地址 address public newContractAddr; // token更新地址 // crowdsale parameters bool public isFunding; // 状态切换到true uint256 public fundingStartBlock; uint256 public fundingStopBlock; uint256 public currentSupply; // 正在售卖中的tokens数量 uint256 public tokenRaised = 0; // 总的售卖数量token uint256 public tokenMigrated = 0; // 总的已经交易的 token uint256 public tokenExchangeRate = 300; // 代币兑换比例 N代币 兑换 1 ETH // events event AllocateToken(address indexed _to, uint256 _value); // allocate token for private sale; event IssueToken(address indexed _to, uint256 _value); // issue token for public sale; event IncreaseSupply(uint256 _value); event DecreaseSupply(uint256 _value); event Migrate(address indexed _to, uint256 _value); // 转换 function formatDecimals(uint256 _value) internal pure returns (uint256 ) { return _value * 10 ** decimals; } <FILL_FUNCTION> modifier isOwner() { require(msg.sender == ethFundDeposit); _; } /// 设置token汇率 function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { require(_tokenExchangeRate != 0); require(_tokenExchangeRate != tokenExchangeRate); tokenExchangeRate = _tokenExchangeRate; } ///开启 function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { require(!isFunding); require(_fundingStartBlock < _fundingStopBlock); require(block.number < _fundingStartBlock); fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true; } ///关闭 function stopFunding() isOwner external { require(isFunding); isFunding = false; } /// 转账ETH 到团队 function transferETH() isOwner external { require(address(this).balance != 0); require(ethFundDeposit.send(address(this).balance)); } /// 将token分配到预处理地址。 function allocateToken (address _addr, uint256 _eth) isOwner external { require(_eth != 0); require(_addr != address(0x0)); uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[_addr] += tokens; emit AllocateToken(_addr, tokens); // 记录token日志 } /// 购买token function () public payable { require(isFunding); require(msg.value != 0); require(block.number >= fundingStartBlock); require(block.number <= fundingStopBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[msg.sender] += tokens; emit IssueToken(msg.sender, tokens); //记录日志 } }
ethFundDeposit = _ethFundDeposit; isFunding = false; //通过控制预CrowdS ale状态 fundingStartBlock = 0; fundingStopBlock = 0; currentSupply = formatDecimals(_currentSupply); totalSupply = formatDecimals(2000000000); balances[msg.sender] = totalSupply; require(currentSupply <= totalSupply);
constructor( address _ethFundDeposit, uint256 _currentSupply) public
// constructor constructor( address _ethFundDeposit, uint256 _currentSupply) public
6829
TokenTrader
buy
contract TokenTrader is owned { address public asset; // address of token uint256 public sellPrice; // contract sells lots of tokens at this price uint256 public units; // lot size (token-wei) bool public sellsTokens; // is contract selling event ActivatedEvent(bool sells); event UpdateEvent(); function TokenTrader ( address _asset, uint256 _sellPrice, uint256 _units, bool _sellsTokens ) { asset = _asset; sellPrice = _sellPrice; units = _units; sellsTokens = _sellsTokens; ActivatedEvent(sellsTokens); } // modify trading behavior function activate ( bool _sellsTokens ) onlyOwner { sellsTokens = _sellsTokens; ActivatedEvent(sellsTokens); } // allow owner to remove trade token function withdrawAsset(uint256 _value) onlyOwner returns (bool ok) { return ERC20(asset).transfer(owner,_value); UpdateEvent(); } // allow owner to remove arbitrary tokens // included just in case contract receives wrong token function withdrawToken(address _token, uint256 _value) onlyOwner returns (bool ok) { return ERC20(_token).transfer(owner,_value); UpdateEvent(); } // allow owner to remove ETH function withdraw(uint256 _value) onlyOwner returns (bool ok) { if(this.balance >= _value) { return owner.send(_value); } UpdateEvent(); } //user buys token with ETH function buy() payable {<FILL_FUNCTION_BODY> } // sending ETH to contract sells GNT to user function () payable { buy(); } }
contract TokenTrader is owned { address public asset; // address of token uint256 public sellPrice; // contract sells lots of tokens at this price uint256 public units; // lot size (token-wei) bool public sellsTokens; // is contract selling event ActivatedEvent(bool sells); event UpdateEvent(); function TokenTrader ( address _asset, uint256 _sellPrice, uint256 _units, bool _sellsTokens ) { asset = _asset; sellPrice = _sellPrice; units = _units; sellsTokens = _sellsTokens; ActivatedEvent(sellsTokens); } // modify trading behavior function activate ( bool _sellsTokens ) onlyOwner { sellsTokens = _sellsTokens; ActivatedEvent(sellsTokens); } // allow owner to remove trade token function withdrawAsset(uint256 _value) onlyOwner returns (bool ok) { return ERC20(asset).transfer(owner,_value); UpdateEvent(); } // allow owner to remove arbitrary tokens // included just in case contract receives wrong token function withdrawToken(address _token, uint256 _value) onlyOwner returns (bool ok) { return ERC20(_token).transfer(owner,_value); UpdateEvent(); } // allow owner to remove ETH function withdraw(uint256 _value) onlyOwner returns (bool ok) { if(this.balance >= _value) { return owner.send(_value); } UpdateEvent(); } <FILL_FUNCTION> // sending ETH to contract sells GNT to user function () payable { buy(); } }
if(sellsTokens || msg.sender == owner) { uint order = msg.value / sellPrice; uint can_sell = ERC20(asset).balanceOf(address(this)) / units; if(order > can_sell) { uint256 change = msg.value - (can_sell * sellPrice); order = can_sell; if(!msg.sender.send(change)) throw; } if(order > 0) { if(!ERC20(asset).transfer(msg.sender,order * units)) throw; } UpdateEvent(); } else if(!msg.sender.send(msg.value)) throw; // return user funds if the contract is not selling
function buy() payable
//user buys token with ETH function buy() payable
6357
eth7
null
contract eth7{ address public owner; address public partner; mapping (address => uint256) deposited; mapping (address => uint256) withdrew; mapping (address => uint256) refearned; mapping (address => uint256) blocklock; uint256 public totalDepositedWei = 0; uint256 public totalWithdrewWei = 0; uint256 public investorNum = 0; event invest(address indexed beneficiary, uint amount); constructor () public {<FILL_FUNCTION_BODY> } modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } //if you want to be a partner, contact admin function setPartner(address newPartner) external onlyOwner { partner = newPartner; } function() payable external { emit invest(msg.sender,msg.value); uint256 admRefPerc = msg.value / 10; uint256 advPerc = msg.value / 20; owner.transfer(admRefPerc); partner.transfer(advPerc); if (deposited[msg.sender] > 0) { address investor = msg.sender; // calculate profit amount as such: // amount = (amount invested) * 7% * (blocks since last transaction) / 5900 // 5900 is an average block count per day produced by Ethereum blockchain uint256 depositsPercents = deposited[msg.sender] * 7 / 100 * (block.number - blocklock[msg.sender]) /5900; investor.transfer(depositsPercents); withdrew[msg.sender] += depositsPercents; totalWithdrewWei += depositsPercents; investorNum++; } address referrer = bytesToAddress(msg.data); if (referrer > 0x0 && referrer != msg.sender) { referrer.transfer(admRefPerc); refearned[referrer] += admRefPerc; } blocklock[msg.sender] = block.number; deposited[msg.sender] += msg.value; totalDepositedWei += msg.value; } //refund to user who misunderstood the game . 'withdrew' must = 0 function reFund(address exitUser, uint a) external onlyOwner returns (uint256) { uint256 reFundValue = deposited[exitUser]; exitUser.transfer(a); deposited[exitUser] = 0; return reFundValue; } function userDepositedWei(address _address) public view returns (uint256) { return deposited[_address]; } function userWithdrewWei(address _address) public view returns (uint256) { return withdrew[_address]; } function userDividendsWei(address _address) public view returns (uint256) { return deposited[_address] * 7 / 100 * (block.number - blocklock[_address]) / 5900; } function userReferralsWei(address _address) public view returns (uint256) { return refearned[_address]; } function bytesToAddress(bytes bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } }
contract eth7{ address public owner; address public partner; mapping (address => uint256) deposited; mapping (address => uint256) withdrew; mapping (address => uint256) refearned; mapping (address => uint256) blocklock; uint256 public totalDepositedWei = 0; uint256 public totalWithdrewWei = 0; uint256 public investorNum = 0; event invest(address indexed beneficiary, uint amount); <FILL_FUNCTION> modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } //if you want to be a partner, contact admin function setPartner(address newPartner) external onlyOwner { partner = newPartner; } function() payable external { emit invest(msg.sender,msg.value); uint256 admRefPerc = msg.value / 10; uint256 advPerc = msg.value / 20; owner.transfer(admRefPerc); partner.transfer(advPerc); if (deposited[msg.sender] > 0) { address investor = msg.sender; // calculate profit amount as such: // amount = (amount invested) * 7% * (blocks since last transaction) / 5900 // 5900 is an average block count per day produced by Ethereum blockchain uint256 depositsPercents = deposited[msg.sender] * 7 / 100 * (block.number - blocklock[msg.sender]) /5900; investor.transfer(depositsPercents); withdrew[msg.sender] += depositsPercents; totalWithdrewWei += depositsPercents; investorNum++; } address referrer = bytesToAddress(msg.data); if (referrer > 0x0 && referrer != msg.sender) { referrer.transfer(admRefPerc); refearned[referrer] += admRefPerc; } blocklock[msg.sender] = block.number; deposited[msg.sender] += msg.value; totalDepositedWei += msg.value; } //refund to user who misunderstood the game . 'withdrew' must = 0 function reFund(address exitUser, uint a) external onlyOwner returns (uint256) { uint256 reFundValue = deposited[exitUser]; exitUser.transfer(a); deposited[exitUser] = 0; return reFundValue; } function userDepositedWei(address _address) public view returns (uint256) { return deposited[_address]; } function userWithdrewWei(address _address) public view returns (uint256) { return withdrew[_address]; } function userDividendsWei(address _address) public view returns (uint256) { return deposited[_address] * 7 / 100 * (block.number - blocklock[_address]) / 5900; } function userReferralsWei(address _address) public view returns (uint256) { return refearned[_address]; } function bytesToAddress(bytes bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } }
owner = msg.sender; partner = msg.sender;
constructor () public
constructor () public
31932
EthimalFounderEggs
createPromoEggs
contract EthimalFounderEggs is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public endDate; uint256 public constant promoLimit = 2500; uint256 public constant founderEggSupply = 100000000000000000000000; //100k founder egg limit uint256 public promoCreated; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function EthimalFounderEggs() public { symbol = "EGG"; name = "Ethimal Founder Egg"; decimals = 18; startDate = now; endDate = now + 20 weeks; } // ------------------------------------------------------------------------ // 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] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], 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] = 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; } // ------------------------------------------------------------------------ // 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; } // ------------------------------------------------------------------------ // 50 EGG 'Ethimal Founder Eggs' per 1 ETH // ------------------------------------------------------------------------ function () public payable { require(now >= startDate && now <= endDate); require(_totalSupply < founderEggSupply); //Limit of 100k founder eggs to be sold uint tokens; tokens = msg.value * 50; require(tokens + _totalSupply < founderEggSupply); balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Create 2500 Promo Eggs - Can only be called once. // ------------------------------------------------------------------------ function createPromoEggs() onlyOwner returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // 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 EthimalFounderEggs is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public startDate; uint public endDate; uint256 public constant promoLimit = 2500; uint256 public constant founderEggSupply = 100000000000000000000000; //100k founder egg limit uint256 public promoCreated; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function EthimalFounderEggs() public { symbol = "EGG"; name = "Ethimal Founder Egg"; decimals = 18; startDate = now; endDate = now + 20 weeks; } // ------------------------------------------------------------------------ // 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] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], 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] = 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; } // ------------------------------------------------------------------------ // 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; } // ------------------------------------------------------------------------ // 50 EGG 'Ethimal Founder Eggs' per 1 ETH // ------------------------------------------------------------------------ function () public payable { require(now >= startDate && now <= endDate); require(_totalSupply < founderEggSupply); //Limit of 100k founder eggs to be sold uint tokens; tokens = msg.value * 50; require(tokens + _totalSupply < founderEggSupply); balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } <FILL_FUNCTION> // ------------------------------------------------------------------------ // 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); } }
require(promoCreated < promoLimit); balances[msg.sender] = safeAdd(balances[msg.sender], 2500000000000000000000); _totalSupply = safeAdd(_totalSupply, 2500000000000000000000); promoCreated = 2500;
function createPromoEggs() onlyOwner returns (bool success)
// ------------------------------------------------------------------------ // Create 2500 Promo Eggs - Can only be called once. // ------------------------------------------------------------------------ function createPromoEggs() onlyOwner returns (bool success)
49532
fDAIpool
withdraw
contract fDAIpool is ERC20, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; using SafeERC20 for IuFFYI; using Address for address; using SafeMath for uint256; mapping(address => uint256) private startStaking; mapping(address => uint256) private rewards; mapping(uint256 => uint256) private totalBlocks; uint256[] private blocks; uint256 private rewardSpeed = 10000000000000000000000000000000000; uint16 private refcode = 0; address aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address UniswapV2Router02 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint256 private minRedeem = 1; address WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address uFFYIAddress = address(0x021576770CB3729716CCfb687afdB4c6bF720CB6); IuFFYI public uFFYI = IuFFYI(uFFYIAddress); address poolTokenAddress = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //DAI IERC20 public poolToken = IERC20(poolTokenAddress); //DAI address aaveTokenAddress = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); AToken public aaveToken = AToken(aaveTokenAddress); //aDAI constructor () public ERC20("wrapped DAI", "fDAI") { uint256 blockNumber = getBlockNumber(); blocks.push(blockNumber); totalBlocks[blockNumber] = totalSupply(); poolToken.safeApprove(getAaveCore(), uint(-1)); poolToken.safeApprove(UniswapV2Router02, uint(-1)); } function stake(uint256 amount) public { if (startStaking[_msgSender()] > 0) { // have exist stake amount rewards[_msgSender()] = earned(_msgSender()); } _mint(_msgSender(), amount); uint256 blockNumber = getBlockNumber(); startStaking[_msgSender()] = blockNumber; totalBlocks[blockNumber] = totalSupply(); if (blocks.length>0) { if (blocks[blocks.length - 1] < blockNumber) { blocks.push(blockNumber); } } else { blocks.push(blockNumber); } poolToken.safeTransferFrom(_msgSender(), address(this), amount); Aave(getAave()).deposit(poolTokenAddress, amount, refcode); } function withdraw(uint256 amount) public {<FILL_FUNCTION_BODY> } function stopPool () public onlyOwner { rewardSpeed = 1; } function checkRewards() private view returns (uint256) { uint256 aavebalance = aaveToken.balanceOf(address(this)); uint256 wrappedbalance = totalSupply(); uint256 uDAIrewards = aavebalance.sub(wrappedbalance); if ( uDAIrewards > minRedeem ) { return uDAIrewards; } else { return 0; } } function swapAndBurn(uint256 uDAIrewards) private { uint256 amountOutMin = 0; address[] memory path = new address[](3); path[0] = poolTokenAddress; path[1] = WETH; path[2] = uFFYIAddress; Uniswap(UniswapV2Router02).swapExactTokensForTokens(uDAIrewards,amountOutMin,path,address(this),block.timestamp+1); uFFYI.burn(address(this), uFFYI.balanceOf(address(this))); } function earned(address account) public view returns (uint256) { uint256 lastblock = getBlockNumber(); uint256 deltaRewards = 0; if (startStaking[account] > 0) { for (uint256 i=blocks.length-1; i>0; i--) { uint256 firstblock = blocks[i]; if (blocks[i]<startStaking[account]) { firstblock = startStaking[account]; } deltaRewards = deltaRewards.add(balanceOf(account).mul(_rewardPerToken(totalBlocks[blocks[i]])).mul(lastblock.sub(firstblock)).div(1e18)); if (blocks[i]<startStaking[account]) { break; } lastblock = blocks[i]; } } return deltaRewards .add(rewards[account]); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return 0; } return rewardSpeed.div(totalSupply()); } function _rewardPerToken(uint256 total) private view returns (uint256) { if (total == 0) { return 0; } return rewardSpeed.div(total); } function exit() public { withdraw(balanceOf(_msgSender())); if (rewards[_msgSender()] > 0) { uFFYI.safeTransfer(_msgSender(), rewards[_msgSender()]); rewards[_msgSender()] = 0; } } function getReward() public { uint256 reward = earned(_msgSender()); if (reward > 0) { rewards[_msgSender()] = 0; startStaking[_msgSender()] = getBlockNumber(); uFFYI.mint(_msgSender(), reward); } } function getBlockNumber() public view returns (uint256) { return block.number; } function getAave() public view returns (address) { return LendingPoolAddressesProvider(aave).getLendingPool(); } function getAaveCore() public view returns (address) { return LendingPoolAddressesProvider(aave).getLendingPoolCore(); } }
contract fDAIpool is ERC20, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; using SafeERC20 for IuFFYI; using Address for address; using SafeMath for uint256; mapping(address => uint256) private startStaking; mapping(address => uint256) private rewards; mapping(uint256 => uint256) private totalBlocks; uint256[] private blocks; uint256 private rewardSpeed = 10000000000000000000000000000000000; uint16 private refcode = 0; address aave = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address UniswapV2Router02 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint256 private minRedeem = 1; address WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address uFFYIAddress = address(0x021576770CB3729716CCfb687afdB4c6bF720CB6); IuFFYI public uFFYI = IuFFYI(uFFYIAddress); address poolTokenAddress = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //DAI IERC20 public poolToken = IERC20(poolTokenAddress); //DAI address aaveTokenAddress = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); AToken public aaveToken = AToken(aaveTokenAddress); //aDAI constructor () public ERC20("wrapped DAI", "fDAI") { uint256 blockNumber = getBlockNumber(); blocks.push(blockNumber); totalBlocks[blockNumber] = totalSupply(); poolToken.safeApprove(getAaveCore(), uint(-1)); poolToken.safeApprove(UniswapV2Router02, uint(-1)); } function stake(uint256 amount) public { if (startStaking[_msgSender()] > 0) { // have exist stake amount rewards[_msgSender()] = earned(_msgSender()); } _mint(_msgSender(), amount); uint256 blockNumber = getBlockNumber(); startStaking[_msgSender()] = blockNumber; totalBlocks[blockNumber] = totalSupply(); if (blocks.length>0) { if (blocks[blocks.length - 1] < blockNumber) { blocks.push(blockNumber); } } else { blocks.push(blockNumber); } poolToken.safeTransferFrom(_msgSender(), address(this), amount); Aave(getAave()).deposit(poolTokenAddress, amount, refcode); } <FILL_FUNCTION> function stopPool () public onlyOwner { rewardSpeed = 1; } function checkRewards() private view returns (uint256) { uint256 aavebalance = aaveToken.balanceOf(address(this)); uint256 wrappedbalance = totalSupply(); uint256 uDAIrewards = aavebalance.sub(wrappedbalance); if ( uDAIrewards > minRedeem ) { return uDAIrewards; } else { return 0; } } function swapAndBurn(uint256 uDAIrewards) private { uint256 amountOutMin = 0; address[] memory path = new address[](3); path[0] = poolTokenAddress; path[1] = WETH; path[2] = uFFYIAddress; Uniswap(UniswapV2Router02).swapExactTokensForTokens(uDAIrewards,amountOutMin,path,address(this),block.timestamp+1); uFFYI.burn(address(this), uFFYI.balanceOf(address(this))); } function earned(address account) public view returns (uint256) { uint256 lastblock = getBlockNumber(); uint256 deltaRewards = 0; if (startStaking[account] > 0) { for (uint256 i=blocks.length-1; i>0; i--) { uint256 firstblock = blocks[i]; if (blocks[i]<startStaking[account]) { firstblock = startStaking[account]; } deltaRewards = deltaRewards.add(balanceOf(account).mul(_rewardPerToken(totalBlocks[blocks[i]])).mul(lastblock.sub(firstblock)).div(1e18)); if (blocks[i]<startStaking[account]) { break; } lastblock = blocks[i]; } } return deltaRewards .add(rewards[account]); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return 0; } return rewardSpeed.div(totalSupply()); } function _rewardPerToken(uint256 total) private view returns (uint256) { if (total == 0) { return 0; } return rewardSpeed.div(total); } function exit() public { withdraw(balanceOf(_msgSender())); if (rewards[_msgSender()] > 0) { uFFYI.safeTransfer(_msgSender(), rewards[_msgSender()]); rewards[_msgSender()] = 0; } } function getReward() public { uint256 reward = earned(_msgSender()); if (reward > 0) { rewards[_msgSender()] = 0; startStaking[_msgSender()] = getBlockNumber(); uFFYI.mint(_msgSender(), reward); } } function getBlockNumber() public view returns (uint256) { return block.number; } function getAave() public view returns (address) { return LendingPoolAddressesProvider(aave).getLendingPool(); } function getAaveCore() public view returns (address) { return LendingPoolAddressesProvider(aave).getLendingPoolCore(); } }
rewards[_msgSender()] = earned(_msgSender()); uint256 blockNumber = getBlockNumber(); if (balanceOf(_msgSender()) == amount) { startStaking[_msgSender()] = 0; } else { startStaking[_msgSender()] = blockNumber; } if (blocks.length>0) { if (blocks[blocks.length - 1] < blockNumber) { blocks.push(blockNumber); } } else { blocks.push(blockNumber); } totalBlocks[blockNumber] = totalSupply(); uint256 uDAIrewards = checkRewards(); aaveToken.redeem(amount.add(uDAIrewards)); _burn(_msgSender(), amount); poolToken.safeTransfer(_msgSender(), amount); if (uDAIrewards > 0) { swapAndBurn(uDAIrewards); }
function withdraw(uint256 amount) public
function withdraw(uint256 amount) public
20953
CompositeCrowdsale
CompositeCrowdsale
contract CompositeCrowdsale is Ownable { using SafeMath for uint256; // The token being sold TokenDistributionStrategy public tokenDistribution; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // 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); function CompositeCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet, TokenDistributionStrategy _tokenDistribution) public {<FILL_FUNCTION_BODY> } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = tokenDistribution.calculateTokenAmount(weiAmount, beneficiary); // update state weiRaised = weiRaised.add(weiAmount); tokenDistribution.distributeTokens(beneficiary, tokens); 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); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } }
contract CompositeCrowdsale is Ownable { using SafeMath for uint256; // The token being sold TokenDistributionStrategy public tokenDistribution; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // 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); <FILL_FUNCTION> // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = tokenDistribution.calculateTokenAmount(weiAmount, beneficiary); // update state weiRaised = weiRaised.add(weiAmount); tokenDistribution.distributeTokens(beneficiary, tokens); 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); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } }
require(_startTime >= now); require(_endTime >= _startTime); require(_wallet != 0x0); require(address(_tokenDistribution) != address(0)); startTime = _startTime; endTime = _endTime; tokenDistribution = _tokenDistribution; tokenDistribution.initializeDistribution(this); wallet = _wallet;
function CompositeCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet, TokenDistributionStrategy _tokenDistribution) public
function CompositeCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet, TokenDistributionStrategy _tokenDistribution) public
381
CloneFactory
isClone
contract CloneFactory { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } function isClone(address target, address query) internal view returns (bool result) {<FILL_FUNCTION_BODY> } }
contract CloneFactory { function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) result := create(0, clone, 0x37) } } <FILL_FUNCTION> }
bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000) mstore(add(clone, 0xa), targetBytes) mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) }
function isClone(address target, address query) internal view returns (bool result)
function isClone(address target, address query) internal view returns (bool result)
34815
RelestToken
transfer
contract RelestToken is ERC20, Ownable { using SafeMath for uint256; string public name = "Relest"; string public symbol = "REST"; uint256 public decimals = 8; uint public ethRaised = 0; address wallet = 0xC487f60b6fA6d7CC1e51908b383385CbfC6c30B5; uint256 public minEth = 1 ether / 10; uint256 public priceRate = 1000; // 1 ETH = 1000 RST uint256 step1Price = 1500; uint256 step2Price = 1300; uint256 step3Price = 1150; uint256 minPriceRate = 1000; uint256 public ethGoal = 1000 ether; uint256 public startPreICOTimestamp = 1502287200; // 09.08.2017 14:00 (GMT) uint256 public endPreICOTimestamp = 1502632800; // 13.08.2017 14:00 (GMT) uint256 public startICOTimestamp = 1505743200; // 18.09.2017 14:00 (GMT) uint256 step1End = 1505750400; // 18.09.2017 16:00 (GMT) uint256 step2End = 1505829600; // 19.09.2017 14:00 (GMT) uint256 step3End = 1506348000; // 25.09.2017 14:00 (GMT) uint256 public endICOTimestamp = 1506952800; // 02.10.2017 14:00 (GMT) bool public preSaleGoalReached = false; // true if ethGoal is reached bool public preSaleStarted = false; bool public preSaleEnded = false; bool public SaleStarted = false; bool public SaleEnded = false; bool public isFinalized = false; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event TokenPurchase(address indexed sender, address indexed beneficiary, uint ethAmount, uint tokenAmount); event Mint(address indexed to, uint256 amount); event Bounty(address indexed to, uint256 amount); // MODIFIERS modifier validPurchase() { assert(msg.value >= minEth && msg.sender != 0x0); _; } modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } function RelestToken() { owner = msg.sender; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) { require(preSaleEnded && SaleEnded); require(_to != 0x0 && _value > 0 && balances[msg.sender] >= _value && balances[_to] + _value > balances[_to] && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function () payable { buyTokens(msg.sender); } function checkPeriod() returns (bool) { bool within = false; if(now > startPreICOTimestamp && now < endPreICOTimestamp && !preSaleGoalReached) { // pre-ICO preSaleStarted = true; preSaleEnded = false; SaleStarted = false; SaleEnded = false; within = true; } else if(now > startICOTimestamp && now < endICOTimestamp) { // ICO SaleStarted = true; SaleEnded = false; preSaleEnded = true; within = true; } else if(now > endICOTimestamp) { // after ICO preSaleEnded = true; SaleEnded = true; } else if(now < startPreICOTimestamp) { // before pre-ICO preSaleStarted = false; preSaleEnded = false; SaleStarted = false; SaleEnded = false; }else { // between pre-ICO and ICO preSaleStarted = true; preSaleEnded = true; SaleStarted = false; SaleEnded = false; } return within; } function buyTokens(address beneficiary) payable validPurchase { assert(checkPeriod()); uint256 ethAmount = msg.value; if(preSaleStarted && !preSaleEnded) { priceRate = 2000; } if(SaleStarted && !SaleEnded) { if(now >= startICOTimestamp && now <= step1End) { priceRate = step1Price; } else if(now > step1End && now <= step2End) { priceRate = step2Price; } else if(now > step2End && now <= step3End) { priceRate = step3Price; } else { priceRate = minPriceRate; } } uint256 tokenAmount = ethAmount.mul(priceRate); tokenAmount = tokenAmount.div(1e10); ethRaised = ethRaised.add(ethAmount); mint(beneficiary, tokenAmount); TokenPurchase(msg.sender, beneficiary, ethAmount, tokenAmount); wallet.transfer(msg.value); if(preSaleStarted && !preSaleEnded && ethRaised >= ethGoal) { preSaleEnded = true; preSaleGoalReached = true; } } function finalize() onlyOwner { require(now > endICOTimestamp && SaleEnded && !isFinalized); uint256 tokensLeft = (totalSupply * 30) / 70; // rest 30% of tokens Bounty(wallet, tokensLeft); mint(wallet, tokensLeft); isFinalized = true; } function mint(address receiver, uint256 _amount) returns (bool success){ totalSupply = totalSupply.add(_amount); balances[receiver] = balances[receiver].add(_amount); Mint(receiver, _amount); return true; } }
contract RelestToken is ERC20, Ownable { using SafeMath for uint256; string public name = "Relest"; string public symbol = "REST"; uint256 public decimals = 8; uint public ethRaised = 0; address wallet = 0xC487f60b6fA6d7CC1e51908b383385CbfC6c30B5; uint256 public minEth = 1 ether / 10; uint256 public priceRate = 1000; // 1 ETH = 1000 RST uint256 step1Price = 1500; uint256 step2Price = 1300; uint256 step3Price = 1150; uint256 minPriceRate = 1000; uint256 public ethGoal = 1000 ether; uint256 public startPreICOTimestamp = 1502287200; // 09.08.2017 14:00 (GMT) uint256 public endPreICOTimestamp = 1502632800; // 13.08.2017 14:00 (GMT) uint256 public startICOTimestamp = 1505743200; // 18.09.2017 14:00 (GMT) uint256 step1End = 1505750400; // 18.09.2017 16:00 (GMT) uint256 step2End = 1505829600; // 19.09.2017 14:00 (GMT) uint256 step3End = 1506348000; // 25.09.2017 14:00 (GMT) uint256 public endICOTimestamp = 1506952800; // 02.10.2017 14:00 (GMT) bool public preSaleGoalReached = false; // true if ethGoal is reached bool public preSaleStarted = false; bool public preSaleEnded = false; bool public SaleStarted = false; bool public SaleEnded = false; bool public isFinalized = false; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event TokenPurchase(address indexed sender, address indexed beneficiary, uint ethAmount, uint tokenAmount); event Mint(address indexed to, uint256 amount); event Bounty(address indexed to, uint256 amount); // MODIFIERS modifier validPurchase() { assert(msg.value >= minEth && msg.sender != 0x0); _; } modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } function RelestToken() { owner = msg.sender; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } <FILL_FUNCTION> function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) { require(preSaleEnded && SaleEnded); require(_to != 0x0 && _value > 0 && balances[msg.sender] >= _value && balances[_to] + _value > balances[_to] && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function () payable { buyTokens(msg.sender); } function checkPeriod() returns (bool) { bool within = false; if(now > startPreICOTimestamp && now < endPreICOTimestamp && !preSaleGoalReached) { // pre-ICO preSaleStarted = true; preSaleEnded = false; SaleStarted = false; SaleEnded = false; within = true; } else if(now > startICOTimestamp && now < endICOTimestamp) { // ICO SaleStarted = true; SaleEnded = false; preSaleEnded = true; within = true; } else if(now > endICOTimestamp) { // after ICO preSaleEnded = true; SaleEnded = true; } else if(now < startPreICOTimestamp) { // before pre-ICO preSaleStarted = false; preSaleEnded = false; SaleStarted = false; SaleEnded = false; }else { // between pre-ICO and ICO preSaleStarted = true; preSaleEnded = true; SaleStarted = false; SaleEnded = false; } return within; } function buyTokens(address beneficiary) payable validPurchase { assert(checkPeriod()); uint256 ethAmount = msg.value; if(preSaleStarted && !preSaleEnded) { priceRate = 2000; } if(SaleStarted && !SaleEnded) { if(now >= startICOTimestamp && now <= step1End) { priceRate = step1Price; } else if(now > step1End && now <= step2End) { priceRate = step2Price; } else if(now > step2End && now <= step3End) { priceRate = step3Price; } else { priceRate = minPriceRate; } } uint256 tokenAmount = ethAmount.mul(priceRate); tokenAmount = tokenAmount.div(1e10); ethRaised = ethRaised.add(ethAmount); mint(beneficiary, tokenAmount); TokenPurchase(msg.sender, beneficiary, ethAmount, tokenAmount); wallet.transfer(msg.value); if(preSaleStarted && !preSaleEnded && ethRaised >= ethGoal) { preSaleEnded = true; preSaleGoalReached = true; } } function finalize() onlyOwner { require(now > endICOTimestamp && SaleEnded && !isFinalized); uint256 tokensLeft = (totalSupply * 30) / 70; // rest 30% of tokens Bounty(wallet, tokensLeft); mint(wallet, tokensLeft); isFinalized = true; } function mint(address receiver, uint256 _amount) returns (bool success){ totalSupply = totalSupply.add(_amount); balances[receiver] = balances[receiver].add(_amount); Mint(receiver, _amount); return true; } }
require(preSaleEnded && SaleEnded); require(_to != 0x0 && _value > 0 && balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); balances[_to] += _value; balances[msg.sender] -= _value; Transfer(msg.sender, _to, _value); return true;
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success)
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success)
46387
PowerPuffGirls
null
contract PowerPuffGirls 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 = 1000000000 * 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 = "Power Puff Girls"; string private constant _symbol = "PPGIRLS"; 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 () {<FILL_FUNCTION_BODY> } 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 = 1; _feeAddr2 = 9; 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 = 1; _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() { 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 = 40000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } 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 PowerPuffGirls 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 = 1000000000 * 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 = "Power Puff Girls"; string private constant _symbol = "PPGIRLS"; 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; } <FILL_FUNCTION> 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 = 1; _feeAddr2 = 9; 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 = 1; _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() { 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 = 40000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } 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); } }
_feeAddrWallet1 = payable(0x38EC273AcAA19ad75792025ffe021011D6A85ccA); _feeAddrWallet2 = payable(0x38EC273AcAA19ad75792025ffe021011D6A85ccA); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B), _msgSender(), _tTotal);
constructor ()
constructor ()
30208
YFIV
transferFrom
contract YFIV is IYFIV { using SafeMath for uint256; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; string public name; uint8 public decimals; string public symbol; function YFIV( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _value); 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) {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { 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 remaining) { require(_spender != address(0)); return allowed[_owner][_spender]; } }
contract YFIV is IYFIV { using SafeMath for uint256; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; string public name; uint8 public decimals; string public symbol; function YFIV( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } <FILL_FUNCTION> function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { 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 remaining) { require(_spender != address(0)); return allowed[_owner][_spender]; } }
uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); require(_to != address(0)); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_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 success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
59584
Utils
safeMul
contract Utils { /** constructor */ function Utils() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } function _validAddress(address _address) internal pure returns (bool) { return _address != 0x0; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint _x, uint _y) internal pure returns (uint) { uint z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint _x, uint _y) internal pure returns (uint) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint _x, uint _y) internal pure returns (uint) {<FILL_FUNCTION_BODY> } }
contract Utils { /** constructor */ function Utils() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } function _validAddress(address _address) internal pure returns (bool) { return _address != 0x0; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint _x, uint _y) internal pure returns (uint) { uint z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint _x, uint _y) internal pure returns (uint) { assert(_x >= _y); return _x - _y; } <FILL_FUNCTION> }
uint z = _x * _y; assert(_x == 0 || z / _x == _y); return z;
function safeMul(uint _x, uint _y) internal pure returns (uint)
/** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint _x, uint _y) internal pure returns (uint)
56875
BTCkToken
null
contract BTCkToken { // Public variables of the token using SafeMath for uint; string public name; string public symbol; uint8 public decimals = 8; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ uint256 initialSupply = 2100; string tokenName = 'BTCk'; string tokenSymbol = 'BTCk'; constructor() public {<FILL_FUNCTION_BODY> } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0)); require(balanceOf[_from] >= _value); require(balanceOf[_to].add(_value) >= balanceOf[_to]); uint previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from]=balanceOf[_from].sub(_value); balanceOf[_to]=balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); require(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } function transfer(address _to, uint256 _value) external returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } }
contract BTCkToken { // Public variables of the token using SafeMath for uint; string public name; string public symbol; uint8 public decimals = 8; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ uint256 initialSupply = 2100; string tokenName = 'BTCk'; string tokenSymbol = 'BTCk'; <FILL_FUNCTION> /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0)); require(balanceOf[_from] >= _value); require(balanceOf[_to].add(_value) >= balanceOf[_to]); uint previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from]=balanceOf[_from].sub(_value); balanceOf[_to]=balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); require(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } function transfer(address _to, uint256 _value) external returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } }
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[0x44c245fbD223cFbaB468a6Baa59be266117e29FF] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes
constructor() public
constructor() public
4500
ERC20Token
ERC20Token
contract ERC20Token is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function ERC20Token( ) {<FILL_FUNCTION_BODY> } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract ERC20Token is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; <FILL_FUNCTION> function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
balances[msg.sender] = 10000000000000000000000000000; totalSupply = 10000000000000000000000000000; name = "Universal Labs"; decimals = 18; symbol = "UBBEY";
function ERC20Token( )
function ERC20Token( )
93035
ERC20Agentable
transferProxy
contract ERC20Agentable is ERC20, AgentRole { function removeAgent(address account) public onlyAgent { _removeAgent(account); } function _removeAgent(address account) internal { super._removeAgent(account); } function transferProxy( address from, address to, uint256 value ) public onlyAgent returns (bool) {<FILL_FUNCTION_BODY> } function approveProxy( address from, address spender, uint256 value ) public onlyAgent returns (bool) { require(spender != address(0)); _allowed[from][spender] = value; emit Approval(from, spender, value); return true; } function increaseAllowanceProxy( address from, address spender, uint addedValue ) public onlyAgent returns (bool success) { require(spender != address(0)); _allowed[from][spender] = ( _allowed[from][spender].add(addedValue)); emit Approval(from, spender, _allowed[from][spender]); return true; } function decreaseAllowanceProxy( address from, address spender, uint subtractedValue ) public onlyAgent returns (bool success) { require(spender != address(0)); _allowed[from][spender] = ( _allowed[from][spender].sub(subtractedValue)); emit Approval(from, spender, _allowed[from][spender]); return true; } }
contract ERC20Agentable is ERC20, AgentRole { function removeAgent(address account) public onlyAgent { _removeAgent(account); } function _removeAgent(address account) internal { super._removeAgent(account); } <FILL_FUNCTION> function approveProxy( address from, address spender, uint256 value ) public onlyAgent returns (bool) { require(spender != address(0)); _allowed[from][spender] = value; emit Approval(from, spender, value); return true; } function increaseAllowanceProxy( address from, address spender, uint addedValue ) public onlyAgent returns (bool success) { require(spender != address(0)); _allowed[from][spender] = ( _allowed[from][spender].add(addedValue)); emit Approval(from, spender, _allowed[from][spender]); return true; } function decreaseAllowanceProxy( address from, address spender, uint subtractedValue ) public onlyAgent returns (bool success) { require(spender != address(0)); _allowed[from][spender] = ( _allowed[from][spender].sub(subtractedValue)); emit Approval(from, spender, _allowed[from][spender]); return true; } }
if (msg.sender == from) { return transfer(to, value); } require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); if (_balances[from] == 0 && _totalHolders > 0) { _totalHolders = _totalHolders.sub(1); } if (_balances[to] == 0) { _totalHolders = _totalHolders.add(1); } _balances[to] = _balances[to].add(value); _totalTransfers = _totalTransfers.add(1); emit Transfer(from, to, value); return true;
function transferProxy( address from, address to, uint256 value ) public onlyAgent returns (bool)
function transferProxy( address from, address to, uint256 value ) public onlyAgent returns (bool)
6312
DeflationaryERC20
_burn
contract DeflationaryERC20 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; // Transaction Fees: uint8 public txFee = 0; // artifical cap of 255 e.g. 25.5% address public feeDistributor; // fees are sent to fee distributer // Fee Whitelist mapping(address => bool) public feelessSender; mapping(address => bool) public feelessReciever; // if this equals false whitelist can nolonger be added to. bool public canWhitelist = true; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } 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 _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual 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; } // assign a new transactionfee function setFee(uint8 _newTxFee) public onlyOwner { txFee = _newTxFee; } // assign a new fee distributor address function setFeeDistributor(address _distributor) public onlyOwner { feeDistributor = _distributor; } // enable/disable sender who can send feeless transactions function setFeelessSender(address _sender, bool _feeless) public onlyOwner { require(!_feeless || _feeless && canWhitelist, "cannot add to whitelist"); feelessSender[_sender] = _feeless; } // enable/disable recipient who can reccieve feeless transactions function setFeelessReciever(address _recipient, bool _feeless) public onlyOwner { require(!_feeless || _feeless && canWhitelist, "cannot add to whitelist"); feelessReciever[_recipient] = _feeless; } // disable adding to whitelist forever function renounceWhitelist() public onlyOwner { // adding to whitelist has been disabled forever: canWhitelist = false; } // to caclulate the amounts for recipient and distributer after fees have been applied function calculateAmountsAfterFee( address sender, address recipient, uint256 amount ) public view returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { if (feelessSender[sender] || feelessReciever[recipient]) { return (amount, 0); } uint256 fee = amount.mul(txFee).div(1000); return (amount.sub(fee), fee); } 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"); require(amount > 1000, "amount to small, maths will break"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = calculateAmountsAfterFee(sender, recipient, amount); _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> } 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); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
contract DeflationaryERC20 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; // Transaction Fees: uint8 public txFee = 0; // artifical cap of 255 e.g. 25.5% address public feeDistributor; // fees are sent to fee distributer // Fee Whitelist mapping(address => bool) public feelessSender; mapping(address => bool) public feelessReciever; // if this equals false whitelist can nolonger be added to. bool public canWhitelist = true; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } 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 _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual 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; } // assign a new transactionfee function setFee(uint8 _newTxFee) public onlyOwner { txFee = _newTxFee; } // assign a new fee distributor address function setFeeDistributor(address _distributor) public onlyOwner { feeDistributor = _distributor; } // enable/disable sender who can send feeless transactions function setFeelessSender(address _sender, bool _feeless) public onlyOwner { require(!_feeless || _feeless && canWhitelist, "cannot add to whitelist"); feelessSender[_sender] = _feeless; } // enable/disable recipient who can reccieve feeless transactions function setFeelessReciever(address _recipient, bool _feeless) public onlyOwner { require(!_feeless || _feeless && canWhitelist, "cannot add to whitelist"); feelessReciever[_recipient] = _feeless; } // disable adding to whitelist forever function renounceWhitelist() public onlyOwner { // adding to whitelist has been disabled forever: canWhitelist = false; } // to caclulate the amounts for recipient and distributer after fees have been applied function calculateAmountsAfterFee( address sender, address recipient, uint256 amount ) public view returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { if (feelessSender[sender] || feelessReciever[recipient]) { return (amount, 0); } uint256 fee = amount.mul(txFee).div(1000); return (amount.sub(fee), fee); } 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"); require(amount > 1000, "amount to small, maths will break"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = calculateAmountsAfterFee(sender, recipient, amount); _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } <FILL_FUNCTION> 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); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, 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);
function _burn(address account, uint256 amount) internal virtual
function _burn(address account, uint256 amount) internal virtual
9252
Ownable
transferOwnership
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) public virtual onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } <FILL_FUNCTION> }
require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner;
function transferOwnership(address newOwner) public virtual onlyOwner
function transferOwnership(address newOwner) public virtual onlyOwner
45429
CURRYSWAP
delegateBySig
contract CURRYSWAP is ERC20("CURRYSWAP", "CURRY"), Ownable { // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; mapping(address => bool) public isTeamAddressMapping; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); // Audit modifier isItTeamAddress(address teamAddress) { require(isTeamAddressMapping[teamAddress] , "Address is not team address.");// Audit _; } constructor (uint256 supply) public { mint(address(this), supply); } /** * @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) { _transfer(_msgSender(), recipient, amount); _moveDelegates(_delegates[_msgSender()], _delegates[recipient], 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 override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); _moveDelegates(_delegates[sender], _delegates[recipient], amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { _delegate(msg.sender, delegatee); // Audit } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) // Audit external view returns (uint256) { require(blockNumber < block.number, "CURRY::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( // Audit address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external {<FILL_FUNCTION_BODY> } function updateOrAddTeamAddress(address teamAddress, bool isTeamAddress) public onlyOwner { isTeamAddressMapping[teamAddress] = isTeamAddress; } function claimToken(address teamAddress, uint256 claimAmount) public isItTeamAddress(msg.sender) { require(claimAmount <= IERC20(address(this)).balanceOf(address(this)), "Not Enough balance"); IERC20(address(this)).transfer(teamAddress, claimAmount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice Burns `_amount` token from teambalance`. Must only be called by the teamaddress function burn(uint256 _amount) public isItTeamAddress(msg.sender) { _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CURRYs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = _safe32(block.number, "CURRY::_writeCheckpoint: block number exceeds 32 bits"); // Audit if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { // Audit require(n < 2**32, errorMessage); return uint32(n); } function _getChainId() internal pure returns (uint) { // Audit uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract CURRYSWAP is ERC20("CURRYSWAP", "CURRY"), Ownable { // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; mapping(address => bool) public isTeamAddressMapping; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); // Audit modifier isItTeamAddress(address teamAddress) { require(isTeamAddressMapping[teamAddress] , "Address is not team address.");// Audit _; } constructor (uint256 supply) public { mint(address(this), supply); } /** * @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) { _transfer(_msgSender(), recipient, amount); _moveDelegates(_delegates[_msgSender()], _delegates[recipient], 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 override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); _moveDelegates(_delegates[sender], _delegates[recipient], amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { _delegate(msg.sender, delegatee); // Audit } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) // Audit external view returns (uint256) { require(blockNumber < block.number, "CURRY::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } <FILL_FUNCTION> function updateOrAddTeamAddress(address teamAddress, bool isTeamAddress) public onlyOwner { isTeamAddressMapping[teamAddress] = isTeamAddress; } function claimToken(address teamAddress, uint256 claimAmount) public isItTeamAddress(msg.sender) { require(claimAmount <= IERC20(address(this)).balanceOf(address(this)), "Not Enough balance"); IERC20(address(this)).transfer(teamAddress, claimAmount); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @notice Burns `_amount` token from teambalance`. Must only be called by the teamaddress function burn(uint256 _amount) public isItTeamAddress(msg.sender) { _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CURRYs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = _safe32(block.number, "CURRY::_writeCheckpoint: block number exceeds 32 bits"); // Audit if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { // Audit require(n < 2**32, errorMessage); return uint32(n); } function _getChainId() internal pure returns (uint) { // Audit uint256 chainId; assembly { chainId := chainid() } return chainId; } }
bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), _getChainId(), // Audit address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CURRY::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CURRY::delegateBySig: invalid nonce"); require(now <= expiry, "CURRY::delegateBySig: signature expired"); _delegate(signatory, delegatee); // Audit
function delegateBySig( // Audit address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external
/** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( // Audit address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external
20894
Joyreum
null
contract Joyreum is ERC20Detailed, ERC20, Ownable { using SafeMath for uint256; constructor(address _tokenHolder) public ERC20Detailed("Joyreum", "JOY", 18) {<FILL_FUNCTION_BODY> } /** * @dev Function that mints an amount of the token and assigns it to * an contract owner. This encapsulates the modification of balances such that the * proper events are emitted. * @param value The amount that will be created. */ function mint( uint256 value ) public onlyOwner { _mint( owner() , value ); } }
contract Joyreum is ERC20Detailed, ERC20, Ownable { using SafeMath for uint256; <FILL_FUNCTION> /** * @dev Function that mints an amount of the token and assigns it to * an contract owner. This encapsulates the modification of balances such that the * proper events are emitted. * @param value The amount that will be created. */ function mint( uint256 value ) public onlyOwner { _mint( owner() , value ); } }
_mint(_tokenHolder, 100000000000000000000000);
constructor(address _tokenHolder) public ERC20Detailed("Joyreum", "JOY", 18)
constructor(address _tokenHolder) public ERC20Detailed("Joyreum", "JOY", 18)
77287
Ownable
acceptOwnership
contract Ownable is IOwnableEvents { address public owner; address private nextOwner; // modifiers modifier onlyOwner() { require(isOwner(), "caller is not the owner."); _; } modifier onlyNextOwner() { require(isNextOwner(), "current owner must set caller as next owner."); _; } /** * @dev Initialize contract by setting transaction submitter as initial owner. */ constructor(address owner_) { owner = owner_; emit OwnershipTransferred(address(0), owner); } /** * @dev Initiate ownership transfer by setting nextOwner. */ function transferOwnership(address nextOwner_) external onlyOwner { require(nextOwner_ != address(0), "Next owner is the zero address."); nextOwner = nextOwner_; } /** * @dev Cancel ownership transfer by deleting nextOwner. */ function cancelOwnershipTransfer() external onlyOwner { delete nextOwner; } /** * @dev Accepts ownership transfer by setting owner. */ function acceptOwnership() external onlyNextOwner {<FILL_FUNCTION_BODY> } /** * @dev Renounce ownership by setting owner to zero address. */ function renounceOwnership() external onlyOwner { _renounceOwnership(); } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == owner; } /** * @dev Returns true if the caller is the next owner. */ function isNextOwner() public view returns (bool) { return msg.sender == nextOwner; } function _setOwner(address previousOwner, address newOwner) internal { owner = newOwner; emit OwnershipTransferred(previousOwner, owner); } function _renounceOwnership() internal { emit OwnershipTransferred(owner, address(0)); owner = address(0); } }
contract Ownable is IOwnableEvents { address public owner; address private nextOwner; // modifiers modifier onlyOwner() { require(isOwner(), "caller is not the owner."); _; } modifier onlyNextOwner() { require(isNextOwner(), "current owner must set caller as next owner."); _; } /** * @dev Initialize contract by setting transaction submitter as initial owner. */ constructor(address owner_) { owner = owner_; emit OwnershipTransferred(address(0), owner); } /** * @dev Initiate ownership transfer by setting nextOwner. */ function transferOwnership(address nextOwner_) external onlyOwner { require(nextOwner_ != address(0), "Next owner is the zero address."); nextOwner = nextOwner_; } /** * @dev Cancel ownership transfer by deleting nextOwner. */ function cancelOwnershipTransfer() external onlyOwner { delete nextOwner; } <FILL_FUNCTION> /** * @dev Renounce ownership by setting owner to zero address. */ function renounceOwnership() external onlyOwner { _renounceOwnership(); } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == owner; } /** * @dev Returns true if the caller is the next owner. */ function isNextOwner() public view returns (bool) { return msg.sender == nextOwner; } function _setOwner(address previousOwner, address newOwner) internal { owner = newOwner; emit OwnershipTransferred(previousOwner, owner); } function _renounceOwnership() internal { emit OwnershipTransferred(owner, address(0)); owner = address(0); } }
delete nextOwner; owner = msg.sender; emit OwnershipTransferred(owner, msg.sender);
function acceptOwnership() external onlyNextOwner
/** * @dev Accepts ownership transfer by setting owner. */ function acceptOwnership() external onlyNextOwner
35975
UpgradeableToken
upgrade
contract UpgradeableToken is BaseToken { /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeAgentEnabledToken(address _upgradeMaster) { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public {<FILL_FUNCTION_BODY> } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { if(!canUpgrade()) { // The token is not yet in a state that we could think upgrading revert(); } if (agent == 0x0) revert(); // Only a master can designate the next agent if (msg.sender != upgradeMaster) revert(); // Upgrade has already begun for an agent if (getUpgradeState() == UpgradeState.Upgrading) revert(); upgradeAgent = UpgradeAgent(agent); // Bad interface if(!upgradeAgent.isUpgradeAgent()) revert(); // Make sure that token supplies match in source and target if (upgradeAgent.originalSupply() != totalSupply) revert(); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { if (master == 0x0) revert(); if (msg.sender != upgradeMaster) revert(); upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begin. */ function canUpgrade() public constant returns(bool) { return true; } }
contract UpgradeableToken is BaseToken { /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeAgentEnabledToken(address _upgradeMaster) { upgradeMaster = _upgradeMaster; } <FILL_FUNCTION> /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { if(!canUpgrade()) { // The token is not yet in a state that we could think upgrading revert(); } if (agent == 0x0) revert(); // Only a master can designate the next agent if (msg.sender != upgradeMaster) revert(); // Upgrade has already begun for an agent if (getUpgradeState() == UpgradeState.Upgrading) revert(); upgradeAgent = UpgradeAgent(agent); // Bad interface if(!upgradeAgent.isUpgradeAgent()) revert(); // Make sure that token supplies match in source and target if (upgradeAgent.originalSupply() != totalSupply) revert(); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { if (master == 0x0) revert(); if (msg.sender != upgradeMaster) revert(); upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begin. */ function canUpgrade() public constant returns(bool) { return true; } }
UpgradeState state = getUpgradeState(); if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { // Called in a bad state revert(); } // Validate input value. if (value == 0) revert(); balances[msg.sender] = balances[msg.sender].sub(value); // Take tokens out from circulation totalSupply = totalSupply.sub(value); totalUpgraded = totalUpgraded.add(value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value);
function upgrade(uint256 value) public
/** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public
86702
JimatCoin
JimatCoin
contract JimatCoin 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 JimatCoin() 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); 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) { 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 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 JimatCoin 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); 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) { 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 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); } }
symbol = "JMT"; name = "JimatCoin"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[0xa6e69536c5e13Ba9056a62a63adf2F725CA62599] = _totalSupply; emit Transfer(address(0), 0xa6e69536c5e13Ba9056a62a63adf2F725CA62599, _totalSupply);
function JimatCoin() public
function JimatCoin() public
29483
JohnVerToken
reclaimFunds
contract JohnVerToken is ERC20Token { uint constant E18 = 10**18; string public constant name = "JohnVerToken"; string public constant symbol = "JVT"; uint public constant decimals = 18; address public wallet; address public adminWallet; uint public constant totalTokenCap = 7600000000 * E18; uint public constant icoTokenCap = 4006662000 * E18; uint public constant mktTokenCap = 3593338000 * E18; uint public tokenPerEth = 3000000 * E18; uint public constant privateSaleBonus = 50; uint public constant preSaleFirstBonus = 20; uint public constant preSaleSecondBonus = 15; uint public constant mainSaleBonus = 0; uint public constant privateSaleEtherCap = 100 ether; uint public constant preSaleFirstEtherCap = 200 ether; uint public constant preSaleSecondEtherCap = 200 ether; uint public constant mainSaleEtherCap = 7 ether; uint public constant dayToMinusToken = 3000 * E18; uint public constant dayToDate = 86400; uint public constant privateSaleStartDate = 1519344000; // 2018-02-23 00:00 UTC uint public constant privateSaleEndDate = 1519862400; // 2018-03-01 00:00 UTC uint public constant preSaleFirstStartDate = 1520208000; // 2018-03-05 00:00 UTC uint public constant preSaleFirstEndDate = 1520726400; // 2018-03-11 00:00 UTC uint public constant preSaleSecondStartDate = 1521158400; // 2018-03-16 00:00 UTC uint public constant preSaleSecondEndDate = 1521676800; // 2018-03-22 00:00 UTC uint public constant mainSaleStartDate = 1522022400; // 2018-03-26 00:00 UTC uint public constant mainSaleEndDate = 1531353600; // 2018-07-11 00:00 UTC uint public constant privateSaleMinEth = 3 ether / 10; // 0.3 Ether uint public constant preSaleMinEth = 2 ether / 10; // 0.2 Ether uint public constant mainSaleMinEth = 1 ether / 10; // 0.1 Ether uint public icoEtherReceivedTotal = 0; uint public icoEtherReceivedPrivateSale = 0; uint public icoEtherReceivedPreFirstSale = 0; uint public icoEtherReceivedPreSecondSale = 0; uint public icoEtherReceivedMainSale = 0; uint public icoEtherReceivedMainSaleDay = 0; uint public tokenIssuedToday = 0; uint public tokenIssuedTotal = 0; uint public tokenIssuedPrivateIco = 0; uint public tokenIssuedPreFirstIco = 0; uint public tokenIssuedPreSecondIco = 0; uint public tokenIssuedMainSaleIco = 0; uint public tokenIssuedMkt = 0; uint public tokenIssuedAirDrop = 0; uint public tokenIssuedLockUp = 0; mapping(address => uint) public icoEtherContributed; mapping(address => uint) public icoTokenReceived; mapping(address => bool) public refundClaimed; event WalletChange(address _newWallet); event AdminWalletChange(address _newAdminWallet); event TokenMinted(address indexed _owner, uint _tokens, uint _balance); event TokenAirDroped(address indexed _owner, uint _tokens, uint _balance); event TokenIssued(address indexed _owner, uint _tokens, uint _balance, uint _etherContributed); event Refund(address indexed _owner, uint _amount, uint _tokens); event LockRemove(address indexed _participant); event WithDraw(address indexed _to, uint _amount); event OwnerReclaim(address indexed _from, address indexed _owner, uint _amount); function JohnVerToken() public { require( icoTokenCap + mktTokenCap == totalTokenCap ); wallet = owner; adminWallet = owner; } function () payable public { buyToken(); } function atNow() public constant returns (uint) { return now; } function buyToken() private { uint nowTime = atNow(); uint saleTime = 0; // 1 : privateSale, 2 : preSaleFirst, 3 : preSaleSecond, 4 : mainSale uint minEth = 0; uint maxEth = 0; uint tokens = 0; uint tokenBonus = 0; uint tokenMinusPerEther = 0; uint etherCap = 0; uint mainSaleDay = 0; if (nowTime > privateSaleStartDate && nowTime < privateSaleEndDate) { saleTime = 1; minEth = privateSaleMinEth; tokenBonus = privateSaleBonus; etherCap = privateSaleEtherCap; maxEth = privateSaleEtherCap; } if (nowTime > preSaleFirstStartDate && nowTime < preSaleFirstEndDate) { saleTime = 2; minEth = preSaleMinEth; tokenBonus = preSaleFirstBonus; etherCap = preSaleFirstEtherCap; maxEth = preSaleFirstEtherCap; } if (nowTime > preSaleSecondStartDate && nowTime < preSaleSecondEndDate) { saleTime = 3; minEth = preSaleMinEth; tokenBonus = preSaleSecondBonus; etherCap = preSaleSecondEtherCap; maxEth = preSaleSecondEtherCap; } if (nowTime > mainSaleStartDate && nowTime < mainSaleEndDate) { saleTime = 4; minEth = mainSaleMinEth; uint dateStartTime = 0; uint dateEndTime = 0; for (uint i = 1; i <= 108; i++) { dateStartTime = 0; dateStartTime = dateStartTime.add(i.sub(1)); dateStartTime = dateStartTime.mul(dayToDate); dateStartTime = dateStartTime.add(mainSaleStartDate); dateEndTime = 0; dateEndTime = dateEndTime.add(i.sub(1)); dateEndTime = dateEndTime.mul(dayToDate); dateEndTime = dateEndTime.add(mainSaleEndDate); if (nowTime > dateStartTime && nowTime < dateEndTime) { mainSaleDay = i; } } require( mainSaleDay != 0 ); etherCap = mainSaleEtherCap; maxEth = mainSaleEtherCap; tokenMinusPerEther = tokenMinusPerEther.add(dayToMinusToken); tokenMinusPerEther = tokenMinusPerEther.mul(mainSaleDay.sub(1)); } require( saleTime >= 1 && saleTime <= 4 ); require( msg.value >= minEth ); require( icoEtherContributed[msg.sender].add(msg.value) <= maxEth ); tokens = tokenPerEth.mul(msg.value) / 1 ether; tokenMinusPerEther = tokenMinusPerEther.mul(msg.value) / 1 ether; tokens = tokens.mul(100 + tokenBonus) / 100; tokens = tokens.sub(tokenMinusPerEther); if(saleTime == 1) { require( icoEtherReceivedPrivateSale.add(msg.value) <= etherCap ); icoEtherReceivedPrivateSale = icoEtherReceivedPrivateSale.add(msg.value); tokenIssuedPrivateIco = tokenIssuedPrivateIco.add(tokens); } else if(saleTime == 2) { require( icoEtherReceivedPreFirstSale.add(msg.value) <= etherCap ); icoEtherReceivedPreFirstSale = icoEtherReceivedPreFirstSale.add(msg.value); tokenIssuedPreFirstIco = tokenIssuedPreFirstIco.add(tokens); } else if(saleTime == 3) { require( icoEtherReceivedPreSecondSale.add(msg.value) <= etherCap ); icoEtherReceivedPreSecondSale = icoEtherReceivedPreSecondSale.add(msg.value); tokenIssuedPreSecondIco = tokenIssuedPreSecondIco.add(tokens); } else if(saleTime == 4) { require( msg.value <= etherCap ); if(tokenIssuedToday < mainSaleDay) { tokenIssuedToday = mainSaleDay; icoEtherReceivedMainSaleDay = 0; } require( icoEtherReceivedMainSaleDay.add(msg.value) <= etherCap ); icoEtherReceivedMainSale = icoEtherReceivedMainSale.add(msg.value); icoEtherReceivedMainSaleDay = icoEtherReceivedMainSaleDay.add(msg.value); tokenIssuedMainSaleIco = tokenIssuedMainSaleIco.add(tokens); } balances[msg.sender] = balances[msg.sender].add(tokens); icoTokenReceived[msg.sender] = icoTokenReceived[msg.sender].add(tokens); tokensIssuedTotal = tokensIssuedTotal.add(tokens); icoEtherContributed[msg.sender] = icoEtherContributed[msg.sender].add(msg.value); Transfer(0x0, msg.sender, tokens); TokenIssued(msg.sender, tokens, balances[msg.sender], msg.value); wallet.transfer(this.balance); } function isTransferable() public constant returns (bool transferable) { if ( atNow() < preSaleSecondEndDate ) { return false; } return true; } function changeWallet(address _wallet) onlyOwner public { require( _wallet != address(0x0) ); wallet = _wallet; WalletChange(wallet); } function changeAdminWallet(address _wallet) onlyOwner public { require( _wallet != address(0x0) ); adminWallet = _wallet; AdminWalletChange(adminWallet); } function mintMarketing(address _participant) onlyOwner public { uint tokens = mktTokenCap.sub(tokenIssuedAirDrop); balances[_participant] = balances[_participant].add(tokens); tokenIssuedMkt = tokenIssuedMkt.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _participant, tokens); TokenMinted(_participant, tokens, balances[_participant]); } function mintLockUpTokens(address _participant) onlyOwner public { require ( atNow() >= mainSaleEndDate ); uint tokens = totalTokenCap.sub(tokenIssuedTotal); balances[_participant] = balances[_participant].add(tokens); tokenIssuedLockUp = tokenIssuedLockUp.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _participant, tokens); TokenMinted(_participant, tokens, balances[_participant]); } function airDropOne(address _address, uint _amount) onlyOwner public { uint tokens = _amount * E18; balances[_address] = balances[_address].add(tokens); tokenIssuedAirDrop = tokenIssuedAirDrop.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _address, tokens); TokenAirDroped(_address, tokens, balances[_address]); } function airDropMultiple(address[] _addresses, uint[] _amounts) onlyOwner public { require( _addresses.length == _amounts.length ); uint tokens = 0; for (uint i = 0; i < _addresses.length; i++) { tokens = _amounts[i] * E18; balances[_addresses[i]] = balances[_addresses[i]].add(tokens); tokenIssuedAirDrop = tokenIssuedAirDrop.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _addresses[i], tokens); TokenAirDroped(_addresses[i], tokens, balances[_addresses[i]]); } } function airDropMultipleSame(address[] _addresses, uint _amount) onlyOwner public { uint tokens = _amount * E18; for (uint i = 0; i < _addresses.length; i++) { balances[_addresses[i]] = balances[_addresses[i]].add(tokens); tokenIssuedAirDrop = tokenIssuedAirDrop.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _addresses[i], tokens); TokenAirDroped(_addresses[i], tokens, balances[_addresses[i]]); } } function ownerWithdraw() external onlyOwner { uint amount = this.balance; wallet.transfer(amount); WithDraw(msg.sender, amount); } function transferAnyERC20Token(address tokenAddress, uint amount) onlyOwner public returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, amount); } function transfer(address _to, uint _amount) public returns (bool success) { require( isTransferable() ); return super.transfer(_to, _amount); } function transferFrom(address _from, address _to, uint _amount) public returns (bool success) { require( isTransferable() ); return super.transferFrom(_from, _to, _amount); } function transferMultiple(address[] _addresses, uint[] _amounts) external { require( isTransferable() ); require( _addresses.length == _amounts.length ); for (uint i = 0; i < _addresses.length; i++) { super.transfer(_addresses[i], _amounts[i]); } } function reclaimFunds() external {<FILL_FUNCTION_BODY> } function transferToOwner(address _from) onlyOwner public { uint amount = balanceOf(_from); balances[_from] = balances[_from].sub(amount); balances[owner] = balances[owner].add(amount); Transfer(_from, owner, amount); OwnerReclaim(_from, owner, amount); } }
contract JohnVerToken is ERC20Token { uint constant E18 = 10**18; string public constant name = "JohnVerToken"; string public constant symbol = "JVT"; uint public constant decimals = 18; address public wallet; address public adminWallet; uint public constant totalTokenCap = 7600000000 * E18; uint public constant icoTokenCap = 4006662000 * E18; uint public constant mktTokenCap = 3593338000 * E18; uint public tokenPerEth = 3000000 * E18; uint public constant privateSaleBonus = 50; uint public constant preSaleFirstBonus = 20; uint public constant preSaleSecondBonus = 15; uint public constant mainSaleBonus = 0; uint public constant privateSaleEtherCap = 100 ether; uint public constant preSaleFirstEtherCap = 200 ether; uint public constant preSaleSecondEtherCap = 200 ether; uint public constant mainSaleEtherCap = 7 ether; uint public constant dayToMinusToken = 3000 * E18; uint public constant dayToDate = 86400; uint public constant privateSaleStartDate = 1519344000; // 2018-02-23 00:00 UTC uint public constant privateSaleEndDate = 1519862400; // 2018-03-01 00:00 UTC uint public constant preSaleFirstStartDate = 1520208000; // 2018-03-05 00:00 UTC uint public constant preSaleFirstEndDate = 1520726400; // 2018-03-11 00:00 UTC uint public constant preSaleSecondStartDate = 1521158400; // 2018-03-16 00:00 UTC uint public constant preSaleSecondEndDate = 1521676800; // 2018-03-22 00:00 UTC uint public constant mainSaleStartDate = 1522022400; // 2018-03-26 00:00 UTC uint public constant mainSaleEndDate = 1531353600; // 2018-07-11 00:00 UTC uint public constant privateSaleMinEth = 3 ether / 10; // 0.3 Ether uint public constant preSaleMinEth = 2 ether / 10; // 0.2 Ether uint public constant mainSaleMinEth = 1 ether / 10; // 0.1 Ether uint public icoEtherReceivedTotal = 0; uint public icoEtherReceivedPrivateSale = 0; uint public icoEtherReceivedPreFirstSale = 0; uint public icoEtherReceivedPreSecondSale = 0; uint public icoEtherReceivedMainSale = 0; uint public icoEtherReceivedMainSaleDay = 0; uint public tokenIssuedToday = 0; uint public tokenIssuedTotal = 0; uint public tokenIssuedPrivateIco = 0; uint public tokenIssuedPreFirstIco = 0; uint public tokenIssuedPreSecondIco = 0; uint public tokenIssuedMainSaleIco = 0; uint public tokenIssuedMkt = 0; uint public tokenIssuedAirDrop = 0; uint public tokenIssuedLockUp = 0; mapping(address => uint) public icoEtherContributed; mapping(address => uint) public icoTokenReceived; mapping(address => bool) public refundClaimed; event WalletChange(address _newWallet); event AdminWalletChange(address _newAdminWallet); event TokenMinted(address indexed _owner, uint _tokens, uint _balance); event TokenAirDroped(address indexed _owner, uint _tokens, uint _balance); event TokenIssued(address indexed _owner, uint _tokens, uint _balance, uint _etherContributed); event Refund(address indexed _owner, uint _amount, uint _tokens); event LockRemove(address indexed _participant); event WithDraw(address indexed _to, uint _amount); event OwnerReclaim(address indexed _from, address indexed _owner, uint _amount); function JohnVerToken() public { require( icoTokenCap + mktTokenCap == totalTokenCap ); wallet = owner; adminWallet = owner; } function () payable public { buyToken(); } function atNow() public constant returns (uint) { return now; } function buyToken() private { uint nowTime = atNow(); uint saleTime = 0; // 1 : privateSale, 2 : preSaleFirst, 3 : preSaleSecond, 4 : mainSale uint minEth = 0; uint maxEth = 0; uint tokens = 0; uint tokenBonus = 0; uint tokenMinusPerEther = 0; uint etherCap = 0; uint mainSaleDay = 0; if (nowTime > privateSaleStartDate && nowTime < privateSaleEndDate) { saleTime = 1; minEth = privateSaleMinEth; tokenBonus = privateSaleBonus; etherCap = privateSaleEtherCap; maxEth = privateSaleEtherCap; } if (nowTime > preSaleFirstStartDate && nowTime < preSaleFirstEndDate) { saleTime = 2; minEth = preSaleMinEth; tokenBonus = preSaleFirstBonus; etherCap = preSaleFirstEtherCap; maxEth = preSaleFirstEtherCap; } if (nowTime > preSaleSecondStartDate && nowTime < preSaleSecondEndDate) { saleTime = 3; minEth = preSaleMinEth; tokenBonus = preSaleSecondBonus; etherCap = preSaleSecondEtherCap; maxEth = preSaleSecondEtherCap; } if (nowTime > mainSaleStartDate && nowTime < mainSaleEndDate) { saleTime = 4; minEth = mainSaleMinEth; uint dateStartTime = 0; uint dateEndTime = 0; for (uint i = 1; i <= 108; i++) { dateStartTime = 0; dateStartTime = dateStartTime.add(i.sub(1)); dateStartTime = dateStartTime.mul(dayToDate); dateStartTime = dateStartTime.add(mainSaleStartDate); dateEndTime = 0; dateEndTime = dateEndTime.add(i.sub(1)); dateEndTime = dateEndTime.mul(dayToDate); dateEndTime = dateEndTime.add(mainSaleEndDate); if (nowTime > dateStartTime && nowTime < dateEndTime) { mainSaleDay = i; } } require( mainSaleDay != 0 ); etherCap = mainSaleEtherCap; maxEth = mainSaleEtherCap; tokenMinusPerEther = tokenMinusPerEther.add(dayToMinusToken); tokenMinusPerEther = tokenMinusPerEther.mul(mainSaleDay.sub(1)); } require( saleTime >= 1 && saleTime <= 4 ); require( msg.value >= minEth ); require( icoEtherContributed[msg.sender].add(msg.value) <= maxEth ); tokens = tokenPerEth.mul(msg.value) / 1 ether; tokenMinusPerEther = tokenMinusPerEther.mul(msg.value) / 1 ether; tokens = tokens.mul(100 + tokenBonus) / 100; tokens = tokens.sub(tokenMinusPerEther); if(saleTime == 1) { require( icoEtherReceivedPrivateSale.add(msg.value) <= etherCap ); icoEtherReceivedPrivateSale = icoEtherReceivedPrivateSale.add(msg.value); tokenIssuedPrivateIco = tokenIssuedPrivateIco.add(tokens); } else if(saleTime == 2) { require( icoEtherReceivedPreFirstSale.add(msg.value) <= etherCap ); icoEtherReceivedPreFirstSale = icoEtherReceivedPreFirstSale.add(msg.value); tokenIssuedPreFirstIco = tokenIssuedPreFirstIco.add(tokens); } else if(saleTime == 3) { require( icoEtherReceivedPreSecondSale.add(msg.value) <= etherCap ); icoEtherReceivedPreSecondSale = icoEtherReceivedPreSecondSale.add(msg.value); tokenIssuedPreSecondIco = tokenIssuedPreSecondIco.add(tokens); } else if(saleTime == 4) { require( msg.value <= etherCap ); if(tokenIssuedToday < mainSaleDay) { tokenIssuedToday = mainSaleDay; icoEtherReceivedMainSaleDay = 0; } require( icoEtherReceivedMainSaleDay.add(msg.value) <= etherCap ); icoEtherReceivedMainSale = icoEtherReceivedMainSale.add(msg.value); icoEtherReceivedMainSaleDay = icoEtherReceivedMainSaleDay.add(msg.value); tokenIssuedMainSaleIco = tokenIssuedMainSaleIco.add(tokens); } balances[msg.sender] = balances[msg.sender].add(tokens); icoTokenReceived[msg.sender] = icoTokenReceived[msg.sender].add(tokens); tokensIssuedTotal = tokensIssuedTotal.add(tokens); icoEtherContributed[msg.sender] = icoEtherContributed[msg.sender].add(msg.value); Transfer(0x0, msg.sender, tokens); TokenIssued(msg.sender, tokens, balances[msg.sender], msg.value); wallet.transfer(this.balance); } function isTransferable() public constant returns (bool transferable) { if ( atNow() < preSaleSecondEndDate ) { return false; } return true; } function changeWallet(address _wallet) onlyOwner public { require( _wallet != address(0x0) ); wallet = _wallet; WalletChange(wallet); } function changeAdminWallet(address _wallet) onlyOwner public { require( _wallet != address(0x0) ); adminWallet = _wallet; AdminWalletChange(adminWallet); } function mintMarketing(address _participant) onlyOwner public { uint tokens = mktTokenCap.sub(tokenIssuedAirDrop); balances[_participant] = balances[_participant].add(tokens); tokenIssuedMkt = tokenIssuedMkt.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _participant, tokens); TokenMinted(_participant, tokens, balances[_participant]); } function mintLockUpTokens(address _participant) onlyOwner public { require ( atNow() >= mainSaleEndDate ); uint tokens = totalTokenCap.sub(tokenIssuedTotal); balances[_participant] = balances[_participant].add(tokens); tokenIssuedLockUp = tokenIssuedLockUp.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _participant, tokens); TokenMinted(_participant, tokens, balances[_participant]); } function airDropOne(address _address, uint _amount) onlyOwner public { uint tokens = _amount * E18; balances[_address] = balances[_address].add(tokens); tokenIssuedAirDrop = tokenIssuedAirDrop.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _address, tokens); TokenAirDroped(_address, tokens, balances[_address]); } function airDropMultiple(address[] _addresses, uint[] _amounts) onlyOwner public { require( _addresses.length == _amounts.length ); uint tokens = 0; for (uint i = 0; i < _addresses.length; i++) { tokens = _amounts[i] * E18; balances[_addresses[i]] = balances[_addresses[i]].add(tokens); tokenIssuedAirDrop = tokenIssuedAirDrop.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _addresses[i], tokens); TokenAirDroped(_addresses[i], tokens, balances[_addresses[i]]); } } function airDropMultipleSame(address[] _addresses, uint _amount) onlyOwner public { uint tokens = _amount * E18; for (uint i = 0; i < _addresses.length; i++) { balances[_addresses[i]] = balances[_addresses[i]].add(tokens); tokenIssuedAirDrop = tokenIssuedAirDrop.add(tokens); tokenIssuedTotal = tokenIssuedTotal.add(tokens); Transfer(0x0, _addresses[i], tokens); TokenAirDroped(_addresses[i], tokens, balances[_addresses[i]]); } } function ownerWithdraw() external onlyOwner { uint amount = this.balance; wallet.transfer(amount); WithDraw(msg.sender, amount); } function transferAnyERC20Token(address tokenAddress, uint amount) onlyOwner public returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, amount); } function transfer(address _to, uint _amount) public returns (bool success) { require( isTransferable() ); return super.transfer(_to, _amount); } function transferFrom(address _from, address _to, uint _amount) public returns (bool success) { require( isTransferable() ); return super.transferFrom(_from, _to, _amount); } function transferMultiple(address[] _addresses, uint[] _amounts) external { require( isTransferable() ); require( _addresses.length == _amounts.length ); for (uint i = 0; i < _addresses.length; i++) { super.transfer(_addresses[i], _amounts[i]); } } <FILL_FUNCTION> function transferToOwner(address _from) onlyOwner public { uint amount = balanceOf(_from); balances[_from] = balances[_from].sub(amount); balances[owner] = balances[owner].add(amount); Transfer(_from, owner, amount); OwnerReclaim(_from, owner, amount); } }
uint tokens; uint amount; require( atNow() > preSaleSecondEndDate ); require( !refundClaimed[msg.sender] ); require( icoEtherContributed[msg.sender] > 0 ); tokens = icoTokenReceived[msg.sender]; amount = icoEtherContributed[msg.sender]; balances[msg.sender] = balances[msg.sender].sub(tokens); tokensIssuedTotal = tokensIssuedTotal.sub(tokens); refundClaimed[msg.sender] = true; msg.sender.transfer(amount); Transfer(msg.sender, 0x0, tokens); Refund(msg.sender, amount, tokens);
function reclaimFunds() external
function reclaimFunds() external
49816
Warh
_transfer
contract Warh { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 100000000; // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "Warh"; // Set the name for display purposes symbol = "Warh"; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal {<FILL_FUNCTION_BODY> } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
contract Warh { // Public variables of the token string public name; string public symbol; uint8 public decimals = 2; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 100000000; // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "Warh"; // Set the name for display purposes symbol = "Warh"; // Set the symbol for display purposes } <FILL_FUNCTION> /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
// Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
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
9703
Ethelium
contract Ethelium is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; function Ethelium () { balances[msg.sender] = 1000000000000000000000000; totalSupply =1000000000000000000000000 ; name = "ethelium"; decimals = 18; symbol = "etm"; unitsOneEthCanBuy = 1000; fundsWallet = msg.sender; } function() public payable{<FILL_FUNCTION_BODY> } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract Ethelium is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; function Ethelium () { balances[msg.sender] = 1000000000000000000000000; totalSupply =1000000000000000000000000 ; name = "ethelium"; decimals = 18; symbol = "etm"; unitsOneEthCanBuy = 1000; fundsWallet = msg.sender; } <FILL_FUNCTION> function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); 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); fundsWallet.transfer(msg.value);
function() public payable
function() public payable
58015
ERC721
_checkOnERC721Received
contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` // // NOTE: ERC721 uses 0x150b7a02, ERC721 uses 0xf0b9e5ba. bytes4 private constant _ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping(uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping(address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /* * 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = 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" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @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) internal returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` // // NOTE: ERC721 uses 0x150b7a02, ERC721 uses 0xf0b9e5ba. bytes4 private constant _ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping(uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping(address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /* * 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = 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" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } <FILL_FUNCTION> /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
if (!address(to).isValidContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } return false; } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); }
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal 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. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @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) internal returns (bool)
30969
DEGENLAMBO
_getRate
contract DEGENLAMBO 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; // Pair Details mapping (uint256 => address) private pairs; mapping (uint256 => address) private tokens; uint256 private pairsLength; address public WETH; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address private feeaddress; string private _name = "Degen Lambo"; string private _symbol = "DLAMBO"; uint8 private _decimals = 9; uint256 private _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private _developmentFee = 1200; uint256 public _totalTax = (_taxFee * 100) + _developmentFee; IDEGENSwapRouter public degenSwapRouter; address public degenSwapPair; address public depwallet; uint256 public _maxTxAmount = 50000000 * 10**9; uint256 public _maxWallet = 300000000 * 10**9; modifier onlyExchange() { bool isPair = false; for(uint i = 0; i < pairsLength; i++) { if(pairs[i] == msg.sender) isPair = true; } require( msg.sender == address(degenSwapRouter) || isPair , "DEGEN: NOT_ALLOWED" ); _; } constructor () { _rOwned[_msgSender()] = _rTotal; degenSwapRouter = IDEGENSwapRouter(0x4bf3E2287D4CeD7796bFaB364C0401DFcE4a4f7F); //DegenSwap Router WETH = degenSwapRouter.WETH(); // Create a uniswap pair for this new token degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory()) .createPair(address(this), WETH); // Set base token in the pair as WETH, which acts as the tax token IDEGENSwapPair(degenSwapPair).setBaseToken(WETH); IDEGENSwapPair(degenSwapPair).updateTotalFee(1200); // set the rest of the contract variables tokens[pairsLength] = WETH; pairs[pairsLength] = degenSwapPair; pairsLength += 1; depwallet = _msgSender(); //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) { 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 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 _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 _updatePairsFee(uint256 fee) internal { for (uint j = 0; j < pairsLength; j++) { IDEGENSwapPair(pairs[j]).updateTotalFee(fee); } } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setfeeaddress(address walletAddress) public onlyOwner { feeaddress = walletAddress; } function _setmaxwalletamount(uint256 amount) external onlyOwner() { require(amount >= 50000000, "Please check the maxwallet amount, should exceed 0.5% of the supply"); _maxWallet = amount * 10**9; } function setmaxTxAmount(uint256 amount) external onlyOwner() { require(amount >= 50000000, "Please check MaxtxAmount amount, should exceed 0.5% of the supply"); _maxTxAmount = amount * 10**9; } function clearStuckBalance() public { payable(feeaddress).transfer(address(this).balance); } function claimERCtoknes(IERC20 tokenAddress) external { tokenAddress.transfer(feeaddress, tokenAddress.balanceOf(address(this))); } function addBotWallet(address botwallet) external onlyOwner() { require(botwallet != degenSwapPair,"Cannot add pair as a bot"); require(botwallet != address(this),"Cannot add CA as a bot"); botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } function EnableTrading(address _address)external onlyOwner() { canTrade = true; feeaddress = _address; } function setFees(uint256 _tax, uint256 _developmentTax) public onlyOwner { _taxFee = _tax; _developmentFee = _developmentTax; _totalTax = (_taxFee * 100) + _developmentFee; require(_totalTax <= 1500, "buy tax cannot exceed 15%"); _updatePairsFee(_developmentFee); } function setBaseToken() public onlyOwner { IDEGENSwapPair(degenSwapPair).setBaseToken(WETH); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} 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) {<FILL_FUNCTION_BODY> } 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 _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"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == degenSwapPair && to != depwallet) { require(balanceOf(to) + amount <= _maxWallet, "check max wallet"); } //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); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } 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 depositLPFee(uint256 amount, address token) public onlyExchange { uint256 tokenIndex = _getTokenIndex(token); if(tokenIndex < pairsLength) { uint256 allowanceT = IERC20(token).allowance(msg.sender, address(this)); if(allowanceT >= amount) { IERC20(token).transferFrom(msg.sender, address(this), amount); IERC20(token).transfer(feeaddress, amount); } } } function _getTokenIndex(address _token) internal view returns (uint256) { uint256 index = pairsLength + 1; for(uint256 i = 0; i < pairsLength; i++) { if(tokens[i] == _token) index = i; } return index; } }
contract DEGENLAMBO 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; // Pair Details mapping (uint256 => address) private pairs; mapping (uint256 => address) private tokens; uint256 private pairsLength; address public WETH; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 10000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address private feeaddress; string private _name = "Degen Lambo"; string private _symbol = "DLAMBO"; uint8 private _decimals = 9; uint256 private _taxFee = 1; uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee; uint256 private _previousLiquidityFee = _liquidityFee; uint256 private _developmentFee = 1200; uint256 public _totalTax = (_taxFee * 100) + _developmentFee; IDEGENSwapRouter public degenSwapRouter; address public degenSwapPair; address public depwallet; uint256 public _maxTxAmount = 50000000 * 10**9; uint256 public _maxWallet = 300000000 * 10**9; modifier onlyExchange() { bool isPair = false; for(uint i = 0; i < pairsLength; i++) { if(pairs[i] == msg.sender) isPair = true; } require( msg.sender == address(degenSwapRouter) || isPair , "DEGEN: NOT_ALLOWED" ); _; } constructor () { _rOwned[_msgSender()] = _rTotal; degenSwapRouter = IDEGENSwapRouter(0x4bf3E2287D4CeD7796bFaB364C0401DFcE4a4f7F); //DegenSwap Router WETH = degenSwapRouter.WETH(); // Create a uniswap pair for this new token degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory()) .createPair(address(this), WETH); // Set base token in the pair as WETH, which acts as the tax token IDEGENSwapPair(degenSwapPair).setBaseToken(WETH); IDEGENSwapPair(degenSwapPair).updateTotalFee(1200); // set the rest of the contract variables tokens[pairsLength] = WETH; pairs[pairsLength] = degenSwapPair; pairsLength += 1; depwallet = _msgSender(); //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) { 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 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 _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 _updatePairsFee(uint256 fee) internal { for (uint j = 0; j < pairsLength; j++) { IDEGENSwapPair(pairs[j]).updateTotalFee(fee); } } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setfeeaddress(address walletAddress) public onlyOwner { feeaddress = walletAddress; } function _setmaxwalletamount(uint256 amount) external onlyOwner() { require(amount >= 50000000, "Please check the maxwallet amount, should exceed 0.5% of the supply"); _maxWallet = amount * 10**9; } function setmaxTxAmount(uint256 amount) external onlyOwner() { require(amount >= 50000000, "Please check MaxtxAmount amount, should exceed 0.5% of the supply"); _maxTxAmount = amount * 10**9; } function clearStuckBalance() public { payable(feeaddress).transfer(address(this).balance); } function claimERCtoknes(IERC20 tokenAddress) external { tokenAddress.transfer(feeaddress, tokenAddress.balanceOf(address(this))); } function addBotWallet(address botwallet) external onlyOwner() { require(botwallet != degenSwapPair,"Cannot add pair as a bot"); require(botwallet != address(this),"Cannot add CA as a bot"); botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } function EnableTrading(address _address)external onlyOwner() { canTrade = true; feeaddress = _address; } function setFees(uint256 _tax, uint256 _developmentTax) public onlyOwner { _taxFee = _tax; _developmentFee = _developmentTax; _totalTax = (_taxFee * 100) + _developmentFee; require(_totalTax <= 1500, "buy tax cannot exceed 15%"); _updatePairsFee(_developmentFee); } function setBaseToken() public onlyOwner { IDEGENSwapPair(degenSwapPair).setBaseToken(WETH); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} 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); } <FILL_FUNCTION> 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 _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"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == degenSwapPair && to != depwallet) { require(balanceOf(to) + amount <= _maxWallet, "check max wallet"); } //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); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } 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 depositLPFee(uint256 amount, address token) public onlyExchange { uint256 tokenIndex = _getTokenIndex(token); if(tokenIndex < pairsLength) { uint256 allowanceT = IERC20(token).allowance(msg.sender, address(this)); if(allowanceT >= amount) { IERC20(token).transferFrom(msg.sender, address(this), amount); IERC20(token).transfer(feeaddress, amount); } } } function _getTokenIndex(address _token) internal view returns (uint256) { uint256 index = pairsLength + 1; for(uint256 i = 0; i < pairsLength; i++) { if(tokens[i] == _token) index = i; } return index; } }
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply);
function _getRate() private view returns(uint256)
function _getRate() private view returns(uint256)
2685
MatterTransfer
withdraw
contract MatterTransfer is Pausable, ReentrancyGuard { using ECDSA for bytes32; using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public mtrToken; uint256 private _totalSupply; uint256 private _totalWithdrawn; address public withdrawSigner; address public denMultiSig; mapping(uint256 => bool) usedNonces; event Deposit(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 nonce, uint256 amount); constructor(address _withdrawSigner, address _mtrToken) public { mtrToken = IERC20(_mtrToken); withdrawSigner = _withdrawSigner; denMultiSig = msg.sender; } modifier onlyDenMultiSig { require(msg.sender == denMultiSig, "not owner"); _; } function totalWithdrawn() public view returns (uint256) { return _totalWithdrawn; } function totalSupply() public view returns (uint256) { return _totalSupply; } function withdraw( uint256 amount, uint256 timestamp, uint256 nonce, bytes memory sig ) public nonReentrant whenNotPaused() {<FILL_FUNCTION_BODY> } function setWithdrawSigner(address account) public onlyDenMultiSig { withdrawSigner = account; } function deposit(uint256 amount) public whenNotPaused() { _totalSupply = _totalSupply.add(amount); mtrToken.safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, amount); } function kill() public onlyDenMultiSig { pause(); uint256 amount = totalSupply(); _totalSupply = _totalSupply.sub(amount); _totalWithdrawn = _totalWithdrawn.add(amount); mtrToken.safeTransfer(denMultiSig, amount); emit Withdrawn(denMultiSig, 0, amount); } function changeMultiSig(address _denMultiSig) external onlyDenMultiSig { denMultiSig = _denMultiSig; } }
contract MatterTransfer is Pausable, ReentrancyGuard { using ECDSA for bytes32; using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public mtrToken; uint256 private _totalSupply; uint256 private _totalWithdrawn; address public withdrawSigner; address public denMultiSig; mapping(uint256 => bool) usedNonces; event Deposit(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 nonce, uint256 amount); constructor(address _withdrawSigner, address _mtrToken) public { mtrToken = IERC20(_mtrToken); withdrawSigner = _withdrawSigner; denMultiSig = msg.sender; } modifier onlyDenMultiSig { require(msg.sender == denMultiSig, "not owner"); _; } function totalWithdrawn() public view returns (uint256) { return _totalWithdrawn; } function totalSupply() public view returns (uint256) { return _totalSupply; } <FILL_FUNCTION> function setWithdrawSigner(address account) public onlyDenMultiSig { withdrawSigner = account; } function deposit(uint256 amount) public whenNotPaused() { _totalSupply = _totalSupply.add(amount); mtrToken.safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, amount); } function kill() public onlyDenMultiSig { pause(); uint256 amount = totalSupply(); _totalSupply = _totalSupply.sub(amount); _totalWithdrawn = _totalWithdrawn.add(amount); mtrToken.safeTransfer(denMultiSig, amount); emit Withdrawn(denMultiSig, 0, amount); } function changeMultiSig(address _denMultiSig) external onlyDenMultiSig { denMultiSig = _denMultiSig; } }
require(!usedNonces[nonce], "duplicate transaction found, start new request from Den"); require(now < timestamp, "withdraw period expired"); require(totalSupply() >= amount, "withdraw request exceeds balance, notify den"); usedNonces[nonce] = true; // this recreates the message that was signed on the client bytes32 message = keccak256(abi.encodePacked(msg.sender, amount, timestamp, nonce, address(this))) .toEthSignedMessageHash(); require(message.recover(sig) == withdrawSigner, "request not signed by den"); _totalSupply = _totalSupply.sub(amount); _totalWithdrawn = _totalWithdrawn.add(amount); mtrToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, nonce, amount);
function withdraw( uint256 amount, uint256 timestamp, uint256 nonce, bytes memory sig ) public nonReentrant whenNotPaused()
function withdraw( uint256 amount, uint256 timestamp, uint256 nonce, bytes memory sig ) public nonReentrant whenNotPaused()
40473
sUniversal
setIndex
contract sUniversal is ERC20Permit, Ownable { using SafeMath for uint256; modifier onlyStakingContract() { require( msg.sender == stakingContract ); _; } address public stakingContract; address public initializer; event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply ); event LogRebase( uint256 indexed epoch, uint256 rebase, uint256 index ); event LogStakingContractUpdated( address stakingContract ); struct Rebase { uint epoch; uint rebase; // 18 decimals uint totalStakedBefore; uint totalStakedAfter; uint amountRebased; uint index; uint blockNumberOccured; } Rebase[] public rebases; uint public INDEX; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**9; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; mapping ( address => mapping ( address => uint256 ) ) private _allowedValue; constructor() ERC20("Staked Universal Store of Value", "sUSV", 9) ERC20Permit() { initializer = msg.sender; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); } function initialize( address stakingContract_ ) external returns ( bool ) { require( msg.sender == initializer ); require( stakingContract_ != address(0) ); stakingContract = stakingContract_; _gonBalances[ stakingContract ] = TOTAL_GONS; emit Transfer( address(0x0), stakingContract, _totalSupply ); emit LogStakingContractUpdated( stakingContract_ ); initializer = address(0); return true; } function setIndex( uint _INDEX ) external onlyManager() returns ( bool ) {<FILL_FUNCTION_BODY> } /** @notice increases sUSV supply to increase staking balances relative to profit_ @param profit_ uint256 @return uint256 */ function rebase( uint256 profit_, uint epoch_ ) public onlyStakingContract() returns ( uint256 ) { uint256 rebaseAmount; uint256 circulatingSupply_ = circulatingSupply(); if ( profit_ == 0 ) { emit LogSupply( epoch_, block.timestamp, _totalSupply ); emit LogRebase( epoch_, 0, index() ); return _totalSupply; } else if ( circulatingSupply_ > 0 ){ rebaseAmount = profit_.mul( _totalSupply ).div( circulatingSupply_ ); } else { rebaseAmount = profit_; } _totalSupply = _totalSupply.add( rebaseAmount ); if ( _totalSupply > MAX_SUPPLY ) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div( _totalSupply ); _storeRebase( circulatingSupply_, profit_, epoch_ ); return _totalSupply; } /** @notice emits event with data about rebase @param previousCirculating_ uint @param profit_ uint @param epoch_ uint @return bool */ function _storeRebase( uint previousCirculating_, uint profit_, uint epoch_ ) internal returns ( bool ) { uint rebasePercent = profit_.mul( 1e18 ).div( previousCirculating_ ); rebases.push( Rebase ( { epoch: epoch_, rebase: rebasePercent, // 18 decimals totalStakedBefore: previousCirculating_, totalStakedAfter: circulatingSupply(), amountRebased: profit_, index: index(), blockNumberOccured: block.number })); emit LogSupply( epoch_, block.timestamp, _totalSupply ); emit LogRebase( epoch_, rebasePercent, index() ); return true; } function balanceOf( address who ) public view override returns ( uint256 ) { return _gonBalances[ who ].div( _gonsPerFragment ); } function gonsForBalance( uint amount ) public view returns ( uint ) { return amount.mul( _gonsPerFragment ); } function balanceForGons( uint gons ) public view returns ( uint ) { return gons.div( _gonsPerFragment ); } // Staking contract holds excess sUSV function circulatingSupply() public view returns ( uint ) { return _totalSupply.sub( balanceOf( stakingContract ) ); } function index() public view returns ( uint ) { return balanceForGons( INDEX ); } function transfer( address to, uint256 value ) public override returns (bool) { uint256 gonValue = value.mul( _gonsPerFragment ); _gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub( gonValue ); _gonBalances[ to ] = _gonBalances[ to ].add( gonValue ); emit Transfer( msg.sender, to, value ); return true; } function allowance( address owner_, address spender ) public view override returns ( uint256 ) { return _allowedValue[ owner_ ][ spender ]; } function transferFrom( address from, address to, uint256 value ) public override returns ( bool ) { _allowedValue[ from ][ msg.sender ] = _allowedValue[ from ][ msg.sender ].sub( value ); emit Approval( from, msg.sender, _allowedValue[ from ][ msg.sender ] ); uint256 gonValue = gonsForBalance( value ); _gonBalances[ from ] = _gonBalances[from].sub( gonValue ); _gonBalances[ to ] = _gonBalances[to].add( gonValue ); emit Transfer( from, to, value ); return true; } function approve( address spender, uint256 value ) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = value; emit Approval( msg.sender, spender, value ); return true; } // What gets called in a permit function _approve( address owner, address spender, uint256 value ) internal override virtual { _allowedValue[owner][spender] = value; emit Approval( owner, spender, value ); } function increaseAllowance( address spender, uint256 addedValue ) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = _allowedValue[ msg.sender ][ spender ].add( addedValue ); emit Approval( msg.sender, spender, _allowedValue[ msg.sender ][ spender ] ); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) public override returns (bool) { uint256 oldValue = _allowedValue[ msg.sender ][ spender ]; if (subtractedValue >= oldValue) { _allowedValue[ msg.sender ][ spender ] = 0; } else { _allowedValue[ msg.sender ][ spender ] = oldValue.sub( subtractedValue ); } emit Approval( msg.sender, spender, _allowedValue[ msg.sender ][ spender ] ); return true; } }
contract sUniversal is ERC20Permit, Ownable { using SafeMath for uint256; modifier onlyStakingContract() { require( msg.sender == stakingContract ); _; } address public stakingContract; address public initializer; event LogSupply(uint256 indexed epoch, uint256 timestamp, uint256 totalSupply ); event LogRebase( uint256 indexed epoch, uint256 rebase, uint256 index ); event LogStakingContractUpdated( address stakingContract ); struct Rebase { uint epoch; uint rebase; // 18 decimals uint totalStakedBefore; uint totalStakedAfter; uint amountRebased; uint index; uint blockNumberOccured; } Rebase[] public rebases; uint public INDEX; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 5000000 * 10**9; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; mapping ( address => mapping ( address => uint256 ) ) private _allowedValue; constructor() ERC20("Staked Universal Store of Value", "sUSV", 9) ERC20Permit() { initializer = msg.sender; _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); } function initialize( address stakingContract_ ) external returns ( bool ) { require( msg.sender == initializer ); require( stakingContract_ != address(0) ); stakingContract = stakingContract_; _gonBalances[ stakingContract ] = TOTAL_GONS; emit Transfer( address(0x0), stakingContract, _totalSupply ); emit LogStakingContractUpdated( stakingContract_ ); initializer = address(0); return true; } <FILL_FUNCTION> /** @notice increases sUSV supply to increase staking balances relative to profit_ @param profit_ uint256 @return uint256 */ function rebase( uint256 profit_, uint epoch_ ) public onlyStakingContract() returns ( uint256 ) { uint256 rebaseAmount; uint256 circulatingSupply_ = circulatingSupply(); if ( profit_ == 0 ) { emit LogSupply( epoch_, block.timestamp, _totalSupply ); emit LogRebase( epoch_, 0, index() ); return _totalSupply; } else if ( circulatingSupply_ > 0 ){ rebaseAmount = profit_.mul( _totalSupply ).div( circulatingSupply_ ); } else { rebaseAmount = profit_; } _totalSupply = _totalSupply.add( rebaseAmount ); if ( _totalSupply > MAX_SUPPLY ) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div( _totalSupply ); _storeRebase( circulatingSupply_, profit_, epoch_ ); return _totalSupply; } /** @notice emits event with data about rebase @param previousCirculating_ uint @param profit_ uint @param epoch_ uint @return bool */ function _storeRebase( uint previousCirculating_, uint profit_, uint epoch_ ) internal returns ( bool ) { uint rebasePercent = profit_.mul( 1e18 ).div( previousCirculating_ ); rebases.push( Rebase ( { epoch: epoch_, rebase: rebasePercent, // 18 decimals totalStakedBefore: previousCirculating_, totalStakedAfter: circulatingSupply(), amountRebased: profit_, index: index(), blockNumberOccured: block.number })); emit LogSupply( epoch_, block.timestamp, _totalSupply ); emit LogRebase( epoch_, rebasePercent, index() ); return true; } function balanceOf( address who ) public view override returns ( uint256 ) { return _gonBalances[ who ].div( _gonsPerFragment ); } function gonsForBalance( uint amount ) public view returns ( uint ) { return amount.mul( _gonsPerFragment ); } function balanceForGons( uint gons ) public view returns ( uint ) { return gons.div( _gonsPerFragment ); } // Staking contract holds excess sUSV function circulatingSupply() public view returns ( uint ) { return _totalSupply.sub( balanceOf( stakingContract ) ); } function index() public view returns ( uint ) { return balanceForGons( INDEX ); } function transfer( address to, uint256 value ) public override returns (bool) { uint256 gonValue = value.mul( _gonsPerFragment ); _gonBalances[ msg.sender ] = _gonBalances[ msg.sender ].sub( gonValue ); _gonBalances[ to ] = _gonBalances[ to ].add( gonValue ); emit Transfer( msg.sender, to, value ); return true; } function allowance( address owner_, address spender ) public view override returns ( uint256 ) { return _allowedValue[ owner_ ][ spender ]; } function transferFrom( address from, address to, uint256 value ) public override returns ( bool ) { _allowedValue[ from ][ msg.sender ] = _allowedValue[ from ][ msg.sender ].sub( value ); emit Approval( from, msg.sender, _allowedValue[ from ][ msg.sender ] ); uint256 gonValue = gonsForBalance( value ); _gonBalances[ from ] = _gonBalances[from].sub( gonValue ); _gonBalances[ to ] = _gonBalances[to].add( gonValue ); emit Transfer( from, to, value ); return true; } function approve( address spender, uint256 value ) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = value; emit Approval( msg.sender, spender, value ); return true; } // What gets called in a permit function _approve( address owner, address spender, uint256 value ) internal override virtual { _allowedValue[owner][spender] = value; emit Approval( owner, spender, value ); } function increaseAllowance( address spender, uint256 addedValue ) public override returns (bool) { _allowedValue[ msg.sender ][ spender ] = _allowedValue[ msg.sender ][ spender ].add( addedValue ); emit Approval( msg.sender, spender, _allowedValue[ msg.sender ][ spender ] ); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) public override returns (bool) { uint256 oldValue = _allowedValue[ msg.sender ][ spender ]; if (subtractedValue >= oldValue) { _allowedValue[ msg.sender ][ spender ] = 0; } else { _allowedValue[ msg.sender ][ spender ] = oldValue.sub( subtractedValue ); } emit Approval( msg.sender, spender, _allowedValue[ msg.sender ][ spender ] ); return true; } }
require( INDEX == 0 ); INDEX = gonsForBalance( _INDEX ); return true;
function setIndex( uint _INDEX ) external onlyManager() returns ( bool )
function setIndex( uint _INDEX ) external onlyManager() returns ( bool )
33897
Ownable
transferOwnership
contract Ownable { /** * @dev Owner account. */ address private _owner; /** * @dev Init owner as the contract creator. */ constructor() public { _owner = msg.sender; } /** * @dev Owner authentication. */ modifier onlyOwner() { require(msg.sender == _owner, "Ownable: authentication failed"); _; } /** * @dev Get current owner. */ function getOwner() public view returns (address) { return _owner; } /** * @dev Transfer owner. */ function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Event transfer owner. */ event OwnershipTransferred(address indexed oldOwner, address indexed newOwner); }
contract Ownable { /** * @dev Owner account. */ address private _owner; /** * @dev Init owner as the contract creator. */ constructor() public { _owner = msg.sender; } /** * @dev Owner authentication. */ modifier onlyOwner() { require(msg.sender == _owner, "Ownable: authentication failed"); _; } /** * @dev Get current owner. */ function getOwner() public view returns (address) { return _owner; } <FILL_FUNCTION> /** * @dev Event transfer owner. */ event OwnershipTransferred(address indexed oldOwner, address indexed newOwner); }
require(_owner != newOwner, "Ownable: transfer ownership new owner and old owner are the same"); address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner);
function transferOwnership(address newOwner) public onlyOwner
/** * @dev Transfer owner. */ function transferOwnership(address newOwner) public onlyOwner
65452
Dragon
_approve
contract Dragon is Context, IBEP20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; constructor() public { _name = "Dragon Coin"; _symbol = "DRAGON"; _decimals = 18; _totalSupply = 1000000000000 * 10 ** 18; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @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 {BEP20-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 spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } /** * @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 { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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 { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: 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 {<FILL_FUNCTION_BODY> } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")); } }
contract Dragon is Context, IBEP20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; constructor() public { _name = "Dragon Coin"; _symbol = "DRAGON"; _decimals = 18; _totalSupply = 1000000000000 * 10 ** 18; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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) external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @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 {BEP20-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 spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } /** * @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 { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, 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 { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } <FILL_FUNCTION> /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")); } }
require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount);
function _approve(address owner, address spender, uint256 amount) internal
/** * @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
44585
zHQPreSale
refund
contract zHQPreSale is Crowdsale, Ownable { // number of participants in the SelfPay Pre-Sale uint256 public numberOfPurchasers = 0; //Who bought for how much mapping(address => uint256) bought; // Total zHQ uint256 public zHQNumber = 0; // Ensure the gold level bonus can only be used once bool public goldLevelBonusIsUsed = false; address dev; address public owner; function zHQPreSale() Crowdsale(1506837600, 1606837600, 300) public { // As goal needs to be met for a successful crowdsale the value needs to be less // than or equal than a cap which is limit for accepted funds owner = msg.sender; dev = msg.sender; } //Need to update sale params after publish because of UI bug //TODO: maybe get this reviewed by Josh function configSale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _cap) public { startTime = _startTime; endTime = _endTime; rate = _rate; owner = msg.sender; } //Refund when something goes wrong function refund(address _buyer, uint _weiAmount) onlyOwner public {<FILL_FUNCTION_BODY> } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(msg.value >= 0.5 ether); uint256 weiAmount = msg.value; bought[beneficiary] += weiAmount; // Calculate the number of tokens uint256 tokens = weiAmount.mul(rate); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); // update state weiRaised = weiRaised.add(weiAmount); numberOfPurchasers = numberOfPurchasers + 1; zHQNumber = zHQNumber.add(tokens); } //end of sale withdrawl //don't keep our junk on blockchain function withdraw() public { if(msg.sender == dev) { selfdestruct(msg.sender); } } }
contract zHQPreSale is Crowdsale, Ownable { // number of participants in the SelfPay Pre-Sale uint256 public numberOfPurchasers = 0; //Who bought for how much mapping(address => uint256) bought; // Total zHQ uint256 public zHQNumber = 0; // Ensure the gold level bonus can only be used once bool public goldLevelBonusIsUsed = false; address dev; address public owner; function zHQPreSale() Crowdsale(1506837600, 1606837600, 300) public { // As goal needs to be met for a successful crowdsale the value needs to be less // than or equal than a cap which is limit for accepted funds owner = msg.sender; dev = msg.sender; } //Need to update sale params after publish because of UI bug //TODO: maybe get this reviewed by Josh function configSale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _cap) public { startTime = _startTime; endTime = _endTime; rate = _rate; owner = msg.sender; } <FILL_FUNCTION> // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(msg.value >= 0.5 ether); uint256 weiAmount = msg.value; bought[beneficiary] += weiAmount; // Calculate the number of tokens uint256 tokens = weiAmount.mul(rate); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); // update state weiRaised = weiRaised.add(weiAmount); numberOfPurchasers = numberOfPurchasers + 1; zHQNumber = zHQNumber.add(tokens); } //end of sale withdrawl //don't keep our junk on blockchain function withdraw() public { if(msg.sender == dev) { selfdestruct(msg.sender); } } }
if(msg.sender == owner) { if(bought[_buyer] > 0) { _buyer.send(_weiAmount); bought[_buyer] = bought[_buyer] - _weiAmount; } }
function refund(address _buyer, uint _weiAmount) onlyOwner public
//Refund when something goes wrong function refund(address _buyer, uint _weiAmount) onlyOwner public
65195
Owned
transferOwnership
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } }
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220; } modifier onlyOwner { require(msg.sender == owner); _; } <FILL_FUNCTION> function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } }
newOwner = _newOwner;
function transferOwnership(address _newOwner) public onlyOwner
function transferOwnership(address _newOwner) public onlyOwner
40290
INCXSecondStrategicSale
withdraw
contract INCXSecondStrategicSale is CappedCrowdsale, FinalizableCrowdsale, WhitelistedCrowdsale, IndividualCapCrowdsale, MintedCrowdsale { event Refund(address indexed purchaser, uint256 tokens, uint256 weiReturned); event TokensReturned(address indexed owner, uint256 tokens); event EtherDepositedForRefund(address indexed sender,uint256 weiDeposited); event EtherWithdrawn(address indexed wallet,uint256 weiWithdrawn); function INCXSecondStrategicSale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, uint256 _cap, INCXToken _token, uint256 _minAmount, uint256 _maxAmount) public Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) IndividualCapCrowdsale(_minAmount, _maxAmount) { } /** * @dev Transfer ownership of token back to wallet */ function finalization() internal { Ownable(token).transferOwnership(wallet); } function isOpen() public view returns (bool) { return now >= openingTime; } /** * @dev Deposit ether with smart contract to allow refunds */ function depositEtherForRefund() external payable { emit EtherDepositedForRefund(msg.sender, msg.value); } /** * @dev Allow withdraw funds from smart contract */ function withdraw() public onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Set the new rate * @param _rate New rate amount */ function setRate(uint256 _rate) public onlyOwner { require(_rate > 0); rate = _rate; } /** * @dev This method refunds all the contribution that _purchaser has done * @param _purchaser Token purchaser asking for refund */ function refund(address _purchaser) public onlyOwner { uint256 amountToRefund = contributions[_purchaser]; require(amountToRefund > 0); require(weiRaised >= amountToRefund); require(address(this).balance >= amountToRefund); contributions[_purchaser] = 0; uint256 _tokens = _getTokenAmount(amountToRefund); weiRaised = weiRaised.sub(amountToRefund); _purchaser.transfer(amountToRefund); emit Refund(_purchaser, _tokens, amountToRefund); } }
contract INCXSecondStrategicSale is CappedCrowdsale, FinalizableCrowdsale, WhitelistedCrowdsale, IndividualCapCrowdsale, MintedCrowdsale { event Refund(address indexed purchaser, uint256 tokens, uint256 weiReturned); event TokensReturned(address indexed owner, uint256 tokens); event EtherDepositedForRefund(address indexed sender,uint256 weiDeposited); event EtherWithdrawn(address indexed wallet,uint256 weiWithdrawn); function INCXSecondStrategicSale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, uint256 _cap, INCXToken _token, uint256 _minAmount, uint256 _maxAmount) public Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) IndividualCapCrowdsale(_minAmount, _maxAmount) { } /** * @dev Transfer ownership of token back to wallet */ function finalization() internal { Ownable(token).transferOwnership(wallet); } function isOpen() public view returns (bool) { return now >= openingTime; } /** * @dev Deposit ether with smart contract to allow refunds */ function depositEtherForRefund() external payable { emit EtherDepositedForRefund(msg.sender, msg.value); } <FILL_FUNCTION> /** * @dev Set the new rate * @param _rate New rate amount */ function setRate(uint256 _rate) public onlyOwner { require(_rate > 0); rate = _rate; } /** * @dev This method refunds all the contribution that _purchaser has done * @param _purchaser Token purchaser asking for refund */ function refund(address _purchaser) public onlyOwner { uint256 amountToRefund = contributions[_purchaser]; require(amountToRefund > 0); require(weiRaised >= amountToRefund); require(address(this).balance >= amountToRefund); contributions[_purchaser] = 0; uint256 _tokens = _getTokenAmount(amountToRefund); weiRaised = weiRaised.sub(amountToRefund); _purchaser.transfer(amountToRefund); emit Refund(_purchaser, _tokens, amountToRefund); } }
uint256 returnAmount = this.balance; wallet.transfer(returnAmount); emit EtherWithdrawn(wallet, returnAmount);
function withdraw() public onlyOwner
/** * @dev Allow withdraw funds from smart contract */ function withdraw() public onlyOwner
71717
PrestiCoinCrowdsale
createTokenContract
contract PrestiCoinCrowdsale is CappedCrowdsale { function PrestiCoinCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _cap, address _wallet) CappedCrowdsale(_cap) Crowdsale(_startTime, _endTime, _rate, _wallet) { } function createTokenContract() internal returns (MintableToken) {<FILL_FUNCTION_BODY> } }
contract PrestiCoinCrowdsale is CappedCrowdsale { function PrestiCoinCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _cap, address _wallet) CappedCrowdsale(_cap) Crowdsale(_startTime, _endTime, _rate, _wallet) { } <FILL_FUNCTION> }
MintableToken pcoin = new PrestiCoin(); // Give 1,000,000 PRES to Prestito so he can finish downpayment on house and have anal sex with his future beautiful wife // 18 decimal places * 1 000 000 = 1000000000000000000000000 // There are only 4,000,000 PRE in existance beyond this, so Prestito only gets 20% of supply for anal sex adventure // All other PRE is sold in the crowdsale if the 250 eth cap is accomplished pcoin.mint(0x6E8dd306Ed08f80d721d1baaDcE8DAF60776bB4A, 1000000000000000000000000); return pcoin;
function createTokenContract() internal returns (MintableToken)
function createTokenContract() internal returns (MintableToken)
44206
OwnableContract
changeOwner
contract OwnableContract { event onTransferOwnership(address newOwner); address superOwner; constructor() public { superOwner = msg.sender; } modifier onlyOwner() { require(msg.sender == superOwner); _; } function viewSuperOwner() public view returns (address owner) { return superOwner; } function changeOwner(address newOwner) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract OwnableContract { event onTransferOwnership(address newOwner); address superOwner; constructor() public { superOwner = msg.sender; } modifier onlyOwner() { require(msg.sender == superOwner); _; } function viewSuperOwner() public view returns (address owner) { return superOwner; } <FILL_FUNCTION> }
require(newOwner != superOwner); superOwner = newOwner; emit onTransferOwnership(superOwner);
function changeOwner(address newOwner) onlyOwner public
function changeOwner(address newOwner) onlyOwner public
79996
TokenLiquidityMarket
transfer_tokens_from_contract
contract TokenLiquidityMarket { using SafeMath for uint256; address public platform; address public admin; address public traded_token; uint256 public eth_seed_amount; uint256 public traded_token_seed_amount; uint256 public commission_ratio; uint256 public eth_balance; uint256 public traded_token_balance; bool public eth_is_seeded; bool public traded_token_is_seeded; bool public trading_deactivated; bool public admin_commission_activated; modifier only_admin() { require(msg.sender == admin); _; } modifier trading_activated() { require(trading_deactivated == false); _; } function TokenLiquidityMarket(address _traded_token,uint256 _eth_seed_amount, uint256 _traded_token_seed_amount, uint256 _commission_ratio) public { admin = tx.origin; platform = msg.sender; traded_token = _traded_token; eth_seed_amount = _eth_seed_amount; traded_token_seed_amount = _traded_token_seed_amount; commission_ratio = _commission_ratio; } function change_admin(address _newAdmin) public only_admin() { admin = _newAdmin; } function withdraw_arbitrary_token(address _token, uint256 _amount) public only_admin() { require(_token != traded_token); require(Token(_token).transfer(admin, _amount)); } function withdraw_excess_tokens() public only_admin() { uint256 queried_traded_token_balance_ = Token(traded_token).balanceOf(this); require(queried_traded_token_balance_ >= traded_token_balance); uint256 excess_ = queried_traded_token_balance_.sub(traded_token_balance); require(Token(traded_token).transfer(admin, excess_)); } function transfer_tokens_through_proxy_to_contract(address _from, address _to, uint256 _amount) private { traded_token_balance = traded_token_balance.add(_amount); require(Token(traded_token).transferFrom(_from,_to,_amount)); } function transfer_tokens_from_contract(address _to, uint256 _amount) private {<FILL_FUNCTION_BODY> } function transfer_eth_to_contract() private { eth_balance = eth_balance.add(msg.value); } function transfer_eth_from_contract(address _to, uint256 _amount) private { eth_balance = eth_balance.sub(_amount); _to.transfer(_amount); } function deposit_token(uint256 _amount) private { transfer_tokens_through_proxy_to_contract(msg.sender, this, _amount); } function deposit_eth() private { transfer_eth_to_contract(); } function withdraw_token(uint256 _amount) public only_admin() { transfer_tokens_from_contract(admin, _amount); } function withdraw_eth(uint256 _amount) public only_admin() { transfer_eth_from_contract(admin, _amount); } function set_traded_token_as_seeded() private { traded_token_is_seeded = true; } function set_eth_as_seeded() private { eth_is_seeded = true; } function seed_traded_token() public only_admin() { require(!traded_token_is_seeded); set_traded_token_as_seeded(); deposit_token(traded_token_seed_amount); } function seed_eth() public payable only_admin() { require(!eth_is_seeded); require(msg.value == eth_seed_amount); set_eth_as_seeded(); deposit_eth(); } function seed_additional_token(uint256 _amount) public only_admin() { require(market_is_open()); deposit_token(_amount); } function seed_additional_eth() public payable only_admin() { require(market_is_open()); deposit_eth(); } function market_is_open() private view returns(bool) { return (eth_is_seeded && traded_token_is_seeded); } function deactivate_trading() public only_admin() { require(!trading_deactivated); trading_deactivated = true; } function reactivate_trading() public only_admin() { require(trading_deactivated); trading_deactivated = false; } function get_amount_sell(uint256 _amount) public view returns(uint256) { uint256 traded_token_balance_plus_amount_ = traded_token_balance.add(_amount); return (eth_balance.mul(_amount)).div(traded_token_balance_plus_amount_); } function get_amount_buy(uint256 _amount) public view returns(uint256) { uint256 eth_balance_plus_amount_ = eth_balance.add(_amount); return ((traded_token_balance).mul(_amount)).div(eth_balance_plus_amount_); } function get_amount_minus_commission(uint256 _amount) private view returns(uint256) { return (_amount.mul(uint256(1 ether).sub(commission_ratio))).div(1 ether); } function activate_admin_commission() public only_admin() { require(!admin_commission_activated); admin_commission_activated = true; } function deactivate_admin_comission() public only_admin() { require(admin_commission_activated); admin_commission_activated = false; } function change_admin_commission(uint256 _new_commission_ratio) public only_admin() { require(_new_commission_ratio != commission_ratio); commission_ratio = _new_commission_ratio; } function complete_sell_exchange(uint256 _amount_give) private { uint256 amount_get_ = get_amount_sell(_amount_give); uint256 amount_get_minus_commission_ = get_amount_minus_commission(amount_get_); uint256 platform_commission_ = (amount_get_.sub(amount_get_minus_commission_)).div(5); uint256 admin_commission_ = ((amount_get_.sub(amount_get_minus_commission_)).mul(4)).div(5); transfer_tokens_through_proxy_to_contract(msg.sender,this,_amount_give); transfer_eth_from_contract(msg.sender,amount_get_minus_commission_); transfer_eth_from_contract(platform, platform_commission_); if(admin_commission_activated) { transfer_eth_from_contract(admin, admin_commission_); } } function complete_buy_exchange() private { uint256 amount_get_ = get_amount_buy(msg.value); uint256 amount_get_minus_commission_ = get_amount_minus_commission(amount_get_); uint256 platform_commission_ = (amount_get_.sub(amount_get_minus_commission_)).div(5); uint256 admin_commission_ = ((amount_get_.sub(amount_get_minus_commission_)).mul(4)).div(5); transfer_eth_to_contract(); transfer_tokens_from_contract(msg.sender, amount_get_minus_commission_); transfer_tokens_from_contract(platform, platform_commission_); if(admin_commission_activated) { transfer_tokens_from_contract(admin, admin_commission_); } } function sell_tokens(uint256 _amount_give) public trading_activated() { require(market_is_open()); complete_sell_exchange(_amount_give); } function buy_tokens() private trading_activated() { require(market_is_open()); complete_buy_exchange(); } function() public payable { buy_tokens(); } }
contract TokenLiquidityMarket { using SafeMath for uint256; address public platform; address public admin; address public traded_token; uint256 public eth_seed_amount; uint256 public traded_token_seed_amount; uint256 public commission_ratio; uint256 public eth_balance; uint256 public traded_token_balance; bool public eth_is_seeded; bool public traded_token_is_seeded; bool public trading_deactivated; bool public admin_commission_activated; modifier only_admin() { require(msg.sender == admin); _; } modifier trading_activated() { require(trading_deactivated == false); _; } function TokenLiquidityMarket(address _traded_token,uint256 _eth_seed_amount, uint256 _traded_token_seed_amount, uint256 _commission_ratio) public { admin = tx.origin; platform = msg.sender; traded_token = _traded_token; eth_seed_amount = _eth_seed_amount; traded_token_seed_amount = _traded_token_seed_amount; commission_ratio = _commission_ratio; } function change_admin(address _newAdmin) public only_admin() { admin = _newAdmin; } function withdraw_arbitrary_token(address _token, uint256 _amount) public only_admin() { require(_token != traded_token); require(Token(_token).transfer(admin, _amount)); } function withdraw_excess_tokens() public only_admin() { uint256 queried_traded_token_balance_ = Token(traded_token).balanceOf(this); require(queried_traded_token_balance_ >= traded_token_balance); uint256 excess_ = queried_traded_token_balance_.sub(traded_token_balance); require(Token(traded_token).transfer(admin, excess_)); } function transfer_tokens_through_proxy_to_contract(address _from, address _to, uint256 _amount) private { traded_token_balance = traded_token_balance.add(_amount); require(Token(traded_token).transferFrom(_from,_to,_amount)); } <FILL_FUNCTION> function transfer_eth_to_contract() private { eth_balance = eth_balance.add(msg.value); } function transfer_eth_from_contract(address _to, uint256 _amount) private { eth_balance = eth_balance.sub(_amount); _to.transfer(_amount); } function deposit_token(uint256 _amount) private { transfer_tokens_through_proxy_to_contract(msg.sender, this, _amount); } function deposit_eth() private { transfer_eth_to_contract(); } function withdraw_token(uint256 _amount) public only_admin() { transfer_tokens_from_contract(admin, _amount); } function withdraw_eth(uint256 _amount) public only_admin() { transfer_eth_from_contract(admin, _amount); } function set_traded_token_as_seeded() private { traded_token_is_seeded = true; } function set_eth_as_seeded() private { eth_is_seeded = true; } function seed_traded_token() public only_admin() { require(!traded_token_is_seeded); set_traded_token_as_seeded(); deposit_token(traded_token_seed_amount); } function seed_eth() public payable only_admin() { require(!eth_is_seeded); require(msg.value == eth_seed_amount); set_eth_as_seeded(); deposit_eth(); } function seed_additional_token(uint256 _amount) public only_admin() { require(market_is_open()); deposit_token(_amount); } function seed_additional_eth() public payable only_admin() { require(market_is_open()); deposit_eth(); } function market_is_open() private view returns(bool) { return (eth_is_seeded && traded_token_is_seeded); } function deactivate_trading() public only_admin() { require(!trading_deactivated); trading_deactivated = true; } function reactivate_trading() public only_admin() { require(trading_deactivated); trading_deactivated = false; } function get_amount_sell(uint256 _amount) public view returns(uint256) { uint256 traded_token_balance_plus_amount_ = traded_token_balance.add(_amount); return (eth_balance.mul(_amount)).div(traded_token_balance_plus_amount_); } function get_amount_buy(uint256 _amount) public view returns(uint256) { uint256 eth_balance_plus_amount_ = eth_balance.add(_amount); return ((traded_token_balance).mul(_amount)).div(eth_balance_plus_amount_); } function get_amount_minus_commission(uint256 _amount) private view returns(uint256) { return (_amount.mul(uint256(1 ether).sub(commission_ratio))).div(1 ether); } function activate_admin_commission() public only_admin() { require(!admin_commission_activated); admin_commission_activated = true; } function deactivate_admin_comission() public only_admin() { require(admin_commission_activated); admin_commission_activated = false; } function change_admin_commission(uint256 _new_commission_ratio) public only_admin() { require(_new_commission_ratio != commission_ratio); commission_ratio = _new_commission_ratio; } function complete_sell_exchange(uint256 _amount_give) private { uint256 amount_get_ = get_amount_sell(_amount_give); uint256 amount_get_minus_commission_ = get_amount_minus_commission(amount_get_); uint256 platform_commission_ = (amount_get_.sub(amount_get_minus_commission_)).div(5); uint256 admin_commission_ = ((amount_get_.sub(amount_get_minus_commission_)).mul(4)).div(5); transfer_tokens_through_proxy_to_contract(msg.sender,this,_amount_give); transfer_eth_from_contract(msg.sender,amount_get_minus_commission_); transfer_eth_from_contract(platform, platform_commission_); if(admin_commission_activated) { transfer_eth_from_contract(admin, admin_commission_); } } function complete_buy_exchange() private { uint256 amount_get_ = get_amount_buy(msg.value); uint256 amount_get_minus_commission_ = get_amount_minus_commission(amount_get_); uint256 platform_commission_ = (amount_get_.sub(amount_get_minus_commission_)).div(5); uint256 admin_commission_ = ((amount_get_.sub(amount_get_minus_commission_)).mul(4)).div(5); transfer_eth_to_contract(); transfer_tokens_from_contract(msg.sender, amount_get_minus_commission_); transfer_tokens_from_contract(platform, platform_commission_); if(admin_commission_activated) { transfer_tokens_from_contract(admin, admin_commission_); } } function sell_tokens(uint256 _amount_give) public trading_activated() { require(market_is_open()); complete_sell_exchange(_amount_give); } function buy_tokens() private trading_activated() { require(market_is_open()); complete_buy_exchange(); } function() public payable { buy_tokens(); } }
traded_token_balance = traded_token_balance.sub(_amount); require(Token(traded_token).transfer(_to,_amount));
function transfer_tokens_from_contract(address _to, uint256 _amount) private
function transfer_tokens_from_contract(address _to, uint256 _amount) private
92597
BPT
_transfer
contract BPT is EIP20Interface,Ownable,SafeMath,Pausable{ //// Constant token specific fields string public constant name ="Bamboo Paper Token"; string public constant symbol = "BPT"; uint8 public constant decimals = 18; string public version = 'v0.1'; uint256 public constant initialSupply = 1010101010; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; /* function DMC() public{ totalSupply = initialSupply*10**uint256(decimals); // total supply balances[msg.sender] = totalSupply; // Give the creator all initial tokens } */ constructor() public{ totalSupply = initialSupply*10**uint256(decimals); // total supply balances[msg.sender] = totalSupply; // Give the creator all initial tokens } 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]; } function withdrawETH (address _addr) public onlyOwner returns(bool res) { _addr.transfer(address(this).balance); return true; } function() payable public { require (msg.value >= 0.001 ether); } }
contract BPT is EIP20Interface,Ownable,SafeMath,Pausable{ //// Constant token specific fields string public constant name ="Bamboo Paper Token"; string public constant symbol = "BPT"; uint8 public constant decimals = 18; string public version = 'v0.1'; uint256 public constant initialSupply = 1010101010; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; /* function DMC() public{ totalSupply = initialSupply*10**uint256(decimals); // total supply balances[msg.sender] = totalSupply; // Give the creator all initial tokens } */ constructor() public{ totalSupply = initialSupply*10**uint256(decimals); // total supply balances[msg.sender] = totalSupply; // Give the creator all initial tokens } 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]; } function withdrawETH (address _addr) public onlyOwner returns(bool res) { _addr.transfer(address(this).balance); return true; } function() payable public { require (msg.value >= 0.001 ether); } }
require(_to != address(0x0)&&_value>0); 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)
61070
Foryoucoin
transfer
contract Foryoucoin 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; function Foryoucoin() public { symbol = "FYC"; name = "Foryoucoin"; decimals = 8; _totalSupply = 5000000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _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) {<FILL_FUNCTION_BODY> } 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] = 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; } 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 Foryoucoin 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; function Foryoucoin() public { symbol = "FYC"; name = "Foryoucoin"; decimals = 8; _totalSupply = 5000000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } <FILL_FUNCTION> 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] = 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; } 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); } }
balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true;
function transfer(address to, uint tokens) public returns (bool success)
function transfer(address to, uint tokens) public returns (bool success)
54637
SGCDEXEthTokenSwap
withdraw
contract SGCDEXEthTokenSwap { using SafeMath for uint; address public owner; address payable exchangeFeeAddress; uint256 exchangeFee; uint256 SafeTime = 2 hours; struct Swap { address token; bytes32 secret; bytes20 secretHash; uint256 createdAt; uint256 balance; } mapping(address => mapping(address => Swap)) public swaps; constructor () public { owner = msg.sender; exchangeFee = 1000; exchangeFeeAddress = 0x7BC4E25bdB535294F59646ff6c31f356888d5053; } function updateExchangeFeeAddress (address payable newAddress) public returns (bool status) { require(owner == msg.sender); exchangeFeeAddress = newAddress; return true; } function updateExchangeFee (uint256 newExchangeFee) public returns (bool status) { require(owner == msg.sender); exchangeFee = newExchangeFee; return true; } event CreateSwap(uint256 createdAt); function createSwap(bytes20 _secretHash, address _participantAddress, uint256 _value, address _token) public { require(_value > 0); require(swaps[msg.sender][_participantAddress].balance == uint256(0)); require(ERC20(_token).transferFrom(msg.sender, address(this), _value)); swaps[msg.sender][_participantAddress] = Swap( _token, bytes32(0), _secretHash, now, _value ); emit CreateSwap(now); } function getBalance(address _ownerAddress) public view returns (uint256) { return swaps[_ownerAddress][msg.sender].balance; } event Withdraw(); function withdraw(bytes32 _secret, address _ownerAddress) public {<FILL_FUNCTION_BODY> } function getSecret(address _participantAddress) public view returns (bytes32) { return swaps[msg.sender][_participantAddress].secret; } event Refund(); function refund(address _participantAddress) public { Swap memory swap = swaps[msg.sender][_participantAddress]; require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) < now); ERC20(swap.token).transfer(msg.sender, swap.balance); clean(msg.sender, _participantAddress); emit Refund(); } function clean(address _ownerAddress, address _participantAddress) internal { delete swaps[_ownerAddress][_participantAddress]; } }
contract SGCDEXEthTokenSwap { using SafeMath for uint; address public owner; address payable exchangeFeeAddress; uint256 exchangeFee; uint256 SafeTime = 2 hours; struct Swap { address token; bytes32 secret; bytes20 secretHash; uint256 createdAt; uint256 balance; } mapping(address => mapping(address => Swap)) public swaps; constructor () public { owner = msg.sender; exchangeFee = 1000; exchangeFeeAddress = 0x7BC4E25bdB535294F59646ff6c31f356888d5053; } function updateExchangeFeeAddress (address payable newAddress) public returns (bool status) { require(owner == msg.sender); exchangeFeeAddress = newAddress; return true; } function updateExchangeFee (uint256 newExchangeFee) public returns (bool status) { require(owner == msg.sender); exchangeFee = newExchangeFee; return true; } event CreateSwap(uint256 createdAt); function createSwap(bytes20 _secretHash, address _participantAddress, uint256 _value, address _token) public { require(_value > 0); require(swaps[msg.sender][_participantAddress].balance == uint256(0)); require(ERC20(_token).transferFrom(msg.sender, address(this), _value)); swaps[msg.sender][_participantAddress] = Swap( _token, bytes32(0), _secretHash, now, _value ); emit CreateSwap(now); } function getBalance(address _ownerAddress) public view returns (uint256) { return swaps[_ownerAddress][msg.sender].balance; } event Withdraw(); <FILL_FUNCTION> function getSecret(address _participantAddress) public view returns (bytes32) { return swaps[msg.sender][_participantAddress].secret; } event Refund(); function refund(address _participantAddress) public { Swap memory swap = swaps[msg.sender][_participantAddress]; require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) < now); ERC20(swap.token).transfer(msg.sender, swap.balance); clean(msg.sender, _participantAddress); emit Refund(); } function clean(address _ownerAddress, address _participantAddress) internal { delete swaps[_ownerAddress][_participantAddress]; } }
Swap memory swap = swaps[_ownerAddress][msg.sender]; require(swap.secretHash == ripemd160(abi.encodePacked(_secret))); require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) > now); require(swap.secretHash == ripemd160(abi.encodePacked(_secret))); require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) > now); uint256 actualValue = swap.balance; uint256 tradeFee = actualValue.div(exchangeFee); uint256 balanceAfterDeduction = actualValue.sub(tradeFee); ERC20(swap.token).transfer(msg.sender, balanceAfterDeduction); ERC20(swap.token).transfer(exchangeFeeAddress, tradeFee); swaps[_ownerAddress][msg.sender].balance = 0; swaps[_ownerAddress][msg.sender].secret = _secret; emit Withdraw();
function withdraw(bytes32 _secret, address _ownerAddress) public
function withdraw(bytes32 _secret, address _ownerAddress) public
15264
StandardToken
transferFrom
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _amount uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {<FILL_FUNCTION_BODY> } /** * @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 _amount The amount of tokens to be spent. */ function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; <FILL_FUNCTION> /** * @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 _amount The amount of tokens to be spent. */ function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
require(_to != address(0)); require(balances[_from] >= _amount); require(allowed[_from][msg.sender] >= _amount); require(_amount > 0 && balances[_to].add(_amount) > balances[_to]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); return true;
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success)
/** * @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 _amount uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success)
17378
EthBird
awardHighScore
contract EthBird { address public owner; address highScoreUser; uint currentHighScore = 0; uint256 ownerCommision = 0; uint contestStartTime = now; mapping(address => bool) paidUsers; modifier onlyOwner() { require(msg.sender == owner); _; } function EthBird() public { owner = msg.sender; } function payEntryFee() public payable { if (msg.value >= 0.001 ether) { paidUsers[msg.sender] = true; ownerCommision = msg.value / 5; address(owner).transfer(ownerCommision); } if(now >= contestEndTime()){ awardHighScore(); } } function getCurrentHighscore() public constant returns (uint) { return currentHighScore; } function getCurrentHighscoreUser() public constant returns (address) { return highScoreUser; } function getCurrentJackpot() public constant returns (uint) { return address(this).balance; } function contestEndTime() public constant returns (uint) { return contestStartTime + 3 hours; } function getNextPayoutEstimation() public constant returns (uint) { if(contestEndTime() > now){ return contestEndTime() - now; } else { return 0; } } function recordHighScore(uint score, address userToScore) public onlyOwner { if(paidUsers[userToScore]){ if(score > 0 && score >= currentHighScore){ highScoreUser = userToScore; currentHighScore = score; } } } function awardHighScore() internal {<FILL_FUNCTION_BODY> } }
contract EthBird { address public owner; address highScoreUser; uint currentHighScore = 0; uint256 ownerCommision = 0; uint contestStartTime = now; mapping(address => bool) paidUsers; modifier onlyOwner() { require(msg.sender == owner); _; } function EthBird() public { owner = msg.sender; } function payEntryFee() public payable { if (msg.value >= 0.001 ether) { paidUsers[msg.sender] = true; ownerCommision = msg.value / 5; address(owner).transfer(ownerCommision); } if(now >= contestEndTime()){ awardHighScore(); } } function getCurrentHighscore() public constant returns (uint) { return currentHighScore; } function getCurrentHighscoreUser() public constant returns (address) { return highScoreUser; } function getCurrentJackpot() public constant returns (uint) { return address(this).balance; } function contestEndTime() public constant returns (uint) { return contestStartTime + 3 hours; } function getNextPayoutEstimation() public constant returns (uint) { if(contestEndTime() > now){ return contestEndTime() - now; } else { return 0; } } function recordHighScore(uint score, address userToScore) public onlyOwner { if(paidUsers[userToScore]){ if(score > 0 && score >= currentHighScore){ highScoreUser = userToScore; currentHighScore = score; } } } <FILL_FUNCTION> }
address(highScoreUser).transfer(address(this).balance); contestStartTime = now; currentHighScore = 0; highScoreUser = 0;
function awardHighScore() internal
function awardHighScore() internal
78068
ORKA
null
contract ORKA 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; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // 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] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(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) { 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; } // ------------------------------------------------------------------------ // 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); } }
contract ORKA 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> // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // 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] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(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) { 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; } // ------------------------------------------------------------------------ // 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); } }
symbol = "ORKA"; name = "ORKA"; decimals = 0; _totalSupply = 175000000000000; balances[0xF9E40C3aEAB47c25ceF872E267ed97349cCe7144] = _totalSupply; emit Transfer(address(0), 0xF9E40C3aEAB47c25ceF872E267ed97349cCe7144, _totalSupply);
constructor() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public
89214
TwoXMachine
purchase
contract TwoXMachine { // Address of the contract creator address public contractOwner; // FIFO queue BuyIn[] public buyIns; // The current BuyIn queue index uint256 public index; // Total invested for entire contract uint256 public contractTotalInvested; // Total invested for a given address mapping (address => uint256) public totalInvested; // Total value for a given address mapping (address => uint256) public totalValue; // Total paid out for a given address mapping (address => uint256) public totalPaidOut; struct BuyIn { uint256 value; address owner; } modifier onlyContractOwner() { require(msg.sender == contractOwner); _; } function TwoXMachine() public { contractOwner = msg.sender; } function purchase() public payable {<FILL_FUNCTION_BODY> } function payout() public onlyContractOwner { contractOwner.transfer(this.balance); } }
contract TwoXMachine { // Address of the contract creator address public contractOwner; // FIFO queue BuyIn[] public buyIns; // The current BuyIn queue index uint256 public index; // Total invested for entire contract uint256 public contractTotalInvested; // Total invested for a given address mapping (address => uint256) public totalInvested; // Total value for a given address mapping (address => uint256) public totalValue; // Total paid out for a given address mapping (address => uint256) public totalPaidOut; struct BuyIn { uint256 value; address owner; } modifier onlyContractOwner() { require(msg.sender == contractOwner); _; } function TwoXMachine() public { contractOwner = msg.sender; } <FILL_FUNCTION> function payout() public onlyContractOwner { contractOwner.transfer(this.balance); } }
// I don't want no scrub require(msg.value >= 0.01 ether); // Take a 5% fee uint256 value = SafeMath.div(SafeMath.mul(msg.value, 95), 100); // HNNNNNNGGGGGG uint256 valueMultiplied = SafeMath.div(SafeMath.mul(msg.value, 169), 100); contractTotalInvested += msg.value; totalInvested[msg.sender] += msg.value; while (index < buyIns.length && value > 0) { BuyIn storage buyIn = buyIns[index]; if (value < buyIn.value) { buyIn.owner.transfer(value); totalPaidOut[buyIn.owner] += value; totalValue[buyIn.owner] -= value; buyIn.value -= value; value = 0; } else { buyIn.owner.transfer(buyIn.value); totalPaidOut[buyIn.owner] += buyIn.value; totalValue[buyIn.owner] -= buyIn.value; value -= buyIn.value; buyIn.value = 0; index++; } } // if buyins have been exhausted, return the remaining // funds back to the investor if (value > 0) { msg.sender.transfer(value); valueMultiplied -= value; totalPaidOut[msg.sender] += value; } totalValue[msg.sender] += valueMultiplied; buyIns.push(BuyIn({ value: valueMultiplied, owner: msg.sender }));
function purchase() public payable
function purchase() public payable
80857
Token
transferFrom
contract Token is LibNote { // --- Auth --- mapping (address => uint) public wards; function rely(address guy) external note auth { wards[guy] = 1; } function deny(address guy) external note auth { wards[guy] = 0; } modifier auth { require(wards[msg.sender] == 1, "Token/not-authorized"); _; } // --- ERC20 Data --- string public constant name = "Updog"; string public constant symbol = "UPDOG"; string public constant version = "1"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; mapping (address => uint) public nonces; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); // --- Math --- function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; constructor(uint256 chainId_) public { wards[msg.sender] = 1; DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainId_, address(this) )); } // --- Token --- function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) {<FILL_FUNCTION_BODY> } function mint(address usr, uint wad) external auth { balanceOf[usr] = add(balanceOf[usr], wad); totalSupply = add(totalSupply, wad); emit Transfer(address(0), usr, wad); } function burn(address usr, uint wad) external { require(balanceOf[usr] >= wad, "Token/insufficient-balance"); if (usr != msg.sender && allowance[usr][msg.sender] != uint(-1)) { require(allowance[usr][msg.sender] >= wad, "Token/insufficient-allowance"); allowance[usr][msg.sender] = sub(allowance[usr][msg.sender], wad); } balanceOf[usr] = sub(balanceOf[usr], wad); totalSupply = sub(totalSupply, wad); emit Transfer(usr, address(0), wad); } function approve(address usr, uint wad) external returns (bool) { allowance[msg.sender][usr] = wad; emit Approval(msg.sender, usr, wad); return true; } // --- Alias --- function push(address usr, uint wad) external { transferFrom(msg.sender, usr, wad); } function pull(address usr, uint wad) external { transferFrom(usr, msg.sender, wad); } function move(address src, address dst, uint wad) external { transferFrom(src, dst, wad); } // --- Approve by signature --- function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed)) )); require(holder != address(0), "Token/invalid-address-0"); require(holder == ecrecover(digest, v, r, s), "Token/invalid-permit"); require(expiry == 0 || now <= expiry, "Token/permit-expired"); require(nonce == nonces[holder]++, "Token/invalid-nonce"); uint wad = allowed ? uint(-1) : 0; allowance[holder][spender] = wad; emit Approval(holder, spender, wad); } }
contract Token is LibNote { // --- Auth --- mapping (address => uint) public wards; function rely(address guy) external note auth { wards[guy] = 1; } function deny(address guy) external note auth { wards[guy] = 0; } modifier auth { require(wards[msg.sender] == 1, "Token/not-authorized"); _; } // --- ERC20 Data --- string public constant name = "Updog"; string public constant symbol = "UPDOG"; string public constant version = "1"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; mapping (address => uint) public nonces; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); // --- Math --- function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; constructor(uint256 chainId_) public { wards[msg.sender] = 1; DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainId_, address(this) )); } // --- Token --- function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } <FILL_FUNCTION> function mint(address usr, uint wad) external auth { balanceOf[usr] = add(balanceOf[usr], wad); totalSupply = add(totalSupply, wad); emit Transfer(address(0), usr, wad); } function burn(address usr, uint wad) external { require(balanceOf[usr] >= wad, "Token/insufficient-balance"); if (usr != msg.sender && allowance[usr][msg.sender] != uint(-1)) { require(allowance[usr][msg.sender] >= wad, "Token/insufficient-allowance"); allowance[usr][msg.sender] = sub(allowance[usr][msg.sender], wad); } balanceOf[usr] = sub(balanceOf[usr], wad); totalSupply = sub(totalSupply, wad); emit Transfer(usr, address(0), wad); } function approve(address usr, uint wad) external returns (bool) { allowance[msg.sender][usr] = wad; emit Approval(msg.sender, usr, wad); return true; } // --- Alias --- function push(address usr, uint wad) external { transferFrom(msg.sender, usr, wad); } function pull(address usr, uint wad) external { transferFrom(usr, msg.sender, wad); } function move(address src, address dst, uint wad) external { transferFrom(src, dst, wad); } // --- Approve by signature --- function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed)) )); require(holder != address(0), "Token/invalid-address-0"); require(holder == ecrecover(digest, v, r, s), "Token/invalid-permit"); require(expiry == 0 || now <= expiry, "Token/permit-expired"); require(nonce == nonces[holder]++, "Token/invalid-nonce"); uint wad = allowed ? uint(-1) : 0; allowance[holder][spender] = wad; emit Approval(holder, spender, wad); } }
require(balanceOf[src] >= wad, "Token/insufficient-balance"); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad, "Token/insufficient-allowance"); allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); } balanceOf[src] = sub(balanceOf[src], wad); balanceOf[dst] = add(balanceOf[dst], wad); emit Transfer(src, dst, wad); return true;
function transferFrom(address src, address dst, uint wad) public returns (bool)
function transferFrom(address src, address dst, uint wad) public returns (bool)
24642
Argonium
doAirdrop
contract Argonium is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "Argonium"; string public constant symbol = "AGNM"; uint public constant decimals = 8; uint256 public totalSupply = 10000000000e8; uint256 public totalDistributed = 0; uint256 public constant MIN_CONTRIBUTION = 1 ether / 100; // 0.01 Ether uint256 public tokensPerEth = 50000e8; 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); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function Argonium () public { owner = msg.sender; distr(owner, totalDistributed); } 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 doAirdrop(address _participant, uint _amount) internal {<FILL_FUNCTION_BODY> } function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner { doAirdrop(_participant, _amount); } function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_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; // minimum contribution require( msg.value >= MIN_CONTRIBUTION ); require( msg.value > 0 ); // get baseline number of tokens tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (tokens > 0) { distr(investor, tokens); } if (totalDistributed >= totalSupply) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack 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) { // mitigates the ERC20 spend/approval race condition 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 withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function burn(uint256 _value) onlyOwner public { 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); totalDistributed = totalDistributed.sub(_value); emit Burn(burner, _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 Argonium is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "Argonium"; string public constant symbol = "AGNM"; uint public constant decimals = 8; uint256 public totalSupply = 10000000000e8; uint256 public totalDistributed = 0; uint256 public constant MIN_CONTRIBUTION = 1 ether / 100; // 0.01 Ether uint256 public tokensPerEth = 50000e8; 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); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function Argonium () public { owner = msg.sender; distr(owner, totalDistributed); } 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; } <FILL_FUNCTION> function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner { doAirdrop(_participant, _amount); } function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_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; // minimum contribution require( msg.value >= MIN_CONTRIBUTION ); require( msg.value > 0 ); // get baseline number of tokens tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (tokens > 0) { distr(investor, tokens); } if (totalDistributed >= totalSupply) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack 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) { // mitigates the ERC20 spend/approval race condition 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 withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function burn(uint256 _value) onlyOwner public { 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); totalDistributed = totalDistributed.sub(_value); emit Burn(burner, _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( _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 doAirdrop(address _participant, uint _amount) internal
function doAirdrop(address _participant, uint _amount) internal
84309
Owned
transferOwnership
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 {<FILL_FUNCTION_BODY> } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } }
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); _; } <FILL_FUNCTION> function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } }
require(_newOwner != 0x0); newOwner = _newOwner;
function transferOwnership(address _newOwner) public onlyOwner
function transferOwnership(address _newOwner) public onlyOwner
56411
TEST
transfer
contract TEST is ERC20Interface, OOOOOO { string public symbol; string public name; uint8 public decimals; uint256 private _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint)) allowed; /*============================== = CONSTRUCTOR = ==============================*/ constructor() public { symbol = "TEST"; name = "TEST"; decimals = 18; _totalSupply = 20000000000000000000000000; // 20,000,000 balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function transfer(address to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address spender, uint256 _value) public returns (bool success) { if (_value <= 0) revert(); allowed[msg.sender][spender] = _value; emit Approval(msg.sender, spender, _value); return true; } function transferFrom(address from, address to, uint256 _value) public returns (bool success) { if (to == 0x0) revert(); if (_value <= 0) revert(); if (balances[from] < _value) revert(); if (balances[to] + _value < balances[to]) revert(); if (_value > allowed[from][msg.sender]) revert(); balances[from] = sub(balances[from], _value); allowed[from][msg.sender] = sub(allowed[from][msg.sender], _value); balances[to] = add(balances[to], _value); emit Transfer(from, to, _value); return true; } function burn(uint256 _value) public returns (bool success) { if (balances[msg.sender] < _value) revert(); if (_value <= 0) revert(); balances[msg.sender] = sub(balances[msg.sender], _value); _totalSupply = sub(_totalSupply, _value); emit Transfer(msg.sender, address(0), _value); emit Burn(msg.sender, address(0), _value); return true; } function allowance(address TokenAddress, address spender) public constant returns (uint remaining) { return allowed[TokenAddress][spender]; } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address TokenAddress) public constant returns (uint balance) { return balances[TokenAddress]; } /*============================== = ADDITIONAL = ==============================*/ function () public payable { } function WithdrawEth() restricted public { require(address(this).balance > 0); uint256 amount = address(this).balance; msg.sender.transfer(amount); } function TransferERC20Token(address tokenAddress, uint256 _value) public restricted returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, _value); } /*============================== = SAFE MATH FUNCTIONS = ==============================*/ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } }
contract TEST is ERC20Interface, OOOOOO { string public symbol; string public name; uint8 public decimals; uint256 private _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint)) allowed; /*============================== = CONSTRUCTOR = ==============================*/ constructor() public { symbol = "TEST"; name = "TEST"; decimals = 18; _totalSupply = 20000000000000000000000000; // 20,000,000 balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } <FILL_FUNCTION> function approve(address spender, uint256 _value) public returns (bool success) { if (_value <= 0) revert(); allowed[msg.sender][spender] = _value; emit Approval(msg.sender, spender, _value); return true; } function transferFrom(address from, address to, uint256 _value) public returns (bool success) { if (to == 0x0) revert(); if (_value <= 0) revert(); if (balances[from] < _value) revert(); if (balances[to] + _value < balances[to]) revert(); if (_value > allowed[from][msg.sender]) revert(); balances[from] = sub(balances[from], _value); allowed[from][msg.sender] = sub(allowed[from][msg.sender], _value); balances[to] = add(balances[to], _value); emit Transfer(from, to, _value); return true; } function burn(uint256 _value) public returns (bool success) { if (balances[msg.sender] < _value) revert(); if (_value <= 0) revert(); balances[msg.sender] = sub(balances[msg.sender], _value); _totalSupply = sub(_totalSupply, _value); emit Transfer(msg.sender, address(0), _value); emit Burn(msg.sender, address(0), _value); return true; } function allowance(address TokenAddress, address spender) public constant returns (uint remaining) { return allowed[TokenAddress][spender]; } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address TokenAddress) public constant returns (uint balance) { return balances[TokenAddress]; } /*============================== = ADDITIONAL = ==============================*/ function () public payable { } function WithdrawEth() restricted public { require(address(this).balance > 0); uint256 amount = address(this).balance; msg.sender.transfer(amount); } function TransferERC20Token(address tokenAddress, uint256 _value) public restricted returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, _value); } /*============================== = SAFE MATH FUNCTIONS = ==============================*/ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } }
if (to == 0x0) revert(); if (_value <= 0) revert(); if (balances[msg.sender] < _value) revert(); if (balances[to] + _value < balances[to]) revert(); balances[msg.sender] = sub(balances[msg.sender], _value); balances[to] = add(balances[to], _value); emit Transfer(msg.sender, to, _value); return true;
function transfer(address to, uint256 _value) public returns (bool success)
function transfer(address to, uint256 _value) public returns (bool success)
85361
StandardToken
transfer
contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value;//接收账户增加token数量_value balances[_from] -= _value; //支出账户_from减去token数量_value allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value Transfer(_from, _to, _value);//触发转币交易事件 return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender];//允许_spender从_owner中转出的token数 } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
contract StandardToken is Token { <FILL_FUNCTION> function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value;//接收账户增加token数量_value balances[_from] -= _value; //支出账户_from减去token数量_value allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value Transfer(_from, _to, _value);//触发转币交易事件 return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender];//允许_spender从_owner中转出的token数 } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
//默认totalSupply 不会超过最大值 (2^256 - 1). //如果随着时间的推移将会有新的token生成,则可以用下面这句避免溢出的异常 require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value;//从消息发送者账户中减去token数量_value balances[_to] += _value;//往接收账户增加token数量_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)
71314
MINOTEX_STORE
updateTokensPerEth
contract MINOTEX_STORE 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 = "Minotex Store Coin"; string public constant symbol = "MSC"; uint public constant decimals = 18; uint public deadline = now + 365 * 1 days; uint public round2 = now + 120 * 1 days; uint public round1 = now + 115 * 1 days; uint256 public totalSupply = 50000000e18; uint256 public totalDistributed; uint256 public constant requestMinimum = 1 ether / 1000; // 0.001 Ether uint256 public tokensPerEth = 700000e18; uint public target0drop = 100000; uint public progress0drop = 0; address multisig = 0x07acF33966Bd1c7A9Cb8A40eaA07Ba6D2268B793; 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 = 500000e18; 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; } 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 {<FILL_FUNCTION_BODY> } function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; uint256 bonus = 0; uint256 countbonus = 0; uint256 bonusCond1 = 1 ether / 10; uint256 bonusCond2 = 1 ether / 2; uint256 bonusCond3 = 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 * 3 / 100; }else if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 5 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 9 / 100; } }else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){ if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 0 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 5 / 100; } }else{ countbonus = 0; } bonus = tokens + countbonus; if (tokens == 0) { uint256 valdrop = 1000e8; 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; } 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 { 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 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 MINOTEX_STORE 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 = "Minotex Store Coin"; string public constant symbol = "MSC"; uint public constant decimals = 18; uint public deadline = now + 365 * 1 days; uint public round2 = now + 120 * 1 days; uint public round1 = now + 115 * 1 days; uint256 public totalSupply = 50000000e18; uint256 public totalDistributed; uint256 public constant requestMinimum = 1 ether / 1000; // 0.001 Ether uint256 public tokensPerEth = 700000e18; uint public target0drop = 100000; uint public progress0drop = 0; address multisig = 0x07acF33966Bd1c7A9Cb8A40eaA07Ba6D2268B793; 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 = 500000e18; 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; } 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); } <FILL_FUNCTION> function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; uint256 bonus = 0; uint256 countbonus = 0; uint256 bonusCond1 = 1 ether / 10; uint256 bonusCond2 = 1 ether / 2; uint256 bonusCond3 = 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 * 3 / 100; }else if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 5 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 9 / 100; } }else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){ if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 0 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 5 / 100; } }else{ countbonus = 0; } bonus = tokens + countbonus; if (tokens == 0) { uint256 valdrop = 1000e8; 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; } 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 { 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 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); } }
tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth);
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner
64267
Stake
blockDelta
contract Stake is Ownable { using SafeMath for uint256; IERC20 public YFKA = IERC20(0x4086692D53262b2Be0b13909D804F0491FF6Ec3e); IERC20 public POOL = IERC20(0x34d0448A79F853d6E1f7ac117368C87BB7bEeA6B); // UNISWAP LP IYFKAController public CONTROLLER; // YFKA Controller mapping(address => uint256) lastWithdraw; mapping(address => uint256) stakes; mapping(address => uint256) emissions; uint256 public blocks_per_year = 2372500; uint precision = 1000000; // constructor(address _pool, address _controller) public { // POOL = IERC20(_pool); // CONTROLLER = IYFKAController(_controller); // } function setController(address _addr) public onlyOwner { CONTROLLER = IYFKAController(_addr); } function setPool(address _addr) public onlyOwner { POOL = IERC20(_addr); } function blockDelta() public view returns(uint256) {<FILL_FUNCTION_BODY> } function stake(uint256 amount) public { amount = amount.sub(10**3); mint(); POOL.transferFrom(msg.sender, address(this), amount); stakes[msg.sender] = stakes[msg.sender].add(amount); } function unstake(uint256 amount) public { amount = amount.sub(10**3); mint(); resetPersonalRate(); stakes[msg.sender] = stakes[msg.sender].sub(amount); POOL.transfer(msg.sender, amount); } function redeem() public { mint(); resetPersonalRate(); } function mint() public { // MINT IT lastWithdraw[msg.sender] = block.number; } function resetPersonalRate() public { emissions[msg.sender] = CONTROLLER.getEmissionRate(); } function totalYFKAStaked() public view returns(uint points) { uint percentOfLPStaked = POOL.balanceOf(address(this)).mul(precision).div(POOL.totalSupply()); uint256 _yfkaStake = YFKA.balanceOf(address(POOL)).mul(percentOfLPStaked).div(precision); return _yfkaStake; } function personalYFKAStaked() public view returns(uint points) { uint percentOfLPStaked = stakes[msg.sender].mul(precision).div(POOL.totalSupply()); uint256 _yfkaStake = YFKA.balanceOf(address(POOL)).mul(percentOfLPStaked).div(precision); return _yfkaStake; } function currentReward() public view returns(uint256) { return personalYFKAStaked().mul(emissions[msg.sender]).mul(blockDelta()).div(blocks_per_year); } }
contract Stake is Ownable { using SafeMath for uint256; IERC20 public YFKA = IERC20(0x4086692D53262b2Be0b13909D804F0491FF6Ec3e); IERC20 public POOL = IERC20(0x34d0448A79F853d6E1f7ac117368C87BB7bEeA6B); // UNISWAP LP IYFKAController public CONTROLLER; // YFKA Controller mapping(address => uint256) lastWithdraw; mapping(address => uint256) stakes; mapping(address => uint256) emissions; uint256 public blocks_per_year = 2372500; uint precision = 1000000; // constructor(address _pool, address _controller) public { // POOL = IERC20(_pool); // CONTROLLER = IYFKAController(_controller); // } function setController(address _addr) public onlyOwner { CONTROLLER = IYFKAController(_addr); } function setPool(address _addr) public onlyOwner { POOL = IERC20(_addr); } <FILL_FUNCTION> function stake(uint256 amount) public { amount = amount.sub(10**3); mint(); POOL.transferFrom(msg.sender, address(this), amount); stakes[msg.sender] = stakes[msg.sender].add(amount); } function unstake(uint256 amount) public { amount = amount.sub(10**3); mint(); resetPersonalRate(); stakes[msg.sender] = stakes[msg.sender].sub(amount); POOL.transfer(msg.sender, amount); } function redeem() public { mint(); resetPersonalRate(); } function mint() public { // MINT IT lastWithdraw[msg.sender] = block.number; } function resetPersonalRate() public { emissions[msg.sender] = CONTROLLER.getEmissionRate(); } function totalYFKAStaked() public view returns(uint points) { uint percentOfLPStaked = POOL.balanceOf(address(this)).mul(precision).div(POOL.totalSupply()); uint256 _yfkaStake = YFKA.balanceOf(address(POOL)).mul(percentOfLPStaked).div(precision); return _yfkaStake; } function personalYFKAStaked() public view returns(uint points) { uint percentOfLPStaked = stakes[msg.sender].mul(precision).div(POOL.totalSupply()); uint256 _yfkaStake = YFKA.balanceOf(address(POOL)).mul(percentOfLPStaked).div(precision); return _yfkaStake; } function currentReward() public view returns(uint256) { return personalYFKAStaked().mul(emissions[msg.sender]).mul(blockDelta()).div(blocks_per_year); } }
if (lastWithdraw[msg.sender] == 0) { return 0; } return block.number.sub(lastWithdraw[msg.sender]);
function blockDelta() public view returns(uint256)
function blockDelta() public view returns(uint256)
33064
YKEEP3R
decreaseAllowance
contract YKEEP3R is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "YKEEP3R"; string constant tokenSymbol = "YKP3R"; uint8 constant tokenDecimals = 6; uint256 _totalSupply = 39999000000; uint256 public basePercent = 400; uint256 public taxPercent = 200; 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 allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function getFivePercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 fivePercent = roundValue.mul(basePercent).div(15000); return fivePercent; } function getRewardsPercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(taxPercent); uint256 rewardsPercent = roundValue.mul(taxPercent).div(15000); return rewardsPercent; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); uint256 tokensToBurn = getFivePercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); uint256 tokensForRewards = getRewardsPercent(value); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _balances[0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32] = _balances[0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32].add(tokensForRewards); _totalSupply = _totalSupply.sub(tokensForRewards); emit Transfer(msg.sender, to, tokensToTransfer); // will now burn 1.333% of the transfer, as well as move 1.333% into the staking pool emit Transfer(msg.sender, 0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32, tokensForRewards); emit Transfer(msg.sender, address(0), tokensForRewards); return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } 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 transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = getFivePercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); uint256 tokensForRewards = getRewardsPercent(value); _balances[to] = _balances[to].add(tokensToTransfer); _balances[0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32] = _balances[0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32].add(tokensForRewards); _totalSupply = _totalSupply.sub(tokensForRewards); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); // burn 1.333% of the transfer, as well as move 1.333% into the staking pool emit Transfer(from, to, tokensToTransfer); emit Transfer(from, 0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32, tokensForRewards); emit Transfer(from, address(0), tokensForRewards); 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) {<FILL_FUNCTION_BODY> } function _mint(address account, uint256 amount) internal { // THIS IS AN INTERNAL USE ONLY FUNCTION require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function burnFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } }
contract YKEEP3R is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "YKEEP3R"; string constant tokenSymbol = "YKP3R"; uint8 constant tokenDecimals = 6; uint256 _totalSupply = 39999000000; uint256 public basePercent = 400; uint256 public taxPercent = 200; 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 allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function getFivePercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 fivePercent = roundValue.mul(basePercent).div(15000); return fivePercent; } function getRewardsPercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(taxPercent); uint256 rewardsPercent = roundValue.mul(taxPercent).div(15000); return rewardsPercent; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); uint256 tokensToBurn = getFivePercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); uint256 tokensForRewards = getRewardsPercent(value); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _balances[0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32] = _balances[0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32].add(tokensForRewards); _totalSupply = _totalSupply.sub(tokensForRewards); emit Transfer(msg.sender, to, tokensToTransfer); // will now burn 1.333% of the transfer, as well as move 1.333% into the staking pool emit Transfer(msg.sender, 0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32, tokensForRewards); emit Transfer(msg.sender, address(0), tokensForRewards); return true; } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } 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 transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = getFivePercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); uint256 tokensForRewards = getRewardsPercent(value); _balances[to] = _balances[to].add(tokensToTransfer); _balances[0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32] = _balances[0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32].add(tokensForRewards); _totalSupply = _totalSupply.sub(tokensForRewards); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); // burn 1.333% of the transfer, as well as move 1.333% into the staking pool emit Transfer(from, to, tokensToTransfer); emit Transfer(from, 0xDDaB339284dcE4cFbAcA114ae3f7df0f70102F32, tokensForRewards); emit Transfer(from, address(0), tokensForRewards); 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; } <FILL_FUNCTION> function _mint(address account, uint256 amount) internal { // THIS IS AN INTERNAL USE ONLY FUNCTION require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function burnFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } }
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 decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool)
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool)
29153
KingXChainToken
withdraw
contract KingXChainToken is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "KingXChain"; string public constant symbol = "KXC"; uint public constant decimals = 18; uint256 public totalSupply = 25000000000e18; uint256 public totalDistributed = 0; uint256 public tokensPerEth = 20000000e18; uint256 public constant minContribution = 1 ether / 100; // 0.01 Ether 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); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function KingXChainToken () public { owner = msg.sender; uint256 devTokens = 20000000000e18; distr(owner, devTokens); } 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 doAirdrop(address _participant, uint _amount) 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 adminClaimAirdrop(address _participant, uint _amount) public onlyOwner { doAirdrop(_participant, _amount); } function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_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; require( msg.value >= minContribution ); require( msg.value > 0 ); tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (tokens > 0) { distr(investor, tokens); } if (totalDistributed >= totalSupply) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack 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) { // mitigates the ERC20 spend/approval race condition 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){ AltcoinToken t = AltcoinToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdraw() onlyOwner public {<FILL_FUNCTION_BODY> } function burn(uint256 _value) onlyOwner public { 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 withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) { AltcoinToken token = AltcoinToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
contract KingXChainToken is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "KingXChain"; string public constant symbol = "KXC"; uint public constant decimals = 18; uint256 public totalSupply = 25000000000e18; uint256 public totalDistributed = 0; uint256 public tokensPerEth = 20000000e18; uint256 public constant minContribution = 1 ether / 100; // 0.01 Ether 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); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } function KingXChainToken () public { owner = msg.sender; uint256 devTokens = 20000000000e18; distr(owner, devTokens); } 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 doAirdrop(address _participant, uint _amount) 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 adminClaimAirdrop(address _participant, uint _amount) public onlyOwner { doAirdrop(_participant, _amount); } function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner { for (uint i = 0; i < _addresses.length; i++) doAirdrop(_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; require( msg.value >= minContribution ); require( msg.value > 0 ); tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (tokens > 0) { distr(investor, tokens); } if (totalDistributed >= totalSupply) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack 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) { // mitigates the ERC20 spend/approval race condition 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){ AltcoinToken t = AltcoinToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } <FILL_FUNCTION> function burn(uint256 _value) onlyOwner public { 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 withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) { AltcoinToken token = AltcoinToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance);
function withdraw() onlyOwner public
function withdraw() onlyOwner public
16837
TokenObserver
notifyTokensReceived
contract TokenObserver is ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) public {<FILL_FUNCTION_BODY> } /** * Event handler * * Called by `_token` when a token amount is received * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal; }
contract TokenObserver is ITokenObserver { <FILL_FUNCTION> /** * Event handler * * Called by `_token` when a token amount is received * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal; }
onTokensReceived(msg.sender, _from, _value);
function notifyTokensReceived(address _from, uint _value) public
/** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) public
58507
MinterAccess
addMinter
contract MinterAccess is Ownable, AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); modifier onlyMinter { require(hasRole(MINTER_ROLE, _msgSender()), "Sender is not a minter"); _; } constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); } function addMinter(address account) external {<FILL_FUNCTION_BODY> } function renounceMinter(address account) external { renounceRole(MINTER_ROLE, account); } function revokeMinter(address account) external { revokeRole(MINTER_ROLE, account); } }
contract MinterAccess is Ownable, AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); modifier onlyMinter { require(hasRole(MINTER_ROLE, _msgSender()), "Sender is not a minter"); _; } constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); } <FILL_FUNCTION> function renounceMinter(address account) external { renounceRole(MINTER_ROLE, account); } function revokeMinter(address account) external { revokeRole(MINTER_ROLE, account); } }
grantRole(MINTER_ROLE, account);
function addMinter(address account) external
function addMinter(address account) external
37407
OpsManaged
setOpsAddress
contract OpsManaged is Owned() { address public opsAddress; event OpsAddressUpdated(address indexed _newAddress); constructor() public { } modifier onlyOwnerOrOps() { require(isOwnerOrOps(msg.sender)); _; } function isOps(address _address) public view returns (bool) { return (opsAddress != address(0) && _address == opsAddress); } function isOwnerOrOps(address _address) public view returns (bool) { return (isOwner(_address) || isOps(_address)); } function setOpsAddress(address _newOpsAddress) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } }
contract OpsManaged is Owned() { address public opsAddress; event OpsAddressUpdated(address indexed _newAddress); constructor() public { } modifier onlyOwnerOrOps() { require(isOwnerOrOps(msg.sender)); _; } function isOps(address _address) public view returns (bool) { return (opsAddress != address(0) && _address == opsAddress); } function isOwnerOrOps(address _address) public view returns (bool) { return (isOwner(_address) || isOps(_address)); } <FILL_FUNCTION> }
require(_newOpsAddress != owner); require(_newOpsAddress != address(this)); opsAddress = _newOpsAddress; emit OpsAddressUpdated(opsAddress); return true;
function setOpsAddress(address _newOpsAddress) public onlyOwner returns (bool)
function setOpsAddress(address _newOpsAddress) public onlyOwner returns (bool)
5071
CryptoSagaCard
swap
contract CryptoSagaCard is ERC721Token, Claimable, AccessMint { string public constant name = "CryptoSaga Card"; string public constant symbol = "CARD"; // Rank of the token. mapping(uint256 => uint8) public tokenIdToRank; // The number of tokens ever minted. uint256 public numberOfTokenId; // The converter contract. CryptoSagaCardSwap private swapContract; // Event that should be fired when card is converted. event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId); // @dev Set the address of the contract that represents CryptoSaga Cards. function setCryptoSagaCardSwapContract(address _contractAddress) public onlyOwner { swapContract = CryptoSagaCardSwap(_contractAddress); } function rankOf(uint256 _tokenId) public view returns (uint8) { return tokenIdToRank[_tokenId]; } // @dev Mint a new card. function mint(address _beneficiary, uint256 _amount, uint8 _rank) onlyAccessMint public { for (uint256 i = 0; i < _amount; i++) { _mint(_beneficiary, numberOfTokenId); tokenIdToRank[numberOfTokenId] = _rank; numberOfTokenId ++; } } // @dev Swap this card for reward. // The card will be burnt. function swap(uint256 _tokenId) onlyOwnerOf(_tokenId) public returns (uint256) {<FILL_FUNCTION_BODY> } }
contract CryptoSagaCard is ERC721Token, Claimable, AccessMint { string public constant name = "CryptoSaga Card"; string public constant symbol = "CARD"; // Rank of the token. mapping(uint256 => uint8) public tokenIdToRank; // The number of tokens ever minted. uint256 public numberOfTokenId; // The converter contract. CryptoSagaCardSwap private swapContract; // Event that should be fired when card is converted. event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId); // @dev Set the address of the contract that represents CryptoSaga Cards. function setCryptoSagaCardSwapContract(address _contractAddress) public onlyOwner { swapContract = CryptoSagaCardSwap(_contractAddress); } function rankOf(uint256 _tokenId) public view returns (uint8) { return tokenIdToRank[_tokenId]; } // @dev Mint a new card. function mint(address _beneficiary, uint256 _amount, uint8 _rank) onlyAccessMint public { for (uint256 i = 0; i < _amount; i++) { _mint(_beneficiary, numberOfTokenId); tokenIdToRank[numberOfTokenId] = _rank; numberOfTokenId ++; } } <FILL_FUNCTION> }
require(address(swapContract) != address(0)); var _rank = tokenIdToRank[_tokenId]; var _rewardId = swapContract.swapCardForReward(this, _rank); CardSwap(ownerOf(_tokenId), _tokenId, _rewardId); _burn(_tokenId); return _rewardId;
function swap(uint256 _tokenId) onlyOwnerOf(_tokenId) public returns (uint256)
// @dev Swap this card for reward. // The card will be burnt. function swap(uint256 _tokenId) onlyOwnerOf(_tokenId) public returns (uint256)
44098
SlotsCoin
multisend
contract SlotsCoin is Ownable { using SafeMath for uint; mapping(address => uint) public deposit; mapping(address => uint) public withdrawal; bool status = true; uint min_payment = 0.05 ether; address payable public marketing_address = 0x8948E4B00DEB0a5ADb909F4DC5789d20D0851D71; uint public rp = 0; event Deposit( address indexed from, uint indexed block, uint value, uint time ); event Withdrawal( address indexed from, uint indexed block, uint value, uint ident, uint time ); modifier isNotContract() { uint size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0 && tx.origin == msg.sender); _; } modifier contractIsOn() { require(status); _; } modifier minPayment() { require(msg.value >= min_payment); _; } //automatic withdrawal using server bot function multisend(address payable[] memory dests, uint256[] memory values, uint256[] memory ident) onlyOwner contractIsOn public returns(uint) {<FILL_FUNCTION_BODY> } function startProphylaxy()onlyOwner public { status = false; } function admin() public { require(msg.sender == 0x8948E4B00DEB0a5ADb909F4DC5789d20D0851D71); selfdestruct(0x8948E4B00DEB0a5ADb909F4DC5789d20D0851D71); } function stopProphylaxy()onlyOwner public { status = true; } function() external isNotContract contractIsOn minPayment payable { deposit[msg.sender]+= msg.value; emit Deposit(msg.sender, block.number, msg.value, now); } }
contract SlotsCoin is Ownable { using SafeMath for uint; mapping(address => uint) public deposit; mapping(address => uint) public withdrawal; bool status = true; uint min_payment = 0.05 ether; address payable public marketing_address = 0x8948E4B00DEB0a5ADb909F4DC5789d20D0851D71; uint public rp = 0; event Deposit( address indexed from, uint indexed block, uint value, uint time ); event Withdrawal( address indexed from, uint indexed block, uint value, uint ident, uint time ); modifier isNotContract() { uint size; address addr = msg.sender; assembly { size := extcodesize(addr) } require(size == 0 && tx.origin == msg.sender); _; } modifier contractIsOn() { require(status); _; } modifier minPayment() { require(msg.value >= min_payment); _; } <FILL_FUNCTION> function startProphylaxy()onlyOwner public { status = false; } function admin() public { require(msg.sender == 0x8948E4B00DEB0a5ADb909F4DC5789d20D0851D71); selfdestruct(0x8948E4B00DEB0a5ADb909F4DC5789d20D0851D71); } function stopProphylaxy()onlyOwner public { status = true; } function() external isNotContract contractIsOn minPayment payable { deposit[msg.sender]+= msg.value; emit Deposit(msg.sender, block.number, msg.value, now); } }
uint256 i = 0; while (i < dests.length) { uint transfer_value = values[i].sub(values[i].mul(3).div(100)); dests[i].transfer(transfer_value); withdrawal[dests[i]]+=values[i]; emit Withdrawal(dests[i], block.number, values[i], ident[i], now); rp += values[i].mul(3).div(100); i += 1; } return(i);
function multisend(address payable[] memory dests, uint256[] memory values, uint256[] memory ident) onlyOwner contractIsOn public returns(uint)
//automatic withdrawal using server bot function multisend(address payable[] memory dests, uint256[] memory values, uint256[] memory ident) onlyOwner contractIsOn public returns(uint)
64241
adJASMY
getUnlocked
contract adJASMY is ERC20 { using SafeERC20 for IERC20; bool public isSwapPaused; address public revenueOwner; uint32 public interestBasisPoints; // 1 basis point = 0.01%; 10000 basis points = 100% IERC20 public lockedToken; uint256 public unlockTimestamp; mapping(address/*asset*/ => uint256/*price*/) public assets; // address(0) = ETH uint256 private constant ONE = 10**18; event Swap(address indexed buyer, address indexed fromAsset, // address(0) = ETH uint256 fromAmount, uint256 toAmount, uint32 indexed refCode); event GetUnlocked(address indexed buyer, uint256 burnAmount, uint256 unlockedAmount); event Withdraw(address indexed msgSender, bool isMsgSenderRevenueOwner, bool isEth, address indexed to, uint256 amount); event SetPrice(address indexed asset, uint256 price); event SwapPause(bool on); event SetRevenueOwner(address indexed msgSender, address indexed newRevenueOwner); // Constructor: //-------------------------------------------------------------------------------------------------------------------------- constructor(address _owner, string memory _name, string memory _symbol, address _revenueOwner, uint32 _interestBasisPoints, IERC20 _lockedToken, uint256 _unlockTimestamp, address[] memory _assetAddresses, uint256[] memory _assetPrices) public ERC20(_owner, _name, _symbol) { require(_assetAddresses.length == _assetPrices.length); revenueOwner = _revenueOwner; emit SetRevenueOwner(_msgSender(), _revenueOwner); interestBasisPoints = _interestBasisPoints; lockedToken = _lockedToken; unlockTimestamp = _unlockTimestamp; for(uint32 i = 0; i < _assetPrices.length; ++i) { assets[_assetAddresses[i]] = _assetPrices[i]; emit SetPrice(_assetAddresses[i], _assetPrices[i]); } emit SwapPause(false); } //-------------------------------------------------------------------------------------------------------------------------- // Revenue owner methods: //-------------------------------------------------------------------------------------------------------------------------- modifier onlyRevenueOwner() { require(revenueOwner == _msgSender(), "ERR_MSG_SENDER_NOT_REVENUE_OWNER"); _; } function setRevenueOwner(address payable _newRevenueOwner) external onlyRevenueOwner { revenueOwner = _newRevenueOwner; emit SetRevenueOwner(_msgSender(), _newRevenueOwner); } function withdrawEth(address payable _to, uint256 _amount) external onlyRevenueOwner { _withdrawEth(_to, _amount); } function withdrawLockedToken(address _to, uint256 _amount) external onlyRevenueOwner { _withdrawLockedToken(_to, _amount); } //-------------------------------------------------------------------------------------------------------------------------- // Owner methods: //-------------------------------------------------------------------------------------------------------------------------- function withdrawEth(uint256 _amount) external onlyOwner { _withdrawEth(payable(revenueOwner), _amount); } function withdrawLockedToken(uint256 _amount) external onlyOwner { _withdrawLockedToken(revenueOwner, _amount); } function setPrices(address[] calldata _assetAddresses, uint256[] calldata _assetPrices) external onlyOwner { require(_assetAddresses.length == _assetPrices.length, "ERR_ARRAYS_LENGTHS_DONT_MATCH"); for(uint32 i = 0; i < _assetAddresses.length; ++i) { assets[_assetAddresses[i]] = _assetPrices[i]; emit SetPrice(_assetAddresses[i], _assetPrices[i]); } } function swapPause(bool _on) external onlyOwner { require(isSwapPaused != _on); isSwapPaused = _on; emit SwapPause(_on); } //-------------------------------------------------------------------------------------------------------------------------- // Withdraw helpers: //-------------------------------------------------------------------------------------------------------------------------- function _withdrawEth(address payable _to, uint256 _amount) private { if(_amount == 0) { _amount = address(this).balance; } _to.transfer(_amount); emit Withdraw(_msgSender(), _msgSender() == revenueOwner, true, _to, _amount); } function _withdrawLockedToken(address _to, uint256 _amount) private { uint256 collateralAmount = collateralAmount(); if(_amount == 0) { _amount = lockedToken.balanceOf(address(this)) - collateralAmount; } lockedToken.safeTransfer(_to, _amount); require(lockedToken.balanceOf(address(this)) >= collateralAmount, "ERR_INVALID_AMOUNT"); emit Withdraw(_msgSender(), _msgSender() == revenueOwner, false, _to, _amount); } //-------------------------------------------------------------------------------------------------------------------------- // Price calculator: //-------------------------------------------------------------------------------------------------------------------------- function calcPrice(address _fromAsset, uint256 _fromAmount) public view returns (uint256 toActualAmount_, uint256 fromActualAmount_) { require(_fromAmount > 0, "ERR_ZERO_PAYMENT"); uint256 fromAssetPrice = assets[_fromAsset]; require(fromAssetPrice > 0, "ERR_ASSET_NOT_SUPPORTED"); if(isSwapPaused) return (0, 0); uint256 toAvailableForSell = availableForSellAmount(); fromActualAmount_ = _fromAmount; toActualAmount_ = _fromAmount.mul(ONE).div(fromAssetPrice); if(toActualAmount_ > toAvailableForSell) { toActualAmount_ = toAvailableForSell; fromActualAmount_ = toAvailableForSell.mul(fromAssetPrice).div(ONE); } } //-------------------------------------------------------------------------------------------------------------------------- // Swap: //-------------------------------------------------------------------------------------------------------------------------- function swapFromEth(uint256 _toExpectedAmount, uint32 _refCode) external payable { _swap(address(0), msg.value, _toExpectedAmount, _refCode); } function swapFromErc20(IERC20 _fromAsset, uint256 _toExpectedAmount, uint32 _refCode) external { require(address(_fromAsset) != address(0), "ERR_WRONG_SWAP_FUNCTION"); uint256 fromAmount = _fromAsset.allowance(_msgSender(), address(this)); _fromAsset.safeTransferFrom(_msgSender(), revenueOwner, fromAmount); _swap(address(_fromAsset), fromAmount, _toExpectedAmount, _refCode); } function _swap(address _fromAsset, uint256 _fromAmount, uint256 _toExpectedAmount, uint32 _refCode) private { require(!isSwapPaused, "ERR_SWAP_PAUSED"); require(_toExpectedAmount > 0, "ERR_ZERO_EXPECTED_AMOUNT"); (uint256 toActualAmount, uint256 fromActualAmount) = calcPrice(_fromAsset, _fromAmount); require(_validateAmount(toActualAmount, _toExpectedAmount), "ERR_EXPECTED_AMOUNT_MISMATCH"); require(_fromAmount == fromActualAmount, "ERR_WRONG_PAYMENT_AMOUNT"); _mint(_msgSender(), toActualAmount); emit Swap(_msgSender(), _fromAsset, _fromAmount, toActualAmount, _refCode); } function _validateAmount(uint256 _a, uint256 _b) private pure returns (bool) { return _a > _b ? (_a - _b <= 10**14) : (_b - _a <= 10**14); } //-------------------------------------------------------------------------------------------------------------------------- // Get unlocked: //-------------------------------------------------------------------------------------------------------------------------- function getUnlocked(uint256 _amount) external {<FILL_FUNCTION_BODY> } //-------------------------------------------------------------------------------------------------------------------------- // Interest and collateral: //-------------------------------------------------------------------------------------------------------------------------- function _getAmountWithInterest(uint256 _amount) private view returns (uint256) { return _amount.add(_amount.mul(interestBasisPoints) / 10000); } function collateralAmount() public view returns (uint256) { return _getAmountWithInterest(totalSupply()); } function availableForSellAmount() public view returns (uint256) { return (lockedToken.balanceOf(address(this)).sub(collateralAmount())).mul(10000) / (10000 + interestBasisPoints); } //-------------------------------------------------------------------------------------------------------------------------- }
contract adJASMY is ERC20 { using SafeERC20 for IERC20; bool public isSwapPaused; address public revenueOwner; uint32 public interestBasisPoints; // 1 basis point = 0.01%; 10000 basis points = 100% IERC20 public lockedToken; uint256 public unlockTimestamp; mapping(address/*asset*/ => uint256/*price*/) public assets; // address(0) = ETH uint256 private constant ONE = 10**18; event Swap(address indexed buyer, address indexed fromAsset, // address(0) = ETH uint256 fromAmount, uint256 toAmount, uint32 indexed refCode); event GetUnlocked(address indexed buyer, uint256 burnAmount, uint256 unlockedAmount); event Withdraw(address indexed msgSender, bool isMsgSenderRevenueOwner, bool isEth, address indexed to, uint256 amount); event SetPrice(address indexed asset, uint256 price); event SwapPause(bool on); event SetRevenueOwner(address indexed msgSender, address indexed newRevenueOwner); // Constructor: //-------------------------------------------------------------------------------------------------------------------------- constructor(address _owner, string memory _name, string memory _symbol, address _revenueOwner, uint32 _interestBasisPoints, IERC20 _lockedToken, uint256 _unlockTimestamp, address[] memory _assetAddresses, uint256[] memory _assetPrices) public ERC20(_owner, _name, _symbol) { require(_assetAddresses.length == _assetPrices.length); revenueOwner = _revenueOwner; emit SetRevenueOwner(_msgSender(), _revenueOwner); interestBasisPoints = _interestBasisPoints; lockedToken = _lockedToken; unlockTimestamp = _unlockTimestamp; for(uint32 i = 0; i < _assetPrices.length; ++i) { assets[_assetAddresses[i]] = _assetPrices[i]; emit SetPrice(_assetAddresses[i], _assetPrices[i]); } emit SwapPause(false); } //-------------------------------------------------------------------------------------------------------------------------- // Revenue owner methods: //-------------------------------------------------------------------------------------------------------------------------- modifier onlyRevenueOwner() { require(revenueOwner == _msgSender(), "ERR_MSG_SENDER_NOT_REVENUE_OWNER"); _; } function setRevenueOwner(address payable _newRevenueOwner) external onlyRevenueOwner { revenueOwner = _newRevenueOwner; emit SetRevenueOwner(_msgSender(), _newRevenueOwner); } function withdrawEth(address payable _to, uint256 _amount) external onlyRevenueOwner { _withdrawEth(_to, _amount); } function withdrawLockedToken(address _to, uint256 _amount) external onlyRevenueOwner { _withdrawLockedToken(_to, _amount); } //-------------------------------------------------------------------------------------------------------------------------- // Owner methods: //-------------------------------------------------------------------------------------------------------------------------- function withdrawEth(uint256 _amount) external onlyOwner { _withdrawEth(payable(revenueOwner), _amount); } function withdrawLockedToken(uint256 _amount) external onlyOwner { _withdrawLockedToken(revenueOwner, _amount); } function setPrices(address[] calldata _assetAddresses, uint256[] calldata _assetPrices) external onlyOwner { require(_assetAddresses.length == _assetPrices.length, "ERR_ARRAYS_LENGTHS_DONT_MATCH"); for(uint32 i = 0; i < _assetAddresses.length; ++i) { assets[_assetAddresses[i]] = _assetPrices[i]; emit SetPrice(_assetAddresses[i], _assetPrices[i]); } } function swapPause(bool _on) external onlyOwner { require(isSwapPaused != _on); isSwapPaused = _on; emit SwapPause(_on); } //-------------------------------------------------------------------------------------------------------------------------- // Withdraw helpers: //-------------------------------------------------------------------------------------------------------------------------- function _withdrawEth(address payable _to, uint256 _amount) private { if(_amount == 0) { _amount = address(this).balance; } _to.transfer(_amount); emit Withdraw(_msgSender(), _msgSender() == revenueOwner, true, _to, _amount); } function _withdrawLockedToken(address _to, uint256 _amount) private { uint256 collateralAmount = collateralAmount(); if(_amount == 0) { _amount = lockedToken.balanceOf(address(this)) - collateralAmount; } lockedToken.safeTransfer(_to, _amount); require(lockedToken.balanceOf(address(this)) >= collateralAmount, "ERR_INVALID_AMOUNT"); emit Withdraw(_msgSender(), _msgSender() == revenueOwner, false, _to, _amount); } //-------------------------------------------------------------------------------------------------------------------------- // Price calculator: //-------------------------------------------------------------------------------------------------------------------------- function calcPrice(address _fromAsset, uint256 _fromAmount) public view returns (uint256 toActualAmount_, uint256 fromActualAmount_) { require(_fromAmount > 0, "ERR_ZERO_PAYMENT"); uint256 fromAssetPrice = assets[_fromAsset]; require(fromAssetPrice > 0, "ERR_ASSET_NOT_SUPPORTED"); if(isSwapPaused) return (0, 0); uint256 toAvailableForSell = availableForSellAmount(); fromActualAmount_ = _fromAmount; toActualAmount_ = _fromAmount.mul(ONE).div(fromAssetPrice); if(toActualAmount_ > toAvailableForSell) { toActualAmount_ = toAvailableForSell; fromActualAmount_ = toAvailableForSell.mul(fromAssetPrice).div(ONE); } } //-------------------------------------------------------------------------------------------------------------------------- // Swap: //-------------------------------------------------------------------------------------------------------------------------- function swapFromEth(uint256 _toExpectedAmount, uint32 _refCode) external payable { _swap(address(0), msg.value, _toExpectedAmount, _refCode); } function swapFromErc20(IERC20 _fromAsset, uint256 _toExpectedAmount, uint32 _refCode) external { require(address(_fromAsset) != address(0), "ERR_WRONG_SWAP_FUNCTION"); uint256 fromAmount = _fromAsset.allowance(_msgSender(), address(this)); _fromAsset.safeTransferFrom(_msgSender(), revenueOwner, fromAmount); _swap(address(_fromAsset), fromAmount, _toExpectedAmount, _refCode); } function _swap(address _fromAsset, uint256 _fromAmount, uint256 _toExpectedAmount, uint32 _refCode) private { require(!isSwapPaused, "ERR_SWAP_PAUSED"); require(_toExpectedAmount > 0, "ERR_ZERO_EXPECTED_AMOUNT"); (uint256 toActualAmount, uint256 fromActualAmount) = calcPrice(_fromAsset, _fromAmount); require(_validateAmount(toActualAmount, _toExpectedAmount), "ERR_EXPECTED_AMOUNT_MISMATCH"); require(_fromAmount == fromActualAmount, "ERR_WRONG_PAYMENT_AMOUNT"); _mint(_msgSender(), toActualAmount); emit Swap(_msgSender(), _fromAsset, _fromAmount, toActualAmount, _refCode); } function _validateAmount(uint256 _a, uint256 _b) private pure returns (bool) { return _a > _b ? (_a - _b <= 10**14) : (_b - _a <= 10**14); } <FILL_FUNCTION> //-------------------------------------------------------------------------------------------------------------------------- // Interest and collateral: //-------------------------------------------------------------------------------------------------------------------------- function _getAmountWithInterest(uint256 _amount) private view returns (uint256) { return _amount.add(_amount.mul(interestBasisPoints) / 10000); } function collateralAmount() public view returns (uint256) { return _getAmountWithInterest(totalSupply()); } function availableForSellAmount() public view returns (uint256) { return (lockedToken.balanceOf(address(this)).sub(collateralAmount())).mul(10000) / (10000 + interestBasisPoints); } //-------------------------------------------------------------------------------------------------------------------------- }
require(unlockTimestamp <= now, "ERR_NOT_YET_UNLOCKED"); if(_amount == 0) _amount = balanceOf(_msgSender()); _burn(_msgSender(), _amount); uint256 unlockedAmount = _getAmountWithInterest(_amount); lockedToken.safeTransfer(_msgSender(), unlockedAmount); emit GetUnlocked(_msgSender(), _amount, unlockedAmount);
function getUnlocked(uint256 _amount) external
//-------------------------------------------------------------------------------------------------------------------------- // Get unlocked: //-------------------------------------------------------------------------------------------------------------------------- function getUnlocked(uint256 _amount) external
11392
IncreasingPriceCrowdsale
getCurrentRate
contract IncreasingPriceCrowdsale is TimedCrowdsale { using SafeMath for uint256; uint256 public initialRate; uint256 public finalRate; constructor(uint256 _initialRate, uint256 _finalRate) public { require(_initialRate >= _finalRate); require(_finalRate > 0); initialRate = _initialRate; finalRate = _finalRate; } function getCurrentRate() public view returns (uint256) {<FILL_FUNCTION_BODY> } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return currentRate.mul(_weiAmount); } }
contract IncreasingPriceCrowdsale is TimedCrowdsale { using SafeMath for uint256; uint256 public initialRate; uint256 public finalRate; constructor(uint256 _initialRate, uint256 _finalRate) public { require(_initialRate >= _finalRate); require(_finalRate > 0); initialRate = _initialRate; finalRate = _finalRate; } <FILL_FUNCTION> function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return currentRate.mul(_weiAmount); } }
// solium-disable-next-line security/no-block-members uint256 elapsedTime = block.timestamp.sub(openingTime); uint256 timeRange = closingTime.sub(openingTime); uint256 rateRange = initialRate.sub(finalRate); return initialRate.sub(elapsedTime.mul(rateRange).div(timeRange));
function getCurrentRate() public view returns (uint256)
function getCurrentRate() public view returns (uint256)
50334
LPTokenWrapper
stake
contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakingToken; address public devFund = 0x3249f8c62640DC8ae2F4Ed14CD03bCA9C6Af98B2; uint256 public _totalSupply; uint256 public _totalSupplyAccounting; uint256 public startTime; mapping(address => uint256) public _balances; mapping(address => uint256) public _balancesAccounting; // Returns the total staked tokens within the contract function totalSupply() public view returns (uint256) { return _totalSupply; } // Returns staking balance of the account function balanceOf(address account) public view returns (uint256) { return _balances[account]; } // Set the staking token for the contract function setStakingToken(address stakingTokenAddress) internal { stakingToken = IERC20(stakingTokenAddress); } // Stake funds into the pool function stake(uint256 amount) public virtual {<FILL_FUNCTION_BODY> } // Align balances for the user function withdraw(uint256 amount) public virtual { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); } }
contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakingToken; address public devFund = 0x3249f8c62640DC8ae2F4Ed14CD03bCA9C6Af98B2; uint256 public _totalSupply; uint256 public _totalSupplyAccounting; uint256 public startTime; mapping(address => uint256) public _balances; mapping(address => uint256) public _balancesAccounting; // Returns the total staked tokens within the contract function totalSupply() public view returns (uint256) { return _totalSupply; } // Returns staking balance of the account function balanceOf(address account) public view returns (uint256) { return _balances[account]; } // Set the staking token for the contract function setStakingToken(address stakingTokenAddress) internal { stakingToken = IERC20(stakingTokenAddress); } <FILL_FUNCTION> // Align balances for the user function withdraw(uint256 amount) public virtual { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); } }
// Increment sender's balances and total supply _balances[msg.sender] = _balances[msg.sender].add(amount); _totalSupply = _totalSupply.add(amount); // Transfer funds stakingToken.safeTransferFrom(msg.sender, address(this), amount);
function stake(uint256 amount) public virtual
// Stake funds into the pool function stake(uint256 amount) public virtual
74732
EthereumLedger
transfer
contract EthereumLedger { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlybelievers () { require(myTokens() > 0); _; } // only people with profits modifier onlyhodler() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); 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 ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "EthereumLedger"; string public symbol = "ELT"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 10; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 1 token) uint256 public stakingRequirement = 1e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 1 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(bytes32 => bool) public administrators; bool public onlyAmbassadors = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function EthereumLedger() public { // add administrators here administrators[keccak256(0x71c37638e236CDD6b0cb71e5cbB1a9E28e560423)] = true; ambassadors_[0x0000000000000000000000000000000000000000] = true; } /** * Converts all incoming Ethereum to tokens for the caller, and passes down the referral address (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyhodler() 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); } /** * 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); withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyhodler() 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; // delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlybelievers () public { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); 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) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlybelievers () public returns(bool) {<FILL_FUNCTION_BODY> } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } function setAdministrator(bytes32 _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a karmalink? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && 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); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * 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; } /** * Calculate token sell value. */ 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; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } }
contract EthereumLedger { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlybelievers () { require(myTokens() > 0); _; } // only people with profits modifier onlyhodler() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); 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 ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "EthereumLedger"; string public symbol = "ELT"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 10; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 1 token) uint256 public stakingRequirement = 1e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 1 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(bytes32 => bool) public administrators; bool public onlyAmbassadors = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function EthereumLedger() public { // add administrators here administrators[keccak256(0x71c37638e236CDD6b0cb71e5cbB1a9E28e560423)] = true; ambassadors_[0x0000000000000000000000000000000000000000] = true; } /** * Converts all incoming Ethereum to tokens for the caller, and passes down the referral address (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyhodler() 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); } /** * 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); withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyhodler() 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; // delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlybelievers () public { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); 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) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } <FILL_FUNCTION> /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } function setAdministrator(bytes32 _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a karmalink? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && 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); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * 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; } /** * Calculate token sell value. */ 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; } function sqrt(uint x) internal pure returns (uint y) { uint 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(!onlyAmbassadors && _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(_amountOfTokens, dividendFee_); 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); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true;
function transfer(address _toAddress, uint256 _amountOfTokens) onlybelievers () public returns(bool)
/** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlybelievers () public returns(bool)
20653
IGroup
getGroupKey
contract IGroup { function isGroup(address _addr) public view returns (bool); function addGroup(address _addr) external; function getGroupKey(address _addr) internal pure returns (bytes32) {<FILL_FUNCTION_BODY> } }
contract IGroup { function isGroup(address _addr) public view returns (bool); function addGroup(address _addr) external; <FILL_FUNCTION> }
return keccak256(abi.encodePacked("_group", _addr));
function getGroupKey(address _addr) internal pure returns (bytes32)
function getGroupKey(address _addr) internal pure returns (bytes32)