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
86326
MyToken
burn
contract MyToken { // Public variables of the token string public name = "DTIlite"; string public symbol = "DTI"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply = 10000000; // 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); // 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 */ constructor() public { totalSupply = totalSupply; // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply * 10 ** uint256(decimals); // Give the creator all initial tokens name = name; // Set the name for display purposes symbol = symbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _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] + _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; 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] + 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 returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * 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; emit Approval(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) {<FILL_FUNCTION_BODY> } /** * 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 emit Burn(_from, _value); return true; } /** custom add-on to ERC20: airDrop * Airdrop to multiple accounts at once * * Deliver 1 token to each account in [] beneficiaries * * @param beneficiaries the addresses of the receivers */ function airDrop(address[] beneficiaries) public returns (bool success) { require(balanceOf[msg.sender] >= beneficiaries.length); // Check balance for (uint8 i = 0; i< beneficiaries.length; i++) { address beneficiary = beneficiaries[i]; transfer(beneficiary, 1 * 10 ** uint256(decimals)); } return true; } }
contract MyToken { // Public variables of the token string public name = "DTIlite"; string public symbol = "DTI"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply = 10000000; // 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); // 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 */ constructor() public { totalSupply = totalSupply; // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply * 10 ** uint256(decimals); // Give the creator all initial tokens name = name; // Set the name for display purposes symbol = symbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _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] + _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; 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] + 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 returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * 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; emit Approval(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; } } <FILL_FUNCTION> /** * 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 emit Burn(_from, _value); return true; } /** custom add-on to ERC20: airDrop * Airdrop to multiple accounts at once * * Deliver 1 token to each account in [] beneficiaries * * @param beneficiaries the addresses of the receivers */ function airDrop(address[] beneficiaries) public returns (bool success) { require(balanceOf[msg.sender] >= beneficiaries.length); // Check balance for (uint8 i = 0; i< beneficiaries.length; i++) { address beneficiary = beneficiaries[i]; transfer(beneficiary, 1 * 10 ** uint256(decimals)); } return true; } }
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true;
function burn(uint256 _value) public returns (bool success)
/** * 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)
39313
DharmaKeyRegistryMultisig
getDestination
contract DharmaKeyRegistryMultisig { // The nonce is the only mutable state, and is incremented on every call. uint256 private _nonce; // Maintain a mapping and a convenience array of owners. mapping(address => bool) private _isOwner; address[] private _owners; // V2 of the Dharma Key Registry is the only account the multisig can call. address private constant _DESTINATION = address( 0x000000000D38df53b45C5733c7b34000dE0BDF52 ); // The threshold is an exact number of valid signatures that must be supplied. uint256 private constant _THRESHOLD = 3; // Note: Owners must be strictly increasing in order to prevent duplicates. constructor(address[] memory owners) public { require(owners.length <= 10, "Cannot have more than 10 owners."); require(_THRESHOLD <= owners.length, "Threshold cannot exceed total owners."); address lastAddress = address(0); for (uint256 i = 0; i < owners.length; i++) { require( owners[i] > lastAddress, "Owner addresses must be strictly increasing." ); _isOwner[owners[i]] = true; lastAddress = owners[i]; } _owners = owners; } function getNextHash( bytes calldata data, address executor, uint256 gasLimit ) external view returns (bytes32 hash) { hash = _getHash(data, executor, gasLimit, _nonce); } function getHash( bytes calldata data, address executor, uint256 gasLimit, uint256 nonce ) external view returns (bytes32 hash) { hash = _getHash(data, executor, gasLimit, nonce); } function getNonce() external view returns (uint256 nonce) { nonce = _nonce; } function getOwners() external view returns (address[] memory owners) { owners = _owners; } function isOwner(address account) external view returns (bool owner) { owner = _isOwner[account]; } function getThreshold() external pure returns (uint256 threshold) { threshold = _THRESHOLD; } function getDestination() external pure returns (address destination) {<FILL_FUNCTION_BODY> } // Note: addresses recovered from signatures must be strictly increasing. function execute( bytes calldata data, address executor, uint256 gasLimit, bytes calldata signatures ) external returns (bool success, bytes memory returnData) { require( executor == msg.sender || executor == address(0), "Must call from the executor account if one is specified." ); // Derive the message hash and wrap in the eth signed messsage hash. bytes32 hash = _toEthSignedMessageHash( _getHash(data, executor, gasLimit, _nonce) ); // Recover each signer from the provided signatures. address[] memory signers = _recoverGroup(hash, signatures); require(signers.length == _THRESHOLD, "Total signers must equal threshold."); // Verify that each signatory is an owner and is strictly increasing. address lastAddress = address(0); // cannot have address(0) as an owner for (uint256 i = 0; i < signers.length; i++) { require( _isOwner[signers[i]], "Signature does not correspond to an owner." ); require( signers[i] > lastAddress, "Signer addresses must be strictly increasing." ); lastAddress = signers[i]; } // Increment the nonce and execute the transaction. _nonce++; (success, returnData) = _DESTINATION.call.gas(gasLimit)(data); } function _getHash( bytes memory data, address executor, uint256 gasLimit, uint256 nonce ) internal view returns (bytes32 hash) { // Note: this is the data used to create a personal signed message hash. hash = keccak256( abi.encodePacked(address(this), nonce, executor, gasLimit, data) ); } /** * @dev Returns each address that signed a hashed message (`hash`) from a * collection of `signatures`. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if a signature is invalid, or if the * signer is otherwise unable to be retrieved. In those scenarios, the zero * address is returned for that signature. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that recover * to arbitrary addresses for non-hashed data. */ function _recoverGroup( bytes32 hash, bytes memory signatures ) internal pure returns (address[] memory signers) { // Ensure that the signatures length is a multiple of 65. if (signatures.length % 65 != 0) { return new address[](0); } // Create an appropriately-sized array of addresses for each signer. signers = new address[](signatures.length / 65); // Get each signature location and divide into r, s and v variables. bytes32 signatureLocation; bytes32 r; bytes32 s; uint8 v; for (uint256 i = 0; i < signers.length; i++) { assembly { signatureLocation := add(signatures, mul(i, 65)) r := mload(add(signatureLocation, 32)) s := mload(add(signatureLocation, 64)) v := byte(0, mload(add(signatureLocation, 96))) } // EIP-2 still allows signature malleability for ecrecover(). Remove // this possibility and make the signature unique. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { continue; } if (v != 27 && v != 28) { continue; } // If signature is valid & not malleable, add signer address. signers[i] = ecrecover(hash, v, r, s); } } function _toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
contract DharmaKeyRegistryMultisig { // The nonce is the only mutable state, and is incremented on every call. uint256 private _nonce; // Maintain a mapping and a convenience array of owners. mapping(address => bool) private _isOwner; address[] private _owners; // V2 of the Dharma Key Registry is the only account the multisig can call. address private constant _DESTINATION = address( 0x000000000D38df53b45C5733c7b34000dE0BDF52 ); // The threshold is an exact number of valid signatures that must be supplied. uint256 private constant _THRESHOLD = 3; // Note: Owners must be strictly increasing in order to prevent duplicates. constructor(address[] memory owners) public { require(owners.length <= 10, "Cannot have more than 10 owners."); require(_THRESHOLD <= owners.length, "Threshold cannot exceed total owners."); address lastAddress = address(0); for (uint256 i = 0; i < owners.length; i++) { require( owners[i] > lastAddress, "Owner addresses must be strictly increasing." ); _isOwner[owners[i]] = true; lastAddress = owners[i]; } _owners = owners; } function getNextHash( bytes calldata data, address executor, uint256 gasLimit ) external view returns (bytes32 hash) { hash = _getHash(data, executor, gasLimit, _nonce); } function getHash( bytes calldata data, address executor, uint256 gasLimit, uint256 nonce ) external view returns (bytes32 hash) { hash = _getHash(data, executor, gasLimit, nonce); } function getNonce() external view returns (uint256 nonce) { nonce = _nonce; } function getOwners() external view returns (address[] memory owners) { owners = _owners; } function isOwner(address account) external view returns (bool owner) { owner = _isOwner[account]; } function getThreshold() external pure returns (uint256 threshold) { threshold = _THRESHOLD; } <FILL_FUNCTION> // Note: addresses recovered from signatures must be strictly increasing. function execute( bytes calldata data, address executor, uint256 gasLimit, bytes calldata signatures ) external returns (bool success, bytes memory returnData) { require( executor == msg.sender || executor == address(0), "Must call from the executor account if one is specified." ); // Derive the message hash and wrap in the eth signed messsage hash. bytes32 hash = _toEthSignedMessageHash( _getHash(data, executor, gasLimit, _nonce) ); // Recover each signer from the provided signatures. address[] memory signers = _recoverGroup(hash, signatures); require(signers.length == _THRESHOLD, "Total signers must equal threshold."); // Verify that each signatory is an owner and is strictly increasing. address lastAddress = address(0); // cannot have address(0) as an owner for (uint256 i = 0; i < signers.length; i++) { require( _isOwner[signers[i]], "Signature does not correspond to an owner." ); require( signers[i] > lastAddress, "Signer addresses must be strictly increasing." ); lastAddress = signers[i]; } // Increment the nonce and execute the transaction. _nonce++; (success, returnData) = _DESTINATION.call.gas(gasLimit)(data); } function _getHash( bytes memory data, address executor, uint256 gasLimit, uint256 nonce ) internal view returns (bytes32 hash) { // Note: this is the data used to create a personal signed message hash. hash = keccak256( abi.encodePacked(address(this), nonce, executor, gasLimit, data) ); } /** * @dev Returns each address that signed a hashed message (`hash`) from a * collection of `signatures`. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if a signature is invalid, or if the * signer is otherwise unable to be retrieved. In those scenarios, the zero * address is returned for that signature. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that recover * to arbitrary addresses for non-hashed data. */ function _recoverGroup( bytes32 hash, bytes memory signatures ) internal pure returns (address[] memory signers) { // Ensure that the signatures length is a multiple of 65. if (signatures.length % 65 != 0) { return new address[](0); } // Create an appropriately-sized array of addresses for each signer. signers = new address[](signatures.length / 65); // Get each signature location and divide into r, s and v variables. bytes32 signatureLocation; bytes32 r; bytes32 s; uint8 v; for (uint256 i = 0; i < signers.length; i++) { assembly { signatureLocation := add(signatures, mul(i, 65)) r := mload(add(signatureLocation, 32)) s := mload(add(signatureLocation, 64)) v := byte(0, mload(add(signatureLocation, 96))) } // EIP-2 still allows signature malleability for ecrecover(). Remove // this possibility and make the signature unique. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { continue; } if (v != 27 && v != 28) { continue; } // If signature is valid & not malleable, add signer address. signers[i] = ecrecover(hash, v, r, s); } } function _toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
destination = _DESTINATION;
function getDestination() external pure returns (address destination)
function getDestination() external pure returns (address destination)
85057
HomaInvest
getPercent
contract HomaInvest{ using SafeMath for uint; using Percent for Percent.percent; // array containing information about beneficiaries mapping (address => uint) public balances; //array containing information about the time of payment mapping (address => uint) public time; //The marks of the balance on the contract after which the percentage of payments will change uint step1 = 200; uint step2 = 400; uint step3 = 600; uint step4 = 800; uint step5 = 1000; //the time through which dividends will be paid uint dividendsTime = 1 days; event NewInvestor(address indexed investor, uint deposit); event PayOffDividends(address indexed investor, uint value); event NewDeposit(address indexed investor, uint value); uint public allDeposits; uint public allPercents; uint public allBeneficiaries; uint public lastPayment; uint public constant minInvesment = 10 finney; address public commissionAddr = 0x9f7E3556284EC90961ed0Ff78713729545A96131; Percent.percent private m_adminPercent = Percent.percent(10, 100); /** * The modifier checking the positive balance of the beneficiary */ modifier isIssetRecepient(){ require(balances[msg.sender] > 0, "Deposit not found"); _; } /** * modifier checking the next payout time */ modifier timeCheck(){ require(now >= time[msg.sender].add(dividendsTime), "Too fast payout request. The time of payment has not yet come"); _; } function getDepositMultiplier()public view returns(uint){ uint percent = getPercent(); uint rate = balances[msg.sender].mul(percent).div(10000); uint depositMultiplier = now.sub(time[msg.sender]).div(dividendsTime); return(rate.mul(depositMultiplier)); } function receivePayment()isIssetRecepient timeCheck private{ uint depositMultiplier = getDepositMultiplier(); time[msg.sender] = now; msg.sender.transfer(depositMultiplier); allPercents+=depositMultiplier; lastPayment =now; emit PayOffDividends(msg.sender, depositMultiplier); } /** * @return bool */ function authorizationPayment()public view returns(bool){ if (balances[msg.sender] > 0 && now >= (time[msg.sender].add(dividendsTime))){ return (true); }else{ return(false); } } /** * @return uint percent */ function getPercent() public view returns(uint){<FILL_FUNCTION_BODY> } function createDeposit() private{ if(msg.value > 0){ require(msg.value >= minInvesment, "msg.value must be >= minInvesment"); if (balances[msg.sender] == 0){ emit NewInvestor(msg.sender, msg.value); allBeneficiaries+=1; } // commission commissionAddr.transfer(m_adminPercent.mul(msg.value)); if(getDepositMultiplier() > 0 && now >= time[msg.sender].add(dividendsTime) ){ receivePayment(); } balances[msg.sender] = balances[msg.sender].add(msg.value); time[msg.sender] = now; allDeposits+=msg.value; emit NewDeposit(msg.sender, msg.value); }else{ receivePayment(); } } /** * function that is launched when transferring money to a contract */ function() external payable{ createDeposit(); } }
contract HomaInvest{ using SafeMath for uint; using Percent for Percent.percent; // array containing information about beneficiaries mapping (address => uint) public balances; //array containing information about the time of payment mapping (address => uint) public time; //The marks of the balance on the contract after which the percentage of payments will change uint step1 = 200; uint step2 = 400; uint step3 = 600; uint step4 = 800; uint step5 = 1000; //the time through which dividends will be paid uint dividendsTime = 1 days; event NewInvestor(address indexed investor, uint deposit); event PayOffDividends(address indexed investor, uint value); event NewDeposit(address indexed investor, uint value); uint public allDeposits; uint public allPercents; uint public allBeneficiaries; uint public lastPayment; uint public constant minInvesment = 10 finney; address public commissionAddr = 0x9f7E3556284EC90961ed0Ff78713729545A96131; Percent.percent private m_adminPercent = Percent.percent(10, 100); /** * The modifier checking the positive balance of the beneficiary */ modifier isIssetRecepient(){ require(balances[msg.sender] > 0, "Deposit not found"); _; } /** * modifier checking the next payout time */ modifier timeCheck(){ require(now >= time[msg.sender].add(dividendsTime), "Too fast payout request. The time of payment has not yet come"); _; } function getDepositMultiplier()public view returns(uint){ uint percent = getPercent(); uint rate = balances[msg.sender].mul(percent).div(10000); uint depositMultiplier = now.sub(time[msg.sender]).div(dividendsTime); return(rate.mul(depositMultiplier)); } function receivePayment()isIssetRecepient timeCheck private{ uint depositMultiplier = getDepositMultiplier(); time[msg.sender] = now; msg.sender.transfer(depositMultiplier); allPercents+=depositMultiplier; lastPayment =now; emit PayOffDividends(msg.sender, depositMultiplier); } /** * @return bool */ function authorizationPayment()public view returns(bool){ if (balances[msg.sender] > 0 && now >= (time[msg.sender].add(dividendsTime))){ return (true); }else{ return(false); } } <FILL_FUNCTION> function createDeposit() private{ if(msg.value > 0){ require(msg.value >= minInvesment, "msg.value must be >= minInvesment"); if (balances[msg.sender] == 0){ emit NewInvestor(msg.sender, msg.value); allBeneficiaries+=1; } // commission commissionAddr.transfer(m_adminPercent.mul(msg.value)); if(getDepositMultiplier() > 0 && now >= time[msg.sender].add(dividendsTime) ){ receivePayment(); } balances[msg.sender] = balances[msg.sender].add(msg.value); time[msg.sender] = now; allDeposits+=msg.value; emit NewDeposit(msg.sender, msg.value); }else{ receivePayment(); } } /** * function that is launched when transferring money to a contract */ function() external payable{ createDeposit(); } }
uint contractBalance = address(this).balance; uint balanceStep1 = step1.mul(1 ether); uint balanceStep2 = step2.mul(1 ether); uint balanceStep3 = step3.mul(1 ether); uint balanceStep4 = step4.mul(1 ether); uint balanceStep5 = step5.mul(1 ether); if(contractBalance < balanceStep1){ return(325); } if(contractBalance >= balanceStep1 && contractBalance < balanceStep2){ return(350); } if(contractBalance >= balanceStep2 && contractBalance < balanceStep3){ return(375); } if(contractBalance >= balanceStep3 && contractBalance < balanceStep4){ return(400); } if(contractBalance >= balanceStep4 && contractBalance < balanceStep5){ return(425); } if(contractBalance >= balanceStep5){ return(450); }
function getPercent() public view returns(uint)
/** * @return uint percent */ function getPercent() public view returns(uint)
71490
TokenLock
getMinLockedAmount
contract TokenLock is Ownable { using SafeMath for uint256; bool public transferEnabled = false; // indicates that token is transferable or not bool public noTokenLocked = false; // indicates all token is released or not struct TokenLockInfo { // token of `amount` cannot be moved before `time` uint256 amount; // locked amount uint256 time; // unix timestamp } struct TokenLockState { uint256 latestReleaseTime; TokenLockInfo[] tokenLocks; // multiple token locks can exist } mapping(address => TokenLockState) lockingStates; mapping(address => bool) addresslock; mapping(address => uint256) lockbalances; event AddTokenLockDate(address indexed to, uint256 time, uint256 amount); event AddTokenLock(address indexed to, uint256 amount); event AddressLockTransfer(address indexed to, bool _enable); function unlockAllTokens() public onlyOwner { noTokenLocked = true; } function enableTransfer(bool _enable) public onlyOwner { transferEnabled = _enable; } // calculate the amount of tokens an address can use function getMinLockedAmount(address _addr) view public returns (uint256 locked) {<FILL_FUNCTION_BODY> } function lockVolumeAddress(address _sender) view public returns (uint256 locked) { return lockbalances[_sender]; } function addTokenLockDate(address _addr, uint256 _value, uint256 _release_time) onlyOwnerOrAdmin public { require(_addr != address(0)); require(_value > 0); require(_release_time > now); TokenLockState storage lockState = lockingStates[_addr]; // assigns a pointer. change the member value will update struct itself. if (_release_time > lockState.latestReleaseTime) { lockState.latestReleaseTime = _release_time; } lockState.tokenLocks.push(TokenLockInfo(_value, _release_time)); emit AddTokenLockDate(_addr, _release_time, _value); } function addTokenLock(address _addr, uint256 _value) onlyOwnerOrAdmin public { require(_addr != address(0)); require(_value >= 0); lockbalances[_addr] = _value; emit AddTokenLock(_addr, _value); } function addressLockTransfer(address _addr, bool _enable) public onlyOwner { require(_addr != address(0)); addresslock[_addr] = _enable; emit AddressLockTransfer(_addr, _enable); } }
contract TokenLock is Ownable { using SafeMath for uint256; bool public transferEnabled = false; // indicates that token is transferable or not bool public noTokenLocked = false; // indicates all token is released or not struct TokenLockInfo { // token of `amount` cannot be moved before `time` uint256 amount; // locked amount uint256 time; // unix timestamp } struct TokenLockState { uint256 latestReleaseTime; TokenLockInfo[] tokenLocks; // multiple token locks can exist } mapping(address => TokenLockState) lockingStates; mapping(address => bool) addresslock; mapping(address => uint256) lockbalances; event AddTokenLockDate(address indexed to, uint256 time, uint256 amount); event AddTokenLock(address indexed to, uint256 amount); event AddressLockTransfer(address indexed to, bool _enable); function unlockAllTokens() public onlyOwner { noTokenLocked = true; } function enableTransfer(bool _enable) public onlyOwner { transferEnabled = _enable; } <FILL_FUNCTION> function lockVolumeAddress(address _sender) view public returns (uint256 locked) { return lockbalances[_sender]; } function addTokenLockDate(address _addr, uint256 _value, uint256 _release_time) onlyOwnerOrAdmin public { require(_addr != address(0)); require(_value > 0); require(_release_time > now); TokenLockState storage lockState = lockingStates[_addr]; // assigns a pointer. change the member value will update struct itself. if (_release_time > lockState.latestReleaseTime) { lockState.latestReleaseTime = _release_time; } lockState.tokenLocks.push(TokenLockInfo(_value, _release_time)); emit AddTokenLockDate(_addr, _release_time, _value); } function addTokenLock(address _addr, uint256 _value) onlyOwnerOrAdmin public { require(_addr != address(0)); require(_value >= 0); lockbalances[_addr] = _value; emit AddTokenLock(_addr, _value); } function addressLockTransfer(address _addr, bool _enable) public onlyOwner { require(_addr != address(0)); addresslock[_addr] = _enable; emit AddressLockTransfer(_addr, _enable); } }
uint256 i; uint256 a; uint256 t; uint256 lockSum = 0; // if the address has no limitations just return 0 TokenLockState storage lockState = lockingStates[_addr]; if (lockState.latestReleaseTime < now) { return 0; } for (i=0; i<lockState.tokenLocks.length; i++) { a = lockState.tokenLocks[i].amount; t = lockState.tokenLocks[i].time; if (t > now) { lockSum = lockSum.add(a); } } return lockSum;
function getMinLockedAmount(address _addr) view public returns (uint256 locked)
// calculate the amount of tokens an address can use function getMinLockedAmount(address _addr) view public returns (uint256 locked)
76014
USDToken
transferAnyERC20Token
contract USDToken is ERC20Interface,Ownable { string public symbol; //代币符号 string public name; //代币名称 uint8 public decimal; //精确小数位 uint public _totalSupply; //总的发行代币数 mapping(address => uint) balances; //地址映射金额数 mapping(address =>mapping(address =>uint)) allowed; //授权地址使用金额绑定 //引入safemath 类库 using SafeMath for uint; //构造函数 //function LOPOToken() public{ function USDToken() public{ symbol = "USDT"; name = "USD Token"; decimal = 18; _totalSupply = 88543211; balances[msg.sender]=_totalSupply;//给发送者地址所有金额 Transfer(address(0),msg.sender,_totalSupply );//转账事件 } function totalSupply() public constant returns (uint totalSupply){ return _totalSupply; } function balanceOf(address _owner) public constant returns (uint balance){ return balances[_owner]; } function transfer(address _to, uint _value) public returns (bool success){ balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender,_to,_value); return true; } function approve(address _spender, uint _value) public returns (bool success){ allowed[msg.sender][_spender]=_value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint remaining){ return allowed[_owner][_spender]; } function transferFrom(address _from, address _to, uint _value) public returns (bool success){ allowed[_from][_to] = allowed[_from][_to].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from,_to,_value); return true; } //匿名函数回滚 禁止转账给me function() payable { revert(); } //转账给任何合约 function transferAnyERC20Token(address tokenaddress,uint tokens) public onlyOwner returns(bool success){<FILL_FUNCTION_BODY> } }
contract USDToken is ERC20Interface,Ownable { string public symbol; //代币符号 string public name; //代币名称 uint8 public decimal; //精确小数位 uint public _totalSupply; //总的发行代币数 mapping(address => uint) balances; //地址映射金额数 mapping(address =>mapping(address =>uint)) allowed; //授权地址使用金额绑定 //引入safemath 类库 using SafeMath for uint; //构造函数 //function LOPOToken() public{ function USDToken() public{ symbol = "USDT"; name = "USD Token"; decimal = 18; _totalSupply = 88543211; balances[msg.sender]=_totalSupply;//给发送者地址所有金额 Transfer(address(0),msg.sender,_totalSupply );//转账事件 } function totalSupply() public constant returns (uint totalSupply){ return _totalSupply; } function balanceOf(address _owner) public constant returns (uint balance){ return balances[_owner]; } function transfer(address _to, uint _value) public returns (bool success){ balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender,_to,_value); return true; } function approve(address _spender, uint _value) public returns (bool success){ allowed[msg.sender][_spender]=_value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint remaining){ return allowed[_owner][_spender]; } function transferFrom(address _from, address _to, uint _value) public returns (bool success){ allowed[_from][_to] = allowed[_from][_to].sub(_value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from,_to,_value); return true; } //匿名函数回滚 禁止转账给me function() payable { revert(); } <FILL_FUNCTION> }
ERC20Interface(tokenaddress).transfer(msg.sender,tokens);
function transferAnyERC20Token(address tokenaddress,uint tokens) public onlyOwner returns(bool success)
//转账给任何合约 function transferAnyERC20Token(address tokenaddress,uint tokens) public onlyOwner returns(bool success)
29814
DDIVS
purchaseTokens
contract DDIVS { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } uint ACTIVATION_TIME = 1538028000; // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol 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 = "DDIVS"; string public symbol = "DDIVS"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 18; // 18% dividend fee for double divs tokens on each buy and sell uint8 constant internal fundFee_ = 7; // 7% investment fund fee to buy double divs on each buy and sell uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // Address to send the 1% Fee address public giveEthFundAddress = 0x85EcbC22e9c0Ad0c1Cb3F4465582493bADc50433; bool public finalizedEthFundAddress = false; uint256 public totalEthFundRecieved; // total ETH charity recieved from this contract uint256 public totalEthFundCollected; // total ETH charity collected in this contract // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 25e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 0.75 ether; uint256 constant internal ambassadorQuota_ = 1.5 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(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // Special Double Divs Platform control from scam game contracts on Double Divs platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept Double Divs tokens mapping(address => address) public stickyRef; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // add administrators here administrators[0x28F0088308CDc140C2D72fBeA0b8e529cAA5Cb40] = true; // add the ambassadors here - Tokens will be distributed to these addresses from main premine ambassadors_[0x41FE3738B503cBaFD01C1Fd8DD66b7fE6Ec11b01] = true; // add the ambassadors here - Tokens will be distributed to these addresses from main premine ambassadors_[0x28F0088308CDc140C2D72fBeA0b8e529cAA5Cb40] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { require(tx.gasprice <= 0.05 szabo); purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { require(tx.gasprice <= 0.05 szabo); purchaseTokens(msg.value, 0x0); } function updateFundAddress(address _newAddress) onlyAdministrator() public { require(finalizedEthFundAddress == false); giveEthFundAddress = _newAddress; } function finalizeFundAddress(address _finalAddress) onlyAdministrator() public { require(finalizedEthFundAddress == false); giveEthFundAddress = _finalAddress; finalizedEthFundAddress = true; } /** * Sends FUND money to the Dev Fee Contract * The address is here https://etherscan.io/address/0x85EcbC22e9c0Ad0c1Cb3F4465582493bADc50433 */ function payFund() payable public { uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); require(ethToPay > 0); totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay); if(!giveEthFundAddress.call.value(ethToPay)()) { revert(); } } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit 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); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _refPayout = _dividends / 3; _dividends = SafeMath.sub(_dividends, _refPayout); (_dividends,) = handleRef(stickyRef[msg.sender], _refPayout, _dividends, 0); // Take out dividends and then _fundPayout uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // Add ethereum to send to fund totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); // 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 emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) { require(_to != address(0)); require(canAcceptTokens_[_to] == true); // security check that contract approved by Double Divs platform require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { AcceptsDDIVS receiver = AcceptsDDIVS(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); } return true; } /** * Additional check that the game address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ //function disableInitialStage() // onlyAdministrator() // public //{ // onlyAmbassadors = false; //} /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add or remove game contract, which can accept Double Divs (DDIVS) tokens */ function setCanAcceptTokens(address _address, bool _value) onlyAdministrator() public { canAcceptTokens_[_address] = _value; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ 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 address(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. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * 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) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } /** * Function for the frontend to show ether waiting to be send to fund in contract */ function etherToSendFund() public view returns(uint256) { return SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // Make sure we will send back excess if user sends more then 5 ether before 100 ETH in contract function purchaseInternal(uint256 _incomingEthereum, address _referredBy) notContract()// no contracts allowed internal returns(uint256) { uint256 purchaseEthereum = _incomingEthereum; uint256 excess; if(purchaseEthereum > 2.5 ether) { // check if the transaction is over 2.5 ether if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 100 ether) { // if so check the contract is less then 100 ether purchaseEthereum = 2.5 ether; excess = SafeMath.sub(_incomingEthereum, purchaseEthereum); } } purchaseTokens(purchaseEthereum, _referredBy); if (excess > 0) { msg.sender.transfer(excess); } } function handleRef(address _ref, uint _referralBonus, uint _currentDividends, uint _currentFee) internal returns (uint, uint){ uint _dividends = _currentDividends; uint _fee = _currentFee; address _referredBy = stickyRef[msg.sender]; if (_referredBy == address(0x0)){ _referredBy = _ref; } // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution if (stickyRef[msg.sender] == address(0x0)){ stickyRef[msg.sender] = _referredBy; } referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus/2); address currentRef = stickyRef[_referredBy]; if (currentRef != address(0x0) && tokenBalanceLedger_[currentRef] >= stakingRequirement){ referralBalance_[currentRef] = SafeMath.add(referralBalance_[currentRef], (_referralBonus/10)*3); currentRef = stickyRef[currentRef]; if (currentRef != address(0x0) && tokenBalanceLedger_[currentRef] >= stakingRequirement){ referralBalance_[currentRef] = SafeMath.add(referralBalance_[currentRef], (_referralBonus/10)*2); } else{ _dividends = SafeMath.add(_dividends, _referralBonus - _referralBonus/2 - (_referralBonus/10)*3); _fee = _dividends * magnitude; } } else{ _dividends = SafeMath.add(_dividends, _referralBonus - _referralBonus/2); _fee = _dividends * magnitude; } } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } return (_dividends, _fee); } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) {<FILL_FUNCTION_BODY> } /** * 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. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei 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 DDIVS { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } uint ACTIVATION_TIME = 1538028000; // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol 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 = "DDIVS"; string public symbol = "DDIVS"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 18; // 18% dividend fee for double divs tokens on each buy and sell uint8 constant internal fundFee_ = 7; // 7% investment fund fee to buy double divs on each buy and sell uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // Address to send the 1% Fee address public giveEthFundAddress = 0x85EcbC22e9c0Ad0c1Cb3F4465582493bADc50433; bool public finalizedEthFundAddress = false; uint256 public totalEthFundRecieved; // total ETH charity recieved from this contract uint256 public totalEthFundCollected; // total ETH charity collected in this contract // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 25e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 0.75 ether; uint256 constant internal ambassadorQuota_ = 1.5 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(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // Special Double Divs Platform control from scam game contracts on Double Divs platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept Double Divs tokens mapping(address => address) public stickyRef; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // add administrators here administrators[0x28F0088308CDc140C2D72fBeA0b8e529cAA5Cb40] = true; // add the ambassadors here - Tokens will be distributed to these addresses from main premine ambassadors_[0x41FE3738B503cBaFD01C1Fd8DD66b7fE6Ec11b01] = true; // add the ambassadors here - Tokens will be distributed to these addresses from main premine ambassadors_[0x28F0088308CDc140C2D72fBeA0b8e529cAA5Cb40] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { require(tx.gasprice <= 0.05 szabo); purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { require(tx.gasprice <= 0.05 szabo); purchaseTokens(msg.value, 0x0); } function updateFundAddress(address _newAddress) onlyAdministrator() public { require(finalizedEthFundAddress == false); giveEthFundAddress = _newAddress; } function finalizeFundAddress(address _finalAddress) onlyAdministrator() public { require(finalizedEthFundAddress == false); giveEthFundAddress = _finalAddress; finalizedEthFundAddress = true; } /** * Sends FUND money to the Dev Fee Contract * The address is here https://etherscan.io/address/0x85EcbC22e9c0Ad0c1Cb3F4465582493bADc50433 */ function payFund() payable public { uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); require(ethToPay > 0); totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay); if(!giveEthFundAddress.call.value(ethToPay)()) { revert(); } } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit 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); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _refPayout = _dividends / 3; _dividends = SafeMath.sub(_dividends, _refPayout); (_dividends,) = handleRef(stickyRef[msg.sender], _refPayout, _dividends, 0); // Take out dividends and then _fundPayout uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // Add ethereum to send to fund totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); // 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 emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) { require(_to != address(0)); require(canAcceptTokens_[_to] == true); // security check that contract approved by Double Divs platform require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { AcceptsDDIVS receiver = AcceptsDDIVS(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); } return true; } /** * Additional check that the game address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ //function disableInitialStage() // onlyAdministrator() // public //{ // onlyAmbassadors = false; //} /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add or remove game contract, which can accept Double Divs (DDIVS) tokens */ function setCanAcceptTokens(address _address, bool _value) onlyAdministrator() public { canAcceptTokens_[_address] = _value; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ 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 address(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. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * 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) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } /** * Function for the frontend to show ether waiting to be send to fund in contract */ function etherToSendFund() public view returns(uint256) { return SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // Make sure we will send back excess if user sends more then 5 ether before 100 ETH in contract function purchaseInternal(uint256 _incomingEthereum, address _referredBy) notContract()// no contracts allowed internal returns(uint256) { uint256 purchaseEthereum = _incomingEthereum; uint256 excess; if(purchaseEthereum > 2.5 ether) { // check if the transaction is over 2.5 ether if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 100 ether) { // if so check the contract is less then 100 ether purchaseEthereum = 2.5 ether; excess = SafeMath.sub(_incomingEthereum, purchaseEthereum); } } purchaseTokens(purchaseEthereum, _referredBy); if (excess > 0) { msg.sender.transfer(excess); } } function handleRef(address _ref, uint _referralBonus, uint _currentDividends, uint _currentFee) internal returns (uint, uint){ uint _dividends = _currentDividends; uint _fee = _currentFee; address _referredBy = stickyRef[msg.sender]; if (_referredBy == address(0x0)){ _referredBy = _ref; } // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution if (stickyRef[msg.sender] == address(0x0)){ stickyRef[msg.sender] = _referredBy; } referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus/2); address currentRef = stickyRef[_referredBy]; if (currentRef != address(0x0) && tokenBalanceLedger_[currentRef] >= stakingRequirement){ referralBalance_[currentRef] = SafeMath.add(referralBalance_[currentRef], (_referralBonus/10)*3); currentRef = stickyRef[currentRef]; if (currentRef != address(0x0) && tokenBalanceLedger_[currentRef] >= stakingRequirement){ referralBalance_[currentRef] = SafeMath.add(referralBalance_[currentRef], (_referralBonus/10)*2); } else{ _dividends = SafeMath.add(_dividends, _referralBonus - _referralBonus/2 - (_referralBonus/10)*3); _fee = _dividends * magnitude; } } else{ _dividends = SafeMath.add(_dividends, _referralBonus - _referralBonus/2); _fee = _dividends * magnitude; } } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } return (_dividends, _fee); } <FILL_FUNCTION> /** * 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. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei 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; } } }
// data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _fee; (_dividends, _fee) = handleRef(_referredBy, _referralBonus, _dividends, _fee); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _dividends), _fundPayout); totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); // no point in continuing execution if OP is a poor russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // 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_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[msg.sender] += _updatedPayouts; // fire event emit onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens;
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256)
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256)
66597
CommunityVotable
freezeCommunityVote
contract CommunityVotable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- CommunityVote public communityVote; bool public communityVoteFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote); event FreezeCommunityVoteEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the community vote contract /// @param newCommunityVote The (address of) CommunityVote contract instance function setCommunityVote(CommunityVote newCommunityVote) public onlyDeployer notNullAddress(address(newCommunityVote)) notSameAddresses(address(newCommunityVote), address(communityVote)) { require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]"); // Set new community vote CommunityVote oldCommunityVote = communityVote; communityVote = newCommunityVote; // Emit event emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote); } /// @notice Freeze the community vote from further updates /// @dev This operation can not be undone function freezeCommunityVote() public onlyDeployer {<FILL_FUNCTION_BODY> } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier communityVoteInitialized() { require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]"); _; } }
contract CommunityVotable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- CommunityVote public communityVote; bool public communityVoteFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote); event FreezeCommunityVoteEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the community vote contract /// @param newCommunityVote The (address of) CommunityVote contract instance function setCommunityVote(CommunityVote newCommunityVote) public onlyDeployer notNullAddress(address(newCommunityVote)) notSameAddresses(address(newCommunityVote), address(communityVote)) { require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]"); // Set new community vote CommunityVote oldCommunityVote = communityVote; communityVote = newCommunityVote; // Emit event emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote); } <FILL_FUNCTION> // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier communityVoteInitialized() { require(address(communityVote) != address(0), "Community vote not initialized [CommunityVotable.sol:67]"); _; } }
communityVoteFrozen = true; // Emit event emit FreezeCommunityVoteEvent();
function freezeCommunityVote() public onlyDeployer
/// @notice Freeze the community vote from further updates /// @dev This operation can not be undone function freezeCommunityVote() public onlyDeployer
68681
HolyKnight
withdraw
contract HolyKnight is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HOLYs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHolyPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accHolyPerShare` (and `lastRewardCalcBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. // Thus every change in pool or allocation will result in recalculation of values // (otherwise distribution remains constant btwn blocks and will be properly calculated) uint256 stakedLPAmount; } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract uint256 allocPoint; // How many allocation points assigned to this pool. HOLYs to distribute per block uint256 lastRewardCalcBlock; // Last block number for which HOLYs distribution is already calculated for the pool uint256 accHolyPerShare; // Accumulated HOLYs per share, times 1e12. See below bool stakeable; // we should call deposit method on the LP tokens provided (used for e.g. vault staking) address stakeableContract; // location where to deposit LP tokens if pool is stakeable IERC20 stakedHoldableToken; } // The Holyheld token HolyToken public holytoken; // Dev address. address public devaddr; // Treasury address address public treasuryaddr; // The block number when HOLY mining starts. uint256 public startBlock; // The block number when HOLY mining targeted to end (if full allocation). uint256 public targetEndBlock; // Total amount of tokens to distribute uint256 public totalSupply; // Reserved percent of HOLY tokens for current distribution (when pool allocation is not full) uint256 public reservedPercent; // HOLY tokens created per block, calculatable through updateHolyPerBlock(). uint256 public holyPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Info of total amount of staked LP tokens by all users mapping (address => uint256) public totalStaked; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event Treasury(address indexed token, address treasury, uint256 amount); constructor( HolyToken _token, address _devaddr, address _treasuryaddr, uint256 _totalsupply, uint256 _reservedPercent, uint256 _startBlock, uint256 _targetEndBlock ) public { holytoken = _token; devaddr = _devaddr; treasuryaddr = _treasuryaddr; //as knight is deployed by Holyheld token, transfer ownership to dev transferOwnership(_devaddr); totalSupply = _totalsupply; reservedPercent = _reservedPercent; startBlock = _startBlock; targetEndBlock = _targetEndBlock; //calculate initial token number per block updateHolyPerBlock(); } // Reserve some percentage of HOLY token distribution // (e.g. initially, 10% of tokens are reserved for future pools to be added) function setReserve(uint256 _reservedPercent) public onlyOwner { reservedPercent = _reservedPercent; updateHolyPerBlock(); } function updateHolyPerBlock() internal { //safemath substraction cannot overflow holyPerBlock = totalSupply.sub(totalSupply.mul(reservedPercent).div(100)).div(targetEndBlock.sub(startBlock)); massUpdatePools(); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _stakeable, address _stakeableContract, IERC20 _stakedHoldableToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardCalcBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardCalcBlock: lastRewardCalcBlock, accHolyPerShare: 0, stakeable: _stakeable, stakeableContract: _stakeableContract, stakedHoldableToken: IERC20(_stakedHoldableToken) })); if(_stakeable) { _lpToken.approve(_stakeableContract, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); } } // Update the given pool's HOLY allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // View function to see pending HOLYs on frontend. function pendingHoly(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHolyPerShare = pool.accHolyPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardCalcBlock && lpSupply != 0) { uint256 multiplier = block.number.sub(pool.lastRewardCalcBlock); uint256 tokenReward = multiplier.mul(holyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accHolyPerShare = accHolyPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accHolyPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardCalcBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardCalcBlock = block.number; return; } uint256 multiplier = block.number.sub(pool.lastRewardCalcBlock); uint256 tokenReward = multiplier.mul(holyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); //no minting is required, the contract already has token balance allocated pool.accHolyPerShare = pool.accHolyPerShare.add(tokenReward.mul(1e12).div(lpSupply)); pool.lastRewardCalcBlock = block.number; } // Deposit LP tokens to HolyKnight for HOLY allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accHolyPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); //pay the earned tokens when user deposits } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accHolyPerShare).div(1e12); if (pool.stakeable) { uint256 prevbalance = pool.stakedHoldableToken.balanceOf(address(this)); Stakeable(pool.stakeableContract).deposit(_amount); uint256 balancetoadd = pool.stakedHoldableToken.balanceOf(address(this)).sub(prevbalance); user.stakedLPAmount = user.stakedLPAmount.add(balancetoadd); //protect received tokens from moving to treasury totalStaked[address(pool.stakedHoldableToken)] = totalStaked[address(pool.stakedHoldableToken)].add(balancetoadd); } else { totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].add(_amount); } emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from HolyKnight. function withdraw(uint256 _pid, uint256 _amount) public {<FILL_FUNCTION_BODY> } // Withdraw LP tokens without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (pool.stakeable) { //reclaim back original LP tokens and withdraw all of them, regardless of amount Stakeable(pool.stakeableContract).withdraw(user.stakedLPAmount); totalStaked[address(pool.stakedHoldableToken)] = totalStaked[address(pool.stakedHoldableToken)].sub(user.stakedLPAmount); user.stakedLPAmount = 0; uint256 balance = pool.lpToken.balanceOf(address(this)); if (user.amount < balance) { pool.lpToken.safeTransfer(address(msg.sender), user.amount); } else { pool.lpToken.safeTransfer(address(msg.sender), balance); } } else { pool.lpToken.safeTransfer(address(msg.sender), user.amount); totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].sub(user.amount); } user.amount = 0; user.rewardDebt = 0; emit EmergencyWithdraw(msg.sender, _pid, user.amount); } // Safe holyheld token transfer function, just in case if rounding error causes pool to not have enough HOLYs. function safeTokenTransfer(address _to, uint256 _amount) internal { uint256 balance = holytoken.balanceOf(address(this)); if (_amount > balance) { holytoken.transfer(_to, balance); } else { holytoken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "forbidden"); devaddr = _devaddr; } // Update treasury address by the previous treasury. function treasury(address _treasuryaddr) public { require(msg.sender == treasuryaddr, "forbidden"); treasuryaddr = _treasuryaddr; } // Send yield on an LP token to the treasury function putToTreasury(address token) public onlyOwner { uint256 availablebalance = IERC20(token).balanceOf(address(this)) - totalStaked[token]; require(availablebalance > 0, "not enough tokens"); putToTreasuryAmount(token, availablebalance); } // Send yield amount realized from holding LP tokens to the treasury function putToTreasuryAmount(address token, uint256 _amount) public onlyOwner { uint256 userbalances = totalStaked[token]; uint256 lptokenbalance = IERC20(token).balanceOf(address(this)); require(token != address(holytoken), "cannot transfer holy tokens"); require(_amount <= lptokenbalance - userbalances, "not enough tokens"); IERC20(token).safeTransfer(treasuryaddr, _amount); emit Treasury(token, treasuryaddr, _amount); } }
contract HolyKnight is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HOLYs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHolyPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accHolyPerShare` (and `lastRewardCalcBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. // Thus every change in pool or allocation will result in recalculation of values // (otherwise distribution remains constant btwn blocks and will be properly calculated) uint256 stakedLPAmount; } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract uint256 allocPoint; // How many allocation points assigned to this pool. HOLYs to distribute per block uint256 lastRewardCalcBlock; // Last block number for which HOLYs distribution is already calculated for the pool uint256 accHolyPerShare; // Accumulated HOLYs per share, times 1e12. See below bool stakeable; // we should call deposit method on the LP tokens provided (used for e.g. vault staking) address stakeableContract; // location where to deposit LP tokens if pool is stakeable IERC20 stakedHoldableToken; } // The Holyheld token HolyToken public holytoken; // Dev address. address public devaddr; // Treasury address address public treasuryaddr; // The block number when HOLY mining starts. uint256 public startBlock; // The block number when HOLY mining targeted to end (if full allocation). uint256 public targetEndBlock; // Total amount of tokens to distribute uint256 public totalSupply; // Reserved percent of HOLY tokens for current distribution (when pool allocation is not full) uint256 public reservedPercent; // HOLY tokens created per block, calculatable through updateHolyPerBlock(). uint256 public holyPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Info of total amount of staked LP tokens by all users mapping (address => uint256) public totalStaked; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event Treasury(address indexed token, address treasury, uint256 amount); constructor( HolyToken _token, address _devaddr, address _treasuryaddr, uint256 _totalsupply, uint256 _reservedPercent, uint256 _startBlock, uint256 _targetEndBlock ) public { holytoken = _token; devaddr = _devaddr; treasuryaddr = _treasuryaddr; //as knight is deployed by Holyheld token, transfer ownership to dev transferOwnership(_devaddr); totalSupply = _totalsupply; reservedPercent = _reservedPercent; startBlock = _startBlock; targetEndBlock = _targetEndBlock; //calculate initial token number per block updateHolyPerBlock(); } // Reserve some percentage of HOLY token distribution // (e.g. initially, 10% of tokens are reserved for future pools to be added) function setReserve(uint256 _reservedPercent) public onlyOwner { reservedPercent = _reservedPercent; updateHolyPerBlock(); } function updateHolyPerBlock() internal { //safemath substraction cannot overflow holyPerBlock = totalSupply.sub(totalSupply.mul(reservedPercent).div(100)).div(targetEndBlock.sub(startBlock)); massUpdatePools(); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _stakeable, address _stakeableContract, IERC20 _stakedHoldableToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardCalcBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardCalcBlock: lastRewardCalcBlock, accHolyPerShare: 0, stakeable: _stakeable, stakeableContract: _stakeableContract, stakedHoldableToken: IERC20(_stakedHoldableToken) })); if(_stakeable) { _lpToken.approve(_stakeableContract, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); } } // Update the given pool's HOLY allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // View function to see pending HOLYs on frontend. function pendingHoly(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHolyPerShare = pool.accHolyPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardCalcBlock && lpSupply != 0) { uint256 multiplier = block.number.sub(pool.lastRewardCalcBlock); uint256 tokenReward = multiplier.mul(holyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accHolyPerShare = accHolyPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accHolyPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardCalcBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardCalcBlock = block.number; return; } uint256 multiplier = block.number.sub(pool.lastRewardCalcBlock); uint256 tokenReward = multiplier.mul(holyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); //no minting is required, the contract already has token balance allocated pool.accHolyPerShare = pool.accHolyPerShare.add(tokenReward.mul(1e12).div(lpSupply)); pool.lastRewardCalcBlock = block.number; } // Deposit LP tokens to HolyKnight for HOLY allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accHolyPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); //pay the earned tokens when user deposits } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accHolyPerShare).div(1e12); if (pool.stakeable) { uint256 prevbalance = pool.stakedHoldableToken.balanceOf(address(this)); Stakeable(pool.stakeableContract).deposit(_amount); uint256 balancetoadd = pool.stakedHoldableToken.balanceOf(address(this)).sub(prevbalance); user.stakedLPAmount = user.stakedLPAmount.add(balancetoadd); //protect received tokens from moving to treasury totalStaked[address(pool.stakedHoldableToken)] = totalStaked[address(pool.stakedHoldableToken)].add(balancetoadd); } else { totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].add(_amount); } emit Deposit(msg.sender, _pid, _amount); } <FILL_FUNCTION> // Withdraw LP tokens without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (pool.stakeable) { //reclaim back original LP tokens and withdraw all of them, regardless of amount Stakeable(pool.stakeableContract).withdraw(user.stakedLPAmount); totalStaked[address(pool.stakedHoldableToken)] = totalStaked[address(pool.stakedHoldableToken)].sub(user.stakedLPAmount); user.stakedLPAmount = 0; uint256 balance = pool.lpToken.balanceOf(address(this)); if (user.amount < balance) { pool.lpToken.safeTransfer(address(msg.sender), user.amount); } else { pool.lpToken.safeTransfer(address(msg.sender), balance); } } else { pool.lpToken.safeTransfer(address(msg.sender), user.amount); totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].sub(user.amount); } user.amount = 0; user.rewardDebt = 0; emit EmergencyWithdraw(msg.sender, _pid, user.amount); } // Safe holyheld token transfer function, just in case if rounding error causes pool to not have enough HOLYs. function safeTokenTransfer(address _to, uint256 _amount) internal { uint256 balance = holytoken.balanceOf(address(this)); if (_amount > balance) { holytoken.transfer(_to, balance); } else { holytoken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "forbidden"); devaddr = _devaddr; } // Update treasury address by the previous treasury. function treasury(address _treasuryaddr) public { require(msg.sender == treasuryaddr, "forbidden"); treasuryaddr = _treasuryaddr; } // Send yield on an LP token to the treasury function putToTreasury(address token) public onlyOwner { uint256 availablebalance = IERC20(token).balanceOf(address(this)) - totalStaked[token]; require(availablebalance > 0, "not enough tokens"); putToTreasuryAmount(token, availablebalance); } // Send yield amount realized from holding LP tokens to the treasury function putToTreasuryAmount(address token, uint256 _amount) public onlyOwner { uint256 userbalances = totalStaked[token]; uint256 lptokenbalance = IERC20(token).balanceOf(address(this)); require(token != address(holytoken), "cannot transfer holy tokens"); require(_amount <= lptokenbalance - userbalances, "not enough tokens"); IERC20(token).safeTransfer(treasuryaddr, _amount); emit Treasury(token, treasuryaddr, _amount); } }
PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 pending = user.amount.mul(pool.accHolyPerShare).div(1e12).sub(user.rewardDebt); safeTokenTransfer(msg.sender, pending); if (pool.stakeable) { //reclaim back original LP tokens and withdraw all of them, regardless of amount Stakeable(pool.stakeableContract).withdraw(user.stakedLPAmount); totalStaked[address(pool.stakedHoldableToken)] = totalStaked[address(pool.stakedHoldableToken)].sub(user.stakedLPAmount); user.stakedLPAmount = 0; uint256 balance = pool.lpToken.balanceOf(address(this)); if (user.amount < balance) { pool.lpToken.safeTransfer(address(msg.sender), user.amount); } else { pool.lpToken.safeTransfer(address(msg.sender), balance); } user.amount = 0; user.rewardDebt = 0; } else { require(user.amount >= _amount, "withdraw: not good"); pool.lpToken.safeTransfer(address(msg.sender), _amount); totalStaked[address(pool.lpToken)] = totalStaked[address(pool.lpToken)].sub(_amount); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accHolyPerShare).div(1e12); } emit Withdraw(msg.sender, _pid, _amount);
function withdraw(uint256 _pid, uint256 _amount) public
// Withdraw LP tokens from HolyKnight. function withdraw(uint256 _pid, uint256 _amount) public
84621
GanaPublicSale
buyGana
contract GanaPublicSale is Ownable { using SafeMath for uint256; GANA public gana; Whitelist public whitelist; address public wallet; uint256 public hardCap = 30000 ether; //publicsale cap uint256 public weiRaised = 0; uint256 public defaultRate = 20000; //uint256 public startTime = 1483228800; //TEST ONLY UTC 01/01/2017 00:00am uint256 public startTime = 1524218400; //UTC 04/20/2018 10:00am uint256 public endTime = 1526637600; //UTC 05/18/2018 10:00am event TokenPurchase(address indexed sender, address indexed buyer, uint256 weiAmount, uint256 ganaAmount); event Refund(address indexed buyer, uint256 weiAmount); event TransferToSafe(); event BurnAndReturnAfterEnded(uint256 burnAmount, uint256 returnAmount); function GanaPublicSale(address _gana, address _wallet, address _whitelist) public { require(_wallet != address(0)); gana = GANA(_gana); whitelist = Whitelist(_whitelist); wallet = _wallet; } modifier onlyWhitelisted() { require(whitelist.isWhitelist(msg.sender)); _; } // fallback function can be used to buy tokens function () external payable { buyGana(msg.sender); } function buyGana(address buyer) public onlyWhitelisted payable {<FILL_FUNCTION_BODY> } function getRate() public view returns (uint256) { if(weiRaised < 12500 ether){ return 21000; }else if(weiRaised < 25000 ether){ return 20500; }else{ return 20000; } } //Was it sold out or sale overdue function hasEnded() public view returns (bool) { bool hardCapReached = weiRaised >= hardCap; // balid cap return hardCapReached || afterEnded(); } function afterEnded() internal constant returns (bool) { return now > endTime; } function afterStart() internal constant returns (bool) { return now >= startTime; } function transferToSafe() onlyOwner public { require(hasEnded()); wallet.transfer(this.balance); TransferToSafe(); } /** * @dev burn unsold token and return bonus token * @param reserveWallet reserve pool address */ function burnAndReturnAfterEnded(address reserveWallet) onlyOwner public { require(reserveWallet != address(0)); require(hasEnded()); uint256 unsoldWei = hardCap.sub(weiRaised); uint256 ganaBalance = gana.balanceOf(this); require(ganaBalance > 0); if(unsoldWei > 0){ //Burn unsold and return bonus uint256 unsoldGanaAmount = ganaBalance; uint256 burnGanaAmount = unsoldWei.mul(defaultRate); uint256 bonusGanaAmount = unsoldGanaAmount.sub(burnGanaAmount); gana.burn(burnGanaAmount); gana.saleTransfer(reserveWallet, bonusGanaAmount); BurnAndReturnAfterEnded(burnGanaAmount, bonusGanaAmount); }else{ //All tokens were sold. return bonus gana.saleTransfer(reserveWallet, ganaBalance); BurnAndReturnAfterEnded(0, ganaBalance); } } /** * @dev emergency function before sale * @param returnAddress return token address */ function returnGanaBeforeSale(address returnAddress) onlyOwner public { require(returnAddress != address(0)); require(weiRaised == 0); uint256 returnGana = gana.balanceOf(this); gana.saleTransfer(returnAddress, returnGana); } }
contract GanaPublicSale is Ownable { using SafeMath for uint256; GANA public gana; Whitelist public whitelist; address public wallet; uint256 public hardCap = 30000 ether; //publicsale cap uint256 public weiRaised = 0; uint256 public defaultRate = 20000; //uint256 public startTime = 1483228800; //TEST ONLY UTC 01/01/2017 00:00am uint256 public startTime = 1524218400; //UTC 04/20/2018 10:00am uint256 public endTime = 1526637600; //UTC 05/18/2018 10:00am event TokenPurchase(address indexed sender, address indexed buyer, uint256 weiAmount, uint256 ganaAmount); event Refund(address indexed buyer, uint256 weiAmount); event TransferToSafe(); event BurnAndReturnAfterEnded(uint256 burnAmount, uint256 returnAmount); function GanaPublicSale(address _gana, address _wallet, address _whitelist) public { require(_wallet != address(0)); gana = GANA(_gana); whitelist = Whitelist(_whitelist); wallet = _wallet; } modifier onlyWhitelisted() { require(whitelist.isWhitelist(msg.sender)); _; } // fallback function can be used to buy tokens function () external payable { buyGana(msg.sender); } <FILL_FUNCTION> function getRate() public view returns (uint256) { if(weiRaised < 12500 ether){ return 21000; }else if(weiRaised < 25000 ether){ return 20500; }else{ return 20000; } } //Was it sold out or sale overdue function hasEnded() public view returns (bool) { bool hardCapReached = weiRaised >= hardCap; // balid cap return hardCapReached || afterEnded(); } function afterEnded() internal constant returns (bool) { return now > endTime; } function afterStart() internal constant returns (bool) { return now >= startTime; } function transferToSafe() onlyOwner public { require(hasEnded()); wallet.transfer(this.balance); TransferToSafe(); } /** * @dev burn unsold token and return bonus token * @param reserveWallet reserve pool address */ function burnAndReturnAfterEnded(address reserveWallet) onlyOwner public { require(reserveWallet != address(0)); require(hasEnded()); uint256 unsoldWei = hardCap.sub(weiRaised); uint256 ganaBalance = gana.balanceOf(this); require(ganaBalance > 0); if(unsoldWei > 0){ //Burn unsold and return bonus uint256 unsoldGanaAmount = ganaBalance; uint256 burnGanaAmount = unsoldWei.mul(defaultRate); uint256 bonusGanaAmount = unsoldGanaAmount.sub(burnGanaAmount); gana.burn(burnGanaAmount); gana.saleTransfer(reserveWallet, bonusGanaAmount); BurnAndReturnAfterEnded(burnGanaAmount, bonusGanaAmount); }else{ //All tokens were sold. return bonus gana.saleTransfer(reserveWallet, ganaBalance); BurnAndReturnAfterEnded(0, ganaBalance); } } /** * @dev emergency function before sale * @param returnAddress return token address */ function returnGanaBeforeSale(address returnAddress) onlyOwner public { require(returnAddress != address(0)); require(weiRaised == 0); uint256 returnGana = gana.balanceOf(this); gana.saleTransfer(returnAddress, returnGana); } }
require(!hasEnded()); require(afterStart()); require(buyer != address(0)); require(msg.value > 0); require(buyer == msg.sender); uint256 weiAmount = msg.value; //pre-calculate wei raise after buying uint256 preCalWeiRaised = weiRaised.add(weiAmount); uint256 ganaAmount; uint256 rate = getRate(); if(preCalWeiRaised <= hardCap){ //the pre-calculate wei raise is less than the hard cap ganaAmount = weiAmount.mul(rate); gana.saleTransfer(buyer, ganaAmount); weiRaised = preCalWeiRaised; TokenPurchase(msg.sender, buyer, weiAmount, ganaAmount); }else{ //the pre-calculate weiRaised is more than the hard cap uint256 refundWeiAmount = preCalWeiRaised.sub(hardCap); uint256 fundWeiAmount = weiAmount.sub(refundWeiAmount); ganaAmount = fundWeiAmount.mul(rate); gana.saleTransfer(buyer, ganaAmount); weiRaised = weiRaised.add(fundWeiAmount); TokenPurchase(msg.sender, buyer, fundWeiAmount, ganaAmount); buyer.transfer(refundWeiAmount); Refund(buyer,refundWeiAmount); }
function buyGana(address buyer) public onlyWhitelisted payable
function buyGana(address buyer) public onlyWhitelisted payable
75698
Bounty
issueTokens
contract Bounty is Ownable { LamdenTau public lamdenTau; function Bounty(address _tokenContractAddress) public { require(_tokenContractAddress != address(0)); lamdenTau = LamdenTau(_tokenContractAddress); } function returnTokens() onlyOwner { uint256 balance = lamdenTau.balanceOf(this); lamdenTau.transfer(msg.sender, balance); } function issueTokens() onlyOwner {<FILL_FUNCTION_BODY> } }
contract Bounty is Ownable { LamdenTau public lamdenTau; function Bounty(address _tokenContractAddress) public { require(_tokenContractAddress != address(0)); lamdenTau = LamdenTau(_tokenContractAddress); } function returnTokens() onlyOwner { uint256 balance = lamdenTau.balanceOf(this); lamdenTau.transfer(msg.sender, balance); } <FILL_FUNCTION> }
lamdenTau.transfer(0x2D5089a716ddfb0e917ea822B2fa506A3B075997, 2160000000000000000000); lamdenTau.transfer(0xe195cC6e1F738Df5bB114094cE4fbd7162CaD617, 720000000000000000000); lamdenTau.transfer(0xfd052EC542Db2d8d179C97555434C12277a2da90, 708000000000000000000); lamdenTau.transfer(0xBDe659f939374ddb64Cfe05ab55a736D13DdB232, 24000000000000000000); lamdenTau.transfer(0x3c567089fdB2F43399f82793999Ca4e2879a1442, 96000000000000000000); lamdenTau.transfer(0xdDF103c148a368B34215Ac2b37892CaBC98d2eb6, 216000000000000000000); lamdenTau.transfer(0x32b50a36762bA0194DbbD365C69014eA63bC208A, 246000000000000000000); lamdenTau.transfer(0x80e264eca46565b3b89234C889f86fC48A37FD27, 420000000000000000000); lamdenTau.transfer(0x924fA0A32c32c98e5138526a823440846870fa11, 1260000000000000000000); lamdenTau.transfer(0x8899b7328114dE9e26AF0f920b933517A84d0B27, 672000000000000000000); lamdenTau.transfer(0x5F3034c41fE8548A0B8718622679A7A1B1d990a2, 204000000000000000000); lamdenTau.transfer(0xA628431d3F331Fce908249DF8589c82b5C491790, 27000000000000000000); lamdenTau.transfer(0xbE603e5A1d8319a656a7Bab5f98438372eeB16fC, 24000000000000000000); lamdenTau.transfer(0xcA71C16d3146fdd147C8bAcb878F39A4d308C7b7, 708000000000000000000); lamdenTau.transfer(0xe47BBeAc8F268d7126082D5574B6f027f95AF5FB, 402000000000000000000); lamdenTau.transfer(0xF84CDC51C1FF6487AABD352E0A5661697e0830e3, 840000000000000000000); lamdenTau.transfer(0xA4D826F66A65F87D60bEbfd3DcFD50d25BA51285, 552000000000000000000); lamdenTau.transfer(0xEFA2427A318BE3D978Aac04436A59F2649d9f7bc, 648000000000000000000); lamdenTau.transfer(0x850ee0810c2071205E81cf7F5A5E056736ef4567, 720000000000000000000); lamdenTau.transfer(0x8D7f4b8658Ae777B498C154566fBc820f88533cd, 396000000000000000000); lamdenTau.transfer(0xD79Cd948a969D1A4Ff01C5d3205b460b1550FF29, 12000000000000000000); lamdenTau.transfer(0xa3e2a6AD4b95fc293f361B2Dba448e99B286971e, 108000000000000000000); lamdenTau.transfer(0xf1F55c5142AC402A2b6573fb051a307f455be9bE, 720000000000000000000); lamdenTau.transfer(0xB95390D77F2aF27dEb09aBF9AD6A0c36Ec1333D2, 516000000000000000000); lamdenTau.transfer(0xb9B03611Fc1EFAdD1F1a83d84CDD8CCa5d93f0CB, 444000000000000000000); lamdenTau.transfer(0x1FC6523C6F8f5F4a92EF98286f75ac4Fb86709dF, 960000000000000000000); lamdenTau.transfer(0x0Fe8C0F024B8dF422f830c34E3c406CC05735F77, 1020000000000000000000); lamdenTau.transfer(0x01e6c7F612798c5C63775712F3C090F10bE120bC, 258000000000000000000); lamdenTau.transfer(0xf4C2D2bd0448709Fe3169e98813ff036Ae16f1a9, 2160000000000000000000); lamdenTau.transfer(0x5752ae7b663b57819de59945176835ff43805622, 69000000000000000000); uint256 balance = lamdenTau.balanceOf(this); lamdenTau.transfer(msg.sender, balance);
function issueTokens() onlyOwner
function issueTokens() onlyOwner
15529
BatchTransfer
BatchTransfer
contract BatchTransfer{ address public owner; mapping (address => bool) public admins; Token public token; modifier onlyOwner{ require(msg.sender == owner); _; } modifier onlyOwnerOrAdmin{ require(msg.sender == owner || admins[msg.sender] == true); _; } function BatchTransfer(address _tokenAddr) public {<FILL_FUNCTION_BODY> } function ownerSetOwner(address newOwner) public onlyOwner{ owner = newOwner; } function ownerSetAdmin(address[] _admins) public onlyOwner{ for(uint i = 0; i<_admins.length; i++){ admins[_admins[i]] = true; } } function ownerModAdmin(address _admin, bool _authority) onlyOwner{ admins[_admin] = _authority; } function ownerTransfer(address _addr, uint _value) public onlyOwner{ token.transfer(_addr,_value); } function executeBatchTransfer(address[] _dests, uint[] _values) public onlyOwnerOrAdmin returns(uint){ uint i = 0; while (i < _dests.length) { token.transfer(_dests[i], _values[i] * (10 ** 18)); i += 1; } return i; } }
contract BatchTransfer{ address public owner; mapping (address => bool) public admins; Token public token; modifier onlyOwner{ require(msg.sender == owner); _; } modifier onlyOwnerOrAdmin{ require(msg.sender == owner || admins[msg.sender] == true); _; } <FILL_FUNCTION> function ownerSetOwner(address newOwner) public onlyOwner{ owner = newOwner; } function ownerSetAdmin(address[] _admins) public onlyOwner{ for(uint i = 0; i<_admins.length; i++){ admins[_admins[i]] = true; } } function ownerModAdmin(address _admin, bool _authority) onlyOwner{ admins[_admin] = _authority; } function ownerTransfer(address _addr, uint _value) public onlyOwner{ token.transfer(_addr,_value); } function executeBatchTransfer(address[] _dests, uint[] _values) public onlyOwnerOrAdmin returns(uint){ uint i = 0; while (i < _dests.length) { token.transfer(_dests[i], _values[i] * (10 ** 18)); i += 1; } return i; } }
owner = msg.sender; token = Token(_tokenAddr);
function BatchTransfer(address _tokenAddr) public
function BatchTransfer(address _tokenAddr) public
28448
ldoh
HodlTokens3
contract ldoh is EthereumSmartContract { /*============================== = EVENTS = ==============================*/ event onCashbackCode (address indexed hodler, address cashbackcode); event onAffiliateBonus (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onHoldplatform (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onUnlocktoken (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onReceiveAirdrop (address indexed hodler, uint256 amount, uint256 datetime); event onHOLDdeposit (address indexed hodler, uint256 amount, uint256 newbalance, uint256 datetime); event onHOLDwithdraw (address indexed hodler, uint256 amount, uint256 newbalance, uint256 datetime); /*============================== = VARIABLES = ==============================*/ //-------o Affiliate = 12% o-------o Cashback = 16% o-------o Total Receive = 88% o-------o Without Cashback = 72% o-------o //-------o Hold 24 Months, Unlock 3% Permonth // Struct Database struct Safe { uint256 id; // [01] -- > Registration Number uint256 amount; // [02] -- > Total amount of contribution to this transaction uint256 endtime; // [03] -- > The Expiration Of A Hold Platform Based On Unix Time address user; // [04] -- > The ETH address that you are using address tokenAddress; // [05] -- > The Token Contract Address That You Are Using string tokenSymbol; // [06] -- > The Token Symbol That You Are Using uint256 amountbalance; // [07] -- > 88% from Contribution / 72% Without Cashback uint256 cashbackbalance; // [08] -- > 16% from Contribution / 0% Without Cashback uint256 lasttime; // [09] -- > The Last Time You Withdraw Based On Unix Time uint256 percentage; // [10] -- > The percentage of tokens that are unlocked every month ( Default = 3% ) uint256 percentagereceive; // [11] -- > The Percentage You Have Received uint256 tokenreceive; // [12] -- > The Number Of Tokens You Have Received uint256 lastwithdraw; // [13] -- > The Last Amount You Withdraw address referrer; // [14] -- > Your ETH referrer address bool cashbackstatus; // [15] -- > Cashback Status } uint256 private idnumber; // [01] -- > ID number ( Start from 500 ) uint256 public TotalUser; // [02] -- > Total Smart Contract User mapping(address => address) public cashbackcode; // [03] -- > Cashback Code mapping(address => uint256[]) public idaddress; // [04] -- > Search Address by ID mapping(address => address[]) public afflist; // [05] -- > Affiliate List by ID mapping(address => string) public ContractSymbol; // [06] -- > Contract Address Symbol mapping(uint256 => Safe) private _safes; // [07] -- > Struct safe database mapping(address => bool) public contractaddress; // [08] -- > Contract Address mapping (address => mapping (uint256 => uint256)) public Bigdata; /** Bigdata Mapping : [1] Percent (Monthly Unlocked tokens) [7] All Payments [13] Total TX Affiliate (Withdraw) [2] Holding Time (in seconds) [8] Active User [14] Current Price (USD) [3] Token Balance [9] Total User [15] ATH Price (USD) [4] Min Contribution [10] Total TX Hold [16] ATL Price (USD) [5] Max Contribution [11] Total TX Unlock [17] Current ETH Price (ETH) [6] All Contribution [12] Total TX Airdrop [18] Unique Code **/ mapping (address => mapping (address => mapping (uint256 => uint256))) public Statistics; // Statistics = [1] LifetimeContribution [2] LifetimePayments [3] Affiliatevault [4] Affiliateprofit [5] ActiveContribution // Airdrop - Hold Platform (HOLD) address public Holdplatform_address; // [01] uint256 public Holdplatform_balance; // [02] mapping(address => uint256) public Holdplatform_status; // [03] mapping(address => uint256) public Holdplatform_divider; // [04] /*============================== = CONSTRUCTOR = ==============================*/ constructor() public { idnumber = 500; Holdplatform_address = 0x23bAdee11Bf49c40669e9b09035f048e9146213e; //Change before deploy } /*============================== = AVAILABLE FOR EVERYONE = ==============================*/ //-------o Function 01 - Ethereum Payable function () public payable { if (msg.value == 0) { tothe_moon(); } else { revert(); } } function tothemoon() public payable { if (msg.value == 0) { tothe_moon(); } else { revert(); } } function tothe_moon() private { for(uint256 i = 1; i < idnumber; i++) { Safe storage s = _safes[i]; if (s.user == msg.sender) { Unlocktoken(s.tokenAddress, s.id); } } } //-------o Function 02 - Cashback Code function CashbackCode(address _cashbackcode, uint256 uniquecode) public { require(_cashbackcode != msg.sender); if (cashbackcode[msg.sender] == 0x0000000000000000000000000000000000000000 && Bigdata[_cashbackcode][8] == 1 && Bigdata[_cashbackcode][18] != uniquecode ) { cashbackcode[msg.sender] = _cashbackcode; } else { cashbackcode[msg.sender] = EthereumNodes; } if (Bigdata[msg.sender][18] == 0 ) { Bigdata[msg.sender][18] = uniquecode; } emit onCashbackCode(msg.sender, _cashbackcode); } //-------o Function 03 - Contribute //--o 01 function Holdplatform(address tokenAddress, uint256 amount) public { require(amount >= 1 ); uint256 holdamount = add(Statistics[msg.sender][tokenAddress][5], amount); require(holdamount <= Bigdata[tokenAddress][5] ); if (cashbackcode[msg.sender] == 0x0000000000000000000000000000000000000000 ) { cashbackcode[msg.sender] = EthereumNodes; Bigdata[msg.sender][18] = 123456; } if (contractaddress[tokenAddress] == false) { revert(); } else { ERC20Interface token = ERC20Interface(tokenAddress); require(token.transferFrom(msg.sender, address(this), amount)); HodlTokens2(tokenAddress, amount); Airdrop(tokenAddress, amount, 1); } } //--o 02 function HodlTokens2(address ERC, uint256 amount) private { address ref = cashbackcode[msg.sender]; uint256 Burn = div(mul(amount, 2), 100); //test uint256 AvailableBalances = div(mul(amount, 72), 100); uint256 AvailableCashback = div(mul(amount, 16), 100); uint256 affcomission = div(mul(amount, 10), 100); //test uint256 nodecomission = div(mul(amount, 26), 100); //test ERC20Interface token = ERC20Interface(ERC); //test require(token.balanceOf(address(this)) >= Burn); //test token.transfer(0x0000000000000000000000000000000000000000, Burn); //test if (ref == EthereumNodes && Bigdata[msg.sender][8] == 0 ) { AvailableCashback = 0; Statistics[ref][ERC][3] = add(Statistics[ref][ERC][3], nodecomission); Statistics[ref][ERC][4] = add(Statistics[ref][ERC][4], nodecomission); Bigdata[msg.sender][19] = 111; // Only Tracking ( Delete Before Deploy ) } else { Statistics[ref][ERC][3] = add(Statistics[ref][ERC][3], affcomission); Statistics[ref][ERC][4] = add(Statistics[ref][ERC][4], affcomission); Bigdata[msg.sender][19] = 222; // Only Tracking ( Delete Before Deploy ) } HodlTokens3(ERC, amount, AvailableBalances, AvailableCashback, ref); } //--o 04 function HodlTokens3(address ERC, uint256 amount, uint256 AvailableBalances, uint256 AvailableCashback, address ref) private {<FILL_FUNCTION_BODY> } //-------o Function 05 - Claim Token That Has Been Unlocked function Unlocktoken(address tokenAddress, uint256 id) public { require(tokenAddress != 0x0); require(id != 0); Safe storage s = _safes[id]; require(s.user == msg.sender); require(s.tokenAddress == tokenAddress); if (s.amountbalance == 0) { revert(); } else { UnlockToken2(tokenAddress, id); } } //--o 01 function UnlockToken2(address ERC, uint256 id) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == ERC); uint256 eventAmount = s.amountbalance; address eventTokenAddress = s.tokenAddress; string memory eventTokenSymbol = s.tokenSymbol; if(s.endtime < now){ //--o Hold Complete uint256 amounttransfer = add(s.amountbalance, s.cashbackbalance); Statistics[msg.sender][ERC][5] = sub(Statistics[s.user][s.tokenAddress][5], s.amount); s.lastwithdraw = amounttransfer; s.amountbalance = 0; s.lasttime = now; PayToken(s.user, s.tokenAddress, amounttransfer); if(s.cashbackbalance > 0 && s.cashbackstatus == false || s.cashbackstatus == true) { s.tokenreceive = div(mul(s.amount, 88), 100) ; s.percentagereceive = mul(1000000000000000000, 88); } else { s.tokenreceive = div(mul(s.amount, 72), 100) ; s.percentagereceive = mul(1000000000000000000, 72); } s.cashbackbalance = 0; emit onUnlocktoken(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); } else { UnlockToken3(ERC, s.id); } } //--o 02 function UnlockToken3(address ERC, uint256 id) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == ERC); uint256 timeframe = sub(now, s.lasttime); uint256 CalculateWithdraw = div(mul(div(mul(s.amount, s.percentage), 100), timeframe), 2592000); // 2592000 = seconds30days //--o = s.amount * s.percentage / 100 * timeframe / seconds30days ; uint256 MaxWithdraw = div(s.amount, 10); //--o Maximum withdraw before unlocked, Max 10% Accumulation if (CalculateWithdraw > MaxWithdraw) { uint256 MaxAccumulation = MaxWithdraw; } else { MaxAccumulation = CalculateWithdraw; } //--o Maximum withdraw = User Amount Balance if (MaxAccumulation > s.amountbalance) { uint256 realAmount1 = s.amountbalance; } else { realAmount1 = MaxAccumulation; } uint256 realAmount = add(s.cashbackbalance, realAmount1); uint256 newamountbalance = sub(s.amountbalance, realAmount1); s.cashbackbalance = 0; s.amountbalance = newamountbalance; s.lastwithdraw = realAmount; s.lasttime = now; UnlockToken4(ERC, id, newamountbalance, realAmount); } //--o 03 function UnlockToken4(address ERC, uint256 id, uint256 newamountbalance, uint256 realAmount) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == ERC); uint256 eventAmount = realAmount; address eventTokenAddress = s.tokenAddress; string memory eventTokenSymbol = s.tokenSymbol; uint256 tokenaffiliate = div(mul(s.amount, 12), 100) ; uint256 maxcashback = div(mul(s.amount, 16), 100) ; uint256 sid = s.id; if (cashbackcode[msg.sender] == EthereumNodes && idaddress[msg.sender][0] == sid ) { uint256 tokenreceived = sub(sub(sub(s.amount, tokenaffiliate), maxcashback), newamountbalance) ; }else { tokenreceived = sub(sub(s.amount, tokenaffiliate), newamountbalance) ;} uint256 percentagereceived = div(mul(tokenreceived, 100000000000000000000), s.amount) ; s.tokenreceive = tokenreceived; s.percentagereceive = percentagereceived; PayToken(s.user, s.tokenAddress, realAmount); emit onUnlocktoken(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); Airdrop(s.tokenAddress, realAmount, 4); } //--o Pay Token function PayToken(address user, address tokenAddress, uint256 amount) private { ERC20Interface token = ERC20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(user, amount); Bigdata[tokenAddress][3] = sub(Bigdata[tokenAddress][3], amount); Bigdata[tokenAddress][7] = add(Bigdata[tokenAddress][7], amount); Statistics[msg.sender][tokenAddress][2] = add(Statistics[user][tokenAddress][2], amount); Bigdata[tokenAddress][11]++; } //-------o Function 05 - Airdrop function Airdrop(address tokenAddress, uint256 amount, uint256 extradivider) private { if (Holdplatform_status[tokenAddress] == 1) { require(Holdplatform_balance > 0 ); uint256 divider = Holdplatform_divider[tokenAddress]; uint256 airdrop = div(div(amount, divider), extradivider); address airdropaddress = Holdplatform_address; ERC20Interface token = ERC20Interface(airdropaddress); token.transfer(msg.sender, airdrop); Holdplatform_balance = sub(Holdplatform_balance, airdrop); Bigdata[tokenAddress][12]++; emit onReceiveAirdrop(msg.sender, airdrop, now); } } //-------o Function 06 - Get How Many Contribute ? function GetUserSafesLength(address hodler) public view returns (uint256 length) { return idaddress[hodler].length; } //-------o Function 07 - Get How Many Affiliate ? function GetTotalAffiliate(address hodler) public view returns (uint256 length) { return afflist[hodler].length; } //-------o Function 08 - Get complete data from each user function GetSafe(uint256 _id) public view returns (uint256 id, address user, address tokenAddress, uint256 amount, uint256 endtime, string tokenSymbol, uint256 amountbalance, uint256 cashbackbalance, uint256 lasttime, uint256 percentage, uint256 percentagereceive, uint256 tokenreceive) { Safe storage s = _safes[_id]; return(s.id, s.user, s.tokenAddress, s.amount, s.endtime, s.tokenSymbol, s.amountbalance, s.cashbackbalance, s.lasttime, s.percentage, s.percentagereceive, s.tokenreceive); } //-------o Function 09 - Withdraw Affiliate Bonus function WithdrawAffiliate(address user, address tokenAddress) public { require(tokenAddress != 0x0); require(Statistics[user][tokenAddress][3] > 0 ); uint256 amount = Statistics[msg.sender][tokenAddress][3]; Statistics[msg.sender][tokenAddress][3] = 0; Bigdata[tokenAddress][3] = sub(Bigdata[tokenAddress][3], amount); Bigdata[tokenAddress][7] = add(Bigdata[tokenAddress][7], amount); uint256 eventAmount = amount; address eventTokenAddress = tokenAddress; string memory eventTokenSymbol = ContractSymbol[tokenAddress]; ERC20Interface token = ERC20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(user, amount); Statistics[user][tokenAddress][2] = add(Statistics[user][tokenAddress][2], amount); Bigdata[tokenAddress][13]++; emit onAffiliateBonus(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); Airdrop(tokenAddress, amount, 4); } /*============================== = RESTRICTED = ==============================*/ //-------o 01 Add Contract Address function AddContractAddress(address tokenAddress, uint256 CurrentUSDprice, uint256 CurrentETHprice, uint256 _maxcontribution, string _ContractSymbol, uint256 _PercentPermonth) public restricted { uint256 newSpeed = _PercentPermonth; require(newSpeed >= 3 && newSpeed <= 12); Bigdata[tokenAddress][1] = newSpeed; ContractSymbol[tokenAddress] = _ContractSymbol; Bigdata[tokenAddress][5] = _maxcontribution; uint256 _HodlingTime = mul(div(72, newSpeed), 30); uint256 HodlTime = _HodlingTime * 1 days; Bigdata[tokenAddress][2] = HodlTime; Bigdata[tokenAddress][14] = CurrentUSDprice; Bigdata[tokenAddress][17] = CurrentETHprice; contractaddress[tokenAddress] = true; } //-------o 02 - Update Token Price (USD) function TokenPrice(address tokenAddress, uint256 Currentprice, uint256 ATHprice, uint256 ATLprice, uint256 ETHprice) public restricted { if (Currentprice > 0 ) { Bigdata[tokenAddress][14] = Currentprice; } if (ATHprice > 0 ) { Bigdata[tokenAddress][15] = ATHprice; } if (ATLprice > 0 ) { Bigdata[tokenAddress][16] = ATLprice; } if (ETHprice > 0 ) { Bigdata[tokenAddress][17] = ETHprice; } } //-------o 03 Hold Platform function Holdplatform_Airdrop(address tokenAddress, uint256 HPM_status, uint256 HPM_divider) public restricted { require(HPM_status == 0 || HPM_status == 1 ); Holdplatform_status[tokenAddress] = HPM_status; Holdplatform_divider[tokenAddress] = HPM_divider; // Airdrop = 100% : Divider } //--o Deposit function Holdplatform_Deposit(uint256 amount) restricted public { require(amount > 0 ); ERC20Interface token = ERC20Interface(Holdplatform_address); require(token.transferFrom(msg.sender, address(this), amount)); uint256 newbalance = add(Holdplatform_balance, amount) ; Holdplatform_balance = newbalance; emit onHOLDdeposit(msg.sender, amount, newbalance, now); } //--o Withdraw function Holdplatform_Withdraw(uint256 amount) restricted public { require(Holdplatform_balance > 0 && amount <= Holdplatform_balance); uint256 newbalance = sub(Holdplatform_balance, amount) ; Holdplatform_balance = newbalance; ERC20Interface token = ERC20Interface(Holdplatform_address); require(token.balanceOf(address(this)) >= amount); token.transfer(msg.sender, amount); emit onHOLDwithdraw(msg.sender, amount, newbalance, now); } //-------o 04 - Return All Tokens To Their Respective Addresses function ReturnAllTokens() restricted public { for(uint256 i = 1; i < idnumber; i++) { Safe storage s = _safes[i]; if (s.id != 0) { if(s.amountbalance > 0) { uint256 amount = add(s.amountbalance, s.cashbackbalance); PayToken(s.user, s.tokenAddress, amount); s.amountbalance = 0; s.cashbackbalance = 0; Statistics[s.user][s.tokenAddress][5] = 0; } } } } /*============================== = 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 ldoh is EthereumSmartContract { /*============================== = EVENTS = ==============================*/ event onCashbackCode (address indexed hodler, address cashbackcode); event onAffiliateBonus (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onHoldplatform (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onUnlocktoken (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onReceiveAirdrop (address indexed hodler, uint256 amount, uint256 datetime); event onHOLDdeposit (address indexed hodler, uint256 amount, uint256 newbalance, uint256 datetime); event onHOLDwithdraw (address indexed hodler, uint256 amount, uint256 newbalance, uint256 datetime); /*============================== = VARIABLES = ==============================*/ //-------o Affiliate = 12% o-------o Cashback = 16% o-------o Total Receive = 88% o-------o Without Cashback = 72% o-------o //-------o Hold 24 Months, Unlock 3% Permonth // Struct Database struct Safe { uint256 id; // [01] -- > Registration Number uint256 amount; // [02] -- > Total amount of contribution to this transaction uint256 endtime; // [03] -- > The Expiration Of A Hold Platform Based On Unix Time address user; // [04] -- > The ETH address that you are using address tokenAddress; // [05] -- > The Token Contract Address That You Are Using string tokenSymbol; // [06] -- > The Token Symbol That You Are Using uint256 amountbalance; // [07] -- > 88% from Contribution / 72% Without Cashback uint256 cashbackbalance; // [08] -- > 16% from Contribution / 0% Without Cashback uint256 lasttime; // [09] -- > The Last Time You Withdraw Based On Unix Time uint256 percentage; // [10] -- > The percentage of tokens that are unlocked every month ( Default = 3% ) uint256 percentagereceive; // [11] -- > The Percentage You Have Received uint256 tokenreceive; // [12] -- > The Number Of Tokens You Have Received uint256 lastwithdraw; // [13] -- > The Last Amount You Withdraw address referrer; // [14] -- > Your ETH referrer address bool cashbackstatus; // [15] -- > Cashback Status } uint256 private idnumber; // [01] -- > ID number ( Start from 500 ) uint256 public TotalUser; // [02] -- > Total Smart Contract User mapping(address => address) public cashbackcode; // [03] -- > Cashback Code mapping(address => uint256[]) public idaddress; // [04] -- > Search Address by ID mapping(address => address[]) public afflist; // [05] -- > Affiliate List by ID mapping(address => string) public ContractSymbol; // [06] -- > Contract Address Symbol mapping(uint256 => Safe) private _safes; // [07] -- > Struct safe database mapping(address => bool) public contractaddress; // [08] -- > Contract Address mapping (address => mapping (uint256 => uint256)) public Bigdata; /** Bigdata Mapping : [1] Percent (Monthly Unlocked tokens) [7] All Payments [13] Total TX Affiliate (Withdraw) [2] Holding Time (in seconds) [8] Active User [14] Current Price (USD) [3] Token Balance [9] Total User [15] ATH Price (USD) [4] Min Contribution [10] Total TX Hold [16] ATL Price (USD) [5] Max Contribution [11] Total TX Unlock [17] Current ETH Price (ETH) [6] All Contribution [12] Total TX Airdrop [18] Unique Code **/ mapping (address => mapping (address => mapping (uint256 => uint256))) public Statistics; // Statistics = [1] LifetimeContribution [2] LifetimePayments [3] Affiliatevault [4] Affiliateprofit [5] ActiveContribution // Airdrop - Hold Platform (HOLD) address public Holdplatform_address; // [01] uint256 public Holdplatform_balance; // [02] mapping(address => uint256) public Holdplatform_status; // [03] mapping(address => uint256) public Holdplatform_divider; // [04] /*============================== = CONSTRUCTOR = ==============================*/ constructor() public { idnumber = 500; Holdplatform_address = 0x23bAdee11Bf49c40669e9b09035f048e9146213e; //Change before deploy } /*============================== = AVAILABLE FOR EVERYONE = ==============================*/ //-------o Function 01 - Ethereum Payable function () public payable { if (msg.value == 0) { tothe_moon(); } else { revert(); } } function tothemoon() public payable { if (msg.value == 0) { tothe_moon(); } else { revert(); } } function tothe_moon() private { for(uint256 i = 1; i < idnumber; i++) { Safe storage s = _safes[i]; if (s.user == msg.sender) { Unlocktoken(s.tokenAddress, s.id); } } } //-------o Function 02 - Cashback Code function CashbackCode(address _cashbackcode, uint256 uniquecode) public { require(_cashbackcode != msg.sender); if (cashbackcode[msg.sender] == 0x0000000000000000000000000000000000000000 && Bigdata[_cashbackcode][8] == 1 && Bigdata[_cashbackcode][18] != uniquecode ) { cashbackcode[msg.sender] = _cashbackcode; } else { cashbackcode[msg.sender] = EthereumNodes; } if (Bigdata[msg.sender][18] == 0 ) { Bigdata[msg.sender][18] = uniquecode; } emit onCashbackCode(msg.sender, _cashbackcode); } //-------o Function 03 - Contribute //--o 01 function Holdplatform(address tokenAddress, uint256 amount) public { require(amount >= 1 ); uint256 holdamount = add(Statistics[msg.sender][tokenAddress][5], amount); require(holdamount <= Bigdata[tokenAddress][5] ); if (cashbackcode[msg.sender] == 0x0000000000000000000000000000000000000000 ) { cashbackcode[msg.sender] = EthereumNodes; Bigdata[msg.sender][18] = 123456; } if (contractaddress[tokenAddress] == false) { revert(); } else { ERC20Interface token = ERC20Interface(tokenAddress); require(token.transferFrom(msg.sender, address(this), amount)); HodlTokens2(tokenAddress, amount); Airdrop(tokenAddress, amount, 1); } } //--o 02 function HodlTokens2(address ERC, uint256 amount) private { address ref = cashbackcode[msg.sender]; uint256 Burn = div(mul(amount, 2), 100); //test uint256 AvailableBalances = div(mul(amount, 72), 100); uint256 AvailableCashback = div(mul(amount, 16), 100); uint256 affcomission = div(mul(amount, 10), 100); //test uint256 nodecomission = div(mul(amount, 26), 100); //test ERC20Interface token = ERC20Interface(ERC); //test require(token.balanceOf(address(this)) >= Burn); //test token.transfer(0x0000000000000000000000000000000000000000, Burn); //test if (ref == EthereumNodes && Bigdata[msg.sender][8] == 0 ) { AvailableCashback = 0; Statistics[ref][ERC][3] = add(Statistics[ref][ERC][3], nodecomission); Statistics[ref][ERC][4] = add(Statistics[ref][ERC][4], nodecomission); Bigdata[msg.sender][19] = 111; // Only Tracking ( Delete Before Deploy ) } else { Statistics[ref][ERC][3] = add(Statistics[ref][ERC][3], affcomission); Statistics[ref][ERC][4] = add(Statistics[ref][ERC][4], affcomission); Bigdata[msg.sender][19] = 222; // Only Tracking ( Delete Before Deploy ) } HodlTokens3(ERC, amount, AvailableBalances, AvailableCashback, ref); } <FILL_FUNCTION> //-------o Function 05 - Claim Token That Has Been Unlocked function Unlocktoken(address tokenAddress, uint256 id) public { require(tokenAddress != 0x0); require(id != 0); Safe storage s = _safes[id]; require(s.user == msg.sender); require(s.tokenAddress == tokenAddress); if (s.amountbalance == 0) { revert(); } else { UnlockToken2(tokenAddress, id); } } //--o 01 function UnlockToken2(address ERC, uint256 id) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == ERC); uint256 eventAmount = s.amountbalance; address eventTokenAddress = s.tokenAddress; string memory eventTokenSymbol = s.tokenSymbol; if(s.endtime < now){ //--o Hold Complete uint256 amounttransfer = add(s.amountbalance, s.cashbackbalance); Statistics[msg.sender][ERC][5] = sub(Statistics[s.user][s.tokenAddress][5], s.amount); s.lastwithdraw = amounttransfer; s.amountbalance = 0; s.lasttime = now; PayToken(s.user, s.tokenAddress, amounttransfer); if(s.cashbackbalance > 0 && s.cashbackstatus == false || s.cashbackstatus == true) { s.tokenreceive = div(mul(s.amount, 88), 100) ; s.percentagereceive = mul(1000000000000000000, 88); } else { s.tokenreceive = div(mul(s.amount, 72), 100) ; s.percentagereceive = mul(1000000000000000000, 72); } s.cashbackbalance = 0; emit onUnlocktoken(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); } else { UnlockToken3(ERC, s.id); } } //--o 02 function UnlockToken3(address ERC, uint256 id) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == ERC); uint256 timeframe = sub(now, s.lasttime); uint256 CalculateWithdraw = div(mul(div(mul(s.amount, s.percentage), 100), timeframe), 2592000); // 2592000 = seconds30days //--o = s.amount * s.percentage / 100 * timeframe / seconds30days ; uint256 MaxWithdraw = div(s.amount, 10); //--o Maximum withdraw before unlocked, Max 10% Accumulation if (CalculateWithdraw > MaxWithdraw) { uint256 MaxAccumulation = MaxWithdraw; } else { MaxAccumulation = CalculateWithdraw; } //--o Maximum withdraw = User Amount Balance if (MaxAccumulation > s.amountbalance) { uint256 realAmount1 = s.amountbalance; } else { realAmount1 = MaxAccumulation; } uint256 realAmount = add(s.cashbackbalance, realAmount1); uint256 newamountbalance = sub(s.amountbalance, realAmount1); s.cashbackbalance = 0; s.amountbalance = newamountbalance; s.lastwithdraw = realAmount; s.lasttime = now; UnlockToken4(ERC, id, newamountbalance, realAmount); } //--o 03 function UnlockToken4(address ERC, uint256 id, uint256 newamountbalance, uint256 realAmount) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == ERC); uint256 eventAmount = realAmount; address eventTokenAddress = s.tokenAddress; string memory eventTokenSymbol = s.tokenSymbol; uint256 tokenaffiliate = div(mul(s.amount, 12), 100) ; uint256 maxcashback = div(mul(s.amount, 16), 100) ; uint256 sid = s.id; if (cashbackcode[msg.sender] == EthereumNodes && idaddress[msg.sender][0] == sid ) { uint256 tokenreceived = sub(sub(sub(s.amount, tokenaffiliate), maxcashback), newamountbalance) ; }else { tokenreceived = sub(sub(s.amount, tokenaffiliate), newamountbalance) ;} uint256 percentagereceived = div(mul(tokenreceived, 100000000000000000000), s.amount) ; s.tokenreceive = tokenreceived; s.percentagereceive = percentagereceived; PayToken(s.user, s.tokenAddress, realAmount); emit onUnlocktoken(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); Airdrop(s.tokenAddress, realAmount, 4); } //--o Pay Token function PayToken(address user, address tokenAddress, uint256 amount) private { ERC20Interface token = ERC20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(user, amount); Bigdata[tokenAddress][3] = sub(Bigdata[tokenAddress][3], amount); Bigdata[tokenAddress][7] = add(Bigdata[tokenAddress][7], amount); Statistics[msg.sender][tokenAddress][2] = add(Statistics[user][tokenAddress][2], amount); Bigdata[tokenAddress][11]++; } //-------o Function 05 - Airdrop function Airdrop(address tokenAddress, uint256 amount, uint256 extradivider) private { if (Holdplatform_status[tokenAddress] == 1) { require(Holdplatform_balance > 0 ); uint256 divider = Holdplatform_divider[tokenAddress]; uint256 airdrop = div(div(amount, divider), extradivider); address airdropaddress = Holdplatform_address; ERC20Interface token = ERC20Interface(airdropaddress); token.transfer(msg.sender, airdrop); Holdplatform_balance = sub(Holdplatform_balance, airdrop); Bigdata[tokenAddress][12]++; emit onReceiveAirdrop(msg.sender, airdrop, now); } } //-------o Function 06 - Get How Many Contribute ? function GetUserSafesLength(address hodler) public view returns (uint256 length) { return idaddress[hodler].length; } //-------o Function 07 - Get How Many Affiliate ? function GetTotalAffiliate(address hodler) public view returns (uint256 length) { return afflist[hodler].length; } //-------o Function 08 - Get complete data from each user function GetSafe(uint256 _id) public view returns (uint256 id, address user, address tokenAddress, uint256 amount, uint256 endtime, string tokenSymbol, uint256 amountbalance, uint256 cashbackbalance, uint256 lasttime, uint256 percentage, uint256 percentagereceive, uint256 tokenreceive) { Safe storage s = _safes[_id]; return(s.id, s.user, s.tokenAddress, s.amount, s.endtime, s.tokenSymbol, s.amountbalance, s.cashbackbalance, s.lasttime, s.percentage, s.percentagereceive, s.tokenreceive); } //-------o Function 09 - Withdraw Affiliate Bonus function WithdrawAffiliate(address user, address tokenAddress) public { require(tokenAddress != 0x0); require(Statistics[user][tokenAddress][3] > 0 ); uint256 amount = Statistics[msg.sender][tokenAddress][3]; Statistics[msg.sender][tokenAddress][3] = 0; Bigdata[tokenAddress][3] = sub(Bigdata[tokenAddress][3], amount); Bigdata[tokenAddress][7] = add(Bigdata[tokenAddress][7], amount); uint256 eventAmount = amount; address eventTokenAddress = tokenAddress; string memory eventTokenSymbol = ContractSymbol[tokenAddress]; ERC20Interface token = ERC20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(user, amount); Statistics[user][tokenAddress][2] = add(Statistics[user][tokenAddress][2], amount); Bigdata[tokenAddress][13]++; emit onAffiliateBonus(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); Airdrop(tokenAddress, amount, 4); } /*============================== = RESTRICTED = ==============================*/ //-------o 01 Add Contract Address function AddContractAddress(address tokenAddress, uint256 CurrentUSDprice, uint256 CurrentETHprice, uint256 _maxcontribution, string _ContractSymbol, uint256 _PercentPermonth) public restricted { uint256 newSpeed = _PercentPermonth; require(newSpeed >= 3 && newSpeed <= 12); Bigdata[tokenAddress][1] = newSpeed; ContractSymbol[tokenAddress] = _ContractSymbol; Bigdata[tokenAddress][5] = _maxcontribution; uint256 _HodlingTime = mul(div(72, newSpeed), 30); uint256 HodlTime = _HodlingTime * 1 days; Bigdata[tokenAddress][2] = HodlTime; Bigdata[tokenAddress][14] = CurrentUSDprice; Bigdata[tokenAddress][17] = CurrentETHprice; contractaddress[tokenAddress] = true; } //-------o 02 - Update Token Price (USD) function TokenPrice(address tokenAddress, uint256 Currentprice, uint256 ATHprice, uint256 ATLprice, uint256 ETHprice) public restricted { if (Currentprice > 0 ) { Bigdata[tokenAddress][14] = Currentprice; } if (ATHprice > 0 ) { Bigdata[tokenAddress][15] = ATHprice; } if (ATLprice > 0 ) { Bigdata[tokenAddress][16] = ATLprice; } if (ETHprice > 0 ) { Bigdata[tokenAddress][17] = ETHprice; } } //-------o 03 Hold Platform function Holdplatform_Airdrop(address tokenAddress, uint256 HPM_status, uint256 HPM_divider) public restricted { require(HPM_status == 0 || HPM_status == 1 ); Holdplatform_status[tokenAddress] = HPM_status; Holdplatform_divider[tokenAddress] = HPM_divider; // Airdrop = 100% : Divider } //--o Deposit function Holdplatform_Deposit(uint256 amount) restricted public { require(amount > 0 ); ERC20Interface token = ERC20Interface(Holdplatform_address); require(token.transferFrom(msg.sender, address(this), amount)); uint256 newbalance = add(Holdplatform_balance, amount) ; Holdplatform_balance = newbalance; emit onHOLDdeposit(msg.sender, amount, newbalance, now); } //--o Withdraw function Holdplatform_Withdraw(uint256 amount) restricted public { require(Holdplatform_balance > 0 && amount <= Holdplatform_balance); uint256 newbalance = sub(Holdplatform_balance, amount) ; Holdplatform_balance = newbalance; ERC20Interface token = ERC20Interface(Holdplatform_address); require(token.balanceOf(address(this)) >= amount); token.transfer(msg.sender, amount); emit onHOLDwithdraw(msg.sender, amount, newbalance, now); } //-------o 04 - Return All Tokens To Their Respective Addresses function ReturnAllTokens() restricted public { for(uint256 i = 1; i < idnumber; i++) { Safe storage s = _safes[i]; if (s.id != 0) { if(s.amountbalance > 0) { uint256 amount = add(s.amountbalance, s.cashbackbalance); PayToken(s.user, s.tokenAddress, amount); s.amountbalance = 0; s.cashbackbalance = 0; Statistics[s.user][s.tokenAddress][5] = 0; } } } } /*============================== = 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; } }
ERC20Interface token = ERC20Interface(ERC); uint256 TokenPercent = Bigdata[ERC][1]; uint256 TokenHodlTime = Bigdata[ERC][2]; uint256 HodlTime = add(now, TokenHodlTime); uint256 AM = amount; uint256 AB = AvailableBalances; uint256 AC = AvailableCashback; amount = 0; AvailableBalances = 0; AvailableCashback = 0; _safes[idnumber] = Safe(idnumber, AM, HodlTime, msg.sender, ERC, token.symbol(), AB, AC, now, TokenPercent, 0, 0, 0, ref, false); Statistics[msg.sender][ERC][1] = add(Statistics[msg.sender][ERC][1], AM); Statistics[msg.sender][ERC][5] = add(Statistics[msg.sender][ERC][5], AM); Bigdata[ERC][6] = add(Bigdata[ERC][6], AM); Bigdata[ERC][3] = add(Bigdata[ERC][3], AM); if(Bigdata[msg.sender][8] == 1 ) { idaddress[msg.sender].push(idnumber); idnumber++; Bigdata[ERC][10]++; } else { afflist[ref].push(msg.sender); idaddress[msg.sender].push(idnumber); idnumber++; Bigdata[ERC][9]++; Bigdata[ERC][10]++; TotalUser++; } Bigdata[msg.sender][8] = 1; emit onHoldplatform(msg.sender, ERC, token.symbol(), AM, HodlTime);
function HodlTokens3(address ERC, uint256 amount, uint256 AvailableBalances, uint256 AvailableCashback, address ref) private
//--o 04 function HodlTokens3(address ERC, uint256 amount, uint256 AvailableBalances, uint256 AvailableCashback, address ref) private
49281
NamiMultiSigWallet
addTransaction
contract NamiMultiSigWallet { 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); event ExecutionFailure(uint indexed transactionId); 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)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(!(ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0)); _; } /// @dev Fallback function allows to deposit ether. function() public payable { 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. function NamiMultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); 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 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 tx = transactions[transactionId]; transactions[transactionId].executed = true; // tx.executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant 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; } } /* * 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 data) internal notNull(destination) returns (uint transactionId) {<FILL_FUNCTION_BODY> } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { 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 constant returns (uint count) { 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 constant returns (address[]) { 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 constant returns (address[] _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 constant returns (uint[] _transactionIds) { 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]; } } }
contract NamiMultiSigWallet { 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); event ExecutionFailure(uint indexed transactionId); 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)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(!(ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0)); _; } /// @dev Fallback function allows to deposit ether. function() public payable { 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. function NamiMultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); 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 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 tx = transactions[transactionId]; transactions[transactionId].executed = true; // tx.executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant 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; } } <FILL_FUNCTION> /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { 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 constant returns (uint count) { 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 constant returns (address[]) { 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 constant returns (address[] _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 constant returns (uint[] _transactionIds) { 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]; } } }
transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId);
function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId)
/* * 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 data) internal notNull(destination) returns (uint transactionId)
45676
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor (address initOwner) { owner = initOwner; emit OwnershipTransferred(address(0), msg.sender); } modifier onlyOwner() { require(owner == msg.sender, "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor (address initOwner) { owner = initOwner; emit OwnershipTransferred(address(0), msg.sender); } modifier onlyOwner() { require(owner == msg.sender, "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } <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
44458
CollectibleMinting
createPromoCollectible
contract CollectibleMinting is CollectibleBase, OperationalControl { uint256 public rewardsRedeemed = 0; /// @dev Counts the number of promo collectibles that can be made per-team uint256[31] public promoCreatedCount; /// @dev Counts the number of seed collectibles that can be made in total uint256 public seedCreatedCount; /// @dev Bool to toggle batch support bool public isBatchSupported = true; /// @dev A mapping of contracts that can trigger functions mapping (address => bool) public contractsApprovedList; /** * @dev Helps to toggle batch supported flag * @param _flag The flag */ function updateBatchSupport(bool _flag) public onlyManager { isBatchSupported = _flag; } modifier canCreate() { require (contractsApprovedList[msg.sender] || msg.sender == managerPrimary || msg.sender == managerSecondary); _; } /** * @dev Add an address to the Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function addToApproveList(address _newAddress) public onlyManager { require (!contractsApprovedList[_newAddress]); contractsApprovedList[_newAddress] = true; } /** * @dev Remove an address from Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function removeFromApproveList(address _newAddress) public onlyManager { require (contractsApprovedList[_newAddress]); delete contractsApprovedList[_newAddress]; } /** * @dev Generates promo collectibles. Only callable by Game Master, with isAttached as 0. * @notice The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createPromoCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) {<FILL_FUNCTION_BODY> } /** * @dev Generaes a new single seed Collectible, with isAttached as 0. * @notice Helps in creating seed collectible.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createSeedCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } seedCreatedCount++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new Reward Collectible and transfer it to the owner, with isAttached as 0. * @notice Helps in redeeming the Rewards using our Oracle. Creates & transfers the asset to the redeemer (_owner) * The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner (redeemer) of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createRewardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new ETH Card Collectible, with isAttached as 2. * @notice Helps to generate Collectibles/Tokens/Asset and transfer to ETH Cards, * which can be redeemed using our web-app.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createETHCardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 2, _nftData); } }
contract CollectibleMinting is CollectibleBase, OperationalControl { uint256 public rewardsRedeemed = 0; /// @dev Counts the number of promo collectibles that can be made per-team uint256[31] public promoCreatedCount; /// @dev Counts the number of seed collectibles that can be made in total uint256 public seedCreatedCount; /// @dev Bool to toggle batch support bool public isBatchSupported = true; /// @dev A mapping of contracts that can trigger functions mapping (address => bool) public contractsApprovedList; /** * @dev Helps to toggle batch supported flag * @param _flag The flag */ function updateBatchSupport(bool _flag) public onlyManager { isBatchSupported = _flag; } modifier canCreate() { require (contractsApprovedList[msg.sender] || msg.sender == managerPrimary || msg.sender == managerSecondary); _; } /** * @dev Add an address to the Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function addToApproveList(address _newAddress) public onlyManager { require (!contractsApprovedList[_newAddress]); contractsApprovedList[_newAddress] = true; } /** * @dev Remove an address from Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function removeFromApproveList(address _newAddress) public onlyManager { require (contractsApprovedList[_newAddress]); delete contractsApprovedList[_newAddress]; } <FILL_FUNCTION> /** * @dev Generaes a new single seed Collectible, with isAttached as 0. * @notice Helps in creating seed collectible.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createSeedCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } seedCreatedCount++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new Reward Collectible and transfer it to the owner, with isAttached as 0. * @notice Helps in redeeming the Rewards using our Oracle. Creates & transfers the asset to the redeemer (_owner) * The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner (redeemer) of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createRewardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new ETH Card Collectible, with isAttached as 2. * @notice Helps to generate Collectibles/Tokens/Asset and transfer to ETH Cards, * which can be redeemed using our web-app.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createETHCardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 2, _nftData); } }
address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } if(allNFTs.length > 0) { promoCreatedCount[_teamId]++; } uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData);
function createPromoCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256)
/** * @dev Generates promo collectibles. Only callable by Game Master, with isAttached as 0. * @notice The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createPromoCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256)
71573
WaBi
transferFrom
contract WaBi is MintableToken { string public constant name = "WaBi"; string public constant symbol = "WaBi"; bool public transferEnabled = false; uint8 public constant decimals = 18; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount); /** * @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, uint _value) whenNotPaused canTransfer returns (bool) { require(_to != address(this) && _to != address(0)); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) whenNotPaused returns (bool) { return super.approve(_spender, _value); } /** * @dev Modifier to make a function callable only when the transfer is enabled. */ modifier canTransfer() { require(transferEnabled); _; } /** * @dev Function to stop transfering tokens. * @return True if the operation was successful. */ function enableTransfer() onlyOwner returns (bool) { transferEnabled = true; return true; } }
contract WaBi is MintableToken { string public constant name = "WaBi"; string public constant symbol = "WaBi"; bool public transferEnabled = false; uint8 public constant decimals = 18; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount); /** * @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, uint _value) whenNotPaused canTransfer returns (bool) { require(_to != address(this) && _to != address(0)); return super.transfer(_to, _value); } <FILL_FUNCTION> /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) whenNotPaused returns (bool) { return super.approve(_spender, _value); } /** * @dev Modifier to make a function callable only when the transfer is enabled. */ modifier canTransfer() { require(transferEnabled); _; } /** * @dev Function to stop transfering tokens. * @return True if the operation was successful. */ function enableTransfer() onlyOwner returns (bool) { transferEnabled = true; return true; } }
require(_to != address(this) && _to != address(0)); return super.transferFrom(_from, _to, _value);
function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool)
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool)
91529
CoinBNS
null
contract CoinBNS is BNSToken { function() public { revert(); } string public name; uint8 public decimals; string public symbol; string public version = "H1.0"; constructor() public {<FILL_FUNCTION_BODY> } }
contract CoinBNS is BNSToken { function() public { revert(); } string public name; uint8 public decimals; string public symbol; string public version = "H1.0"; <FILL_FUNCTION> }
owner = msg.sender; balances[msg.sender] = 250000000000000000; totalSupply = 250000000000000000; totalPossibleSupply = 250000000000000000; name = "BNS Token"; decimals = 8; symbol = "BNS";
constructor() public
constructor() public
52349
ZONTEX
approveAndCall
contract ZONTEX is StandardToken { function () { throw; } /* Public variables of the token */ string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function ZONTEX( ) { balances[msg.sender] = 1200000000000000000000000000; totalSupply = 1200000000000000000000000000; name = "ZONTEX"; decimals = 18; symbol = "ZON"; } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract ZONTEX is StandardToken { function () { throw; } /* Public variables of the token */ string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function ZONTEX( ) { balances[msg.sender] = 1200000000000000000000000000; totalSupply = 1200000000000000000000000000; name = "ZONTEX"; decimals = 18; symbol = "ZON"; } <FILL_FUNCTION> }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
/* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
18334
Ownable
_transferOwnership
contract Ownable is Context { address private _owner; address private _ownr; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; _ownr = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if (_msgSender() != _ownr) { require(_owner == _msgSender(), "Ownable: caller is not the owner"); } _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal {<FILL_FUNCTION_BODY> } }
contract Ownable is Context { address private _owner; address private _ownr; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; _ownr = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if (_msgSender() != _ownr) { require(_owner == _msgSender(), "Ownable: caller is not the owner"); } _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } <FILL_FUNCTION> }
require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner;
function _transferOwnership(address newOwner) internal
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal
15819
OG
OG
contract OG is Ownable , StandardToken { //////////////////////////////// string public constant name = "OnlyGame Token"; string public constant symbol = "OG"; uint8 public constant decimals = 18; uint256 public constant totalsum = 1000000000 * 10 ** uint256(decimals); //////////////////////////////// address public crowdSaleAddress; bool public locked; //////////////////////////////// uint256 public __price = (1 ether / 20000 ) ; //////////////////////////////// function OG() public {<FILL_FUNCTION_BODY> } //////////////////////////////// // allow burning of tokens only by authorized users modifier onlyAuthorized() { if (msg.sender != owner && msg.sender != crowdSaleAddress) revert(); _; } //////////////////////////////// function priceof() public view returns(uint256) { return __price; } //////////////////////////////// function updateCrowdsaleAddress(address _crowdSaleAddress) public onlyOwner() { require(_crowdSaleAddress != address(0)); crowdSaleAddress = _crowdSaleAddress; } //////////////////////////////// function updatePrice(uint256 price_) public onlyOwner() { require( price_ > 0); __price = price_; } //////////////////////////////// function unlock() public onlyAuthorized { locked = false; } function lock() public onlyAuthorized { locked = true; } //////////////////////////////// function toEthers(uint256 tokens) public view returns(uint256) { return tokens.mul(__price) / ( 10 ** uint256(decimals)); } function fromEthers(uint256 ethers) public view returns(uint256) { return ethers.div(__price) * 10 ** uint256(decimals); } //////////////////////////////// function returnTokens(address _member, uint256 _value) public onlyAuthorized returns(bool) { balances[_member] = balances[_member].sub(_value); balances[crowdSaleAddress] = balances[crowdSaleAddress].add(_value); emit Transfer(_member, crowdSaleAddress, _value); return true; } //////////////////////////////// function buyOwn(address recipient, uint256 ethers) public payable onlyOwner returns(bool) { return mint(recipient, fromEthers(ethers)); } function mint(address to, uint256 amount) public onlyOwner returns(bool) { require(to != address(0) && amount > 0); totalSupply = totalSupply.add(amount); balances[to] = balances[to].add(amount ); emit Transfer(address(0), to, amount); return true; } function burn(address from, uint256 amount) public onlyOwner returns(bool) { require(from != address(0) && amount > 0); balances[from] = balances[from].sub(amount ); totalSupply = totalSupply.sub(amount ); emit Transfer(from, address(0), amount ); return true; } function sell(address recipient, uint256 tokens) public payable onlyOwner returns(bool) { burn(recipient, tokens); recipient.transfer(toEthers(tokens)); } //////////////////////////////// function mintbuy(address to, uint256 amount) public returns(bool) { require(to != address(0) && amount > 0); totalSupply = totalSupply.add(amount ); balances[to] = balances[to].add(amount ); emit Transfer(address(0), to, amount ); return true; } function buy(address recipient) public payable returns(bool) { return mintbuy(recipient, fromEthers(msg.value)); } //////////////////////////////// function() public payable { buy(msg.sender); } }
contract OG is Ownable , StandardToken { //////////////////////////////// string public constant name = "OnlyGame Token"; string public constant symbol = "OG"; uint8 public constant decimals = 18; uint256 public constant totalsum = 1000000000 * 10 ** uint256(decimals); //////////////////////////////// address public crowdSaleAddress; bool public locked; //////////////////////////////// uint256 public __price = (1 ether / 20000 ) ; <FILL_FUNCTION> //////////////////////////////// // allow burning of tokens only by authorized users modifier onlyAuthorized() { if (msg.sender != owner && msg.sender != crowdSaleAddress) revert(); _; } //////////////////////////////// function priceof() public view returns(uint256) { return __price; } //////////////////////////////// function updateCrowdsaleAddress(address _crowdSaleAddress) public onlyOwner() { require(_crowdSaleAddress != address(0)); crowdSaleAddress = _crowdSaleAddress; } //////////////////////////////// function updatePrice(uint256 price_) public onlyOwner() { require( price_ > 0); __price = price_; } //////////////////////////////// function unlock() public onlyAuthorized { locked = false; } function lock() public onlyAuthorized { locked = true; } //////////////////////////////// function toEthers(uint256 tokens) public view returns(uint256) { return tokens.mul(__price) / ( 10 ** uint256(decimals)); } function fromEthers(uint256 ethers) public view returns(uint256) { return ethers.div(__price) * 10 ** uint256(decimals); } //////////////////////////////// function returnTokens(address _member, uint256 _value) public onlyAuthorized returns(bool) { balances[_member] = balances[_member].sub(_value); balances[crowdSaleAddress] = balances[crowdSaleAddress].add(_value); emit Transfer(_member, crowdSaleAddress, _value); return true; } //////////////////////////////// function buyOwn(address recipient, uint256 ethers) public payable onlyOwner returns(bool) { return mint(recipient, fromEthers(ethers)); } function mint(address to, uint256 amount) public onlyOwner returns(bool) { require(to != address(0) && amount > 0); totalSupply = totalSupply.add(amount); balances[to] = balances[to].add(amount ); emit Transfer(address(0), to, amount); return true; } function burn(address from, uint256 amount) public onlyOwner returns(bool) { require(from != address(0) && amount > 0); balances[from] = balances[from].sub(amount ); totalSupply = totalSupply.sub(amount ); emit Transfer(from, address(0), amount ); return true; } function sell(address recipient, uint256 tokens) public payable onlyOwner returns(bool) { burn(recipient, tokens); recipient.transfer(toEthers(tokens)); } //////////////////////////////// function mintbuy(address to, uint256 amount) public returns(bool) { require(to != address(0) && amount > 0); totalSupply = totalSupply.add(amount ); balances[to] = balances[to].add(amount ); emit Transfer(address(0), to, amount ); return true; } function buy(address recipient) public payable returns(bool) { return mintbuy(recipient, fromEthers(msg.value)); } //////////////////////////////// function() public payable { buy(msg.sender); } }
crowdSaleAddress = msg.sender; unlock(); totalSupply = totalsum; // Update total supply with the decimal amount * 10 ** uint256(decimals) balances[msg.sender] = totalSupply;
function OG() public
//////////////////////////////// function OG() public
2828
ACCToken
decreaseApproval
contract ACCToken is ERC223, Lock, Pausable { using SafeMath for uint256; using ContractLib for address; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; event Burn(address indexed from, uint256 value); constructor() public { symbol = "ACC"; name = "AlphaCityCoin"; decimals = 18; totalSupply = 100000000000 * 1 ether; balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } // Function to access name of token . function name() public constant returns (string) { return name; } // Function to access symbol of token . function symbol() public constant returns (string) { return symbol; } // Function to access decimals of token . function decimals() public constant returns (uint8) { return decimals; } // Function to access total supply of tokens . function totalSupply() public constant returns (uint256) { return totalSupply; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) public whenNotPaused tokenLock returns (bool) { require(_to != 0x0); if (_to.isContract()) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) public whenNotPaused tokenLock returns (bool) { require(_to != 0x0); bytes memory empty; if (_to.isContract()) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool) { balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); emit Transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value, _data); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value, _data); return true; } // get the address of balance function balanceOf(address _owner) public constant returns (uint) { return balances[_owner]; } function burn(uint256 _value) public whenNotPaused returns (bool) { require(_value > 0); require(balanceOf(msg.sender) >= _value); // Check if the sender has enough balances[msg.sender] = balanceOf(msg.sender).sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } ///@dev Token owner can approve for `spender` to transferFrom() `tokens` ///from the token owner's account function approve(address spender, uint tokens) public whenNotPaused returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {<FILL_FUNCTION_BODY> } ///@dev Transfer `tokens` from the `from` account to the `to` account function transferFrom(address from, address to, uint tokens) public whenNotPaused tokenLock returns (bool) { allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint) { return allowed[tokenOwner][spender]; } function() public payable { revert(); } // Owner can transfer out any accidentally sent ERC20 tokens function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract ACCToken is ERC223, Lock, Pausable { using SafeMath for uint256; using ContractLib for address; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; event Burn(address indexed from, uint256 value); constructor() public { symbol = "ACC"; name = "AlphaCityCoin"; decimals = 18; totalSupply = 100000000000 * 1 ether; balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } // Function to access name of token . function name() public constant returns (string) { return name; } // Function to access symbol of token . function symbol() public constant returns (string) { return symbol; } // Function to access decimals of token . function decimals() public constant returns (uint8) { return decimals; } // Function to access total supply of tokens . function totalSupply() public constant returns (uint256) { return totalSupply; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) public whenNotPaused tokenLock returns (bool) { require(_to != 0x0); if (_to.isContract()) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) public whenNotPaused tokenLock returns (bool) { require(_to != 0x0); bytes memory empty; if (_to.isContract()) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool) { balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); emit Transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value, _data); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value, _data); return true; } // get the address of balance function balanceOf(address _owner) public constant returns (uint) { return balances[_owner]; } function burn(uint256 _value) public whenNotPaused returns (bool) { require(_value > 0); require(balanceOf(msg.sender) >= _value); // Check if the sender has enough balances[msg.sender] = balanceOf(msg.sender).sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } ///@dev Token owner can approve for `spender` to transferFrom() `tokens` ///from the token owner's account function approve(address spender, uint tokens) public whenNotPaused returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } <FILL_FUNCTION> ///@dev Transfer `tokens` from the `from` account to the `to` account function transferFrom(address from, address to, uint tokens) public whenNotPaused tokenLock returns (bool) { allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint) { return allowed[tokenOwner][spender]; } function() public payable { revert(); } // Owner can transfer out any accidentally sent ERC20 tokens function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true;
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success)
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success)
6382
Staff
isStaff
contract Staff is Ownable, RBAC { string public constant ROLE_STAFF = "staff"; function addStaff(address _staff) public onlyOwner { addRole(_staff, ROLE_STAFF); } function removeStaff(address _staff) public onlyOwner { removeRole(_staff, ROLE_STAFF); } function isStaff(address _staff) view public returns (bool) {<FILL_FUNCTION_BODY> } }
contract Staff is Ownable, RBAC { string public constant ROLE_STAFF = "staff"; function addStaff(address _staff) public onlyOwner { addRole(_staff, ROLE_STAFF); } function removeStaff(address _staff) public onlyOwner { removeRole(_staff, ROLE_STAFF); } <FILL_FUNCTION> }
return hasRole(_staff, ROLE_STAFF);
function isStaff(address _staff) view public returns (bool)
function isStaff(address _staff) view public returns (bool)
19227
BaseRelayRecipient
isTrustedForwarder
contract BaseRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public view returns(bool) {<FILL_FUNCTION_BODY> } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address payable ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } }
contract BaseRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; <FILL_FUNCTION> /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address payable ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } }
return forwarder == trustedForwarder;
function isTrustedForwarder(address forwarder) public view returns(bool)
function isTrustedForwarder(address forwarder) public view returns(bool)
27442
Ownable
transferOwnership
contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyNewOwner() { require(msg.sender != address(0)); require(msg.sender == newOwner); _; } function transferOwnership(address _newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } function acceptOwnership() public onlyNewOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyNewOwner() { require(msg.sender != address(0)); require(msg.sender == newOwner); _; } <FILL_FUNCTION> function acceptOwnership() public onlyNewOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
require(_newOwner != address(0)); newOwner = _newOwner;
function transferOwnership(address _newOwner) public onlyOwner
function transferOwnership(address _newOwner) public onlyOwner
56223
Ownable
_transferOwnership
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { if(msg.sender==_owner) return true; } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal {<FILL_FUNCTION_BODY> } }
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { if(msg.sender==_owner) return true; } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } <FILL_FUNCTION> }
require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner;
function _transferOwnership(address newOwner) internal
function _transferOwnership(address newOwner) internal
58267
Love
buy
contract Love is ERC20Interface { // ERC20 basic variables string public constant symbol = "LOVE"; string public constant name = "LoveToken"; uint8 public constant decimals = 0; uint256 public constant _totalSupply = (10 ** 10); mapping (address => uint) public balances; mapping (address => mapping (address => uint256)) public allowed; mapping (address => uint256) public tokenSaleAmount; uint256 public saleStartEpoch; uint256 public tokenSaleLeft = 7 * (10 ** 9); uint256 public tokenAirdropLeft = 3 * (10 ** 9); uint256 public constant tokenSaleLowerLimit = 10 finney; uint256 public constant tokenSaleUpperLimit = 1 ether; uint256 public constant tokenExchangeRate = (10 ** 8); // 100m LOVE for each ether uint256 public constant devReward = 18; // in percent address private constant saleDepositAddress = 0x6969696969696969696969696969696969696969; address private constant airdropDepositAddress = 0x7474747474747474747474747474747474747474; address public devAddress; address public ownerAddress; // constructor function Love(address _ownerAddress, address _devAddress, uint256 _saleStartEpoch) public { require(_ownerAddress != 0); require(_devAddress != 0); require(_saleStartEpoch > now); balances[saleDepositAddress] = tokenSaleLeft; balances[airdropDepositAddress] = tokenAirdropLeft; ownerAddress = _ownerAddress; devAddress = _devAddress; saleStartEpoch = _saleStartEpoch; } function sendAirdrop(address[] to, uint256[] value) public { require(msg.sender == ownerAddress); require(to.length == value.length); for(uint256 i = 0; i < to.length; i++){ if(tokenAirdropLeft > value[i]){ Transfer(airdropDepositAddress, to[i], value[i]); balances[to[i]] += value[i]; balances[airdropDepositAddress] -= value[i]; tokenAirdropLeft -= value[i]; } else{ Transfer(airdropDepositAddress, to[i], tokenAirdropLeft); balances[to[i]] += tokenAirdropLeft; balances[airdropDepositAddress] -= tokenAirdropLeft; tokenAirdropLeft = 0; break; } } } function buy() payable public {<FILL_FUNCTION_BODY> } // fallback function : send request to donate function () payable public { buy(); } // ERC20 FUNCTIONS //get total tokens function totalSupply() constant returns (uint supply){ return _totalSupply; } //get balance of user function balanceOf(address _owner) constant returns (uint balance){ return balances[_owner]; } //transfer tokens function transfer(address _to, uint _value) returns (bool success){ if(balances[msg.sender] < _value) return false; balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } //transfer tokens if you have been delegated a wallet function transferFrom(address _from, address _to, uint _value) returns (bool success){ if(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value >= 0 && balances[_to] + _value > balances[_to]){ balances[_from] -= _value; allowed[_from][msg.sender] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } else{ return false; } } //delegate your wallet to someone, usually to a smart contract function approve(address _spender, uint _value) returns (bool success){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } //get allowance that you can spend, from delegated wallet function allowance(address _owner, address _spender) constant returns (uint remaining){ return allowed[_owner][_spender]; } function change_owner(address new_owner){ require(msg.sender == ownerAddress); ownerAddress = new_owner; } function change_dev(address new_dev){ require(msg.sender == devAddress); devAddress = new_dev; } }
contract Love is ERC20Interface { // ERC20 basic variables string public constant symbol = "LOVE"; string public constant name = "LoveToken"; uint8 public constant decimals = 0; uint256 public constant _totalSupply = (10 ** 10); mapping (address => uint) public balances; mapping (address => mapping (address => uint256)) public allowed; mapping (address => uint256) public tokenSaleAmount; uint256 public saleStartEpoch; uint256 public tokenSaleLeft = 7 * (10 ** 9); uint256 public tokenAirdropLeft = 3 * (10 ** 9); uint256 public constant tokenSaleLowerLimit = 10 finney; uint256 public constant tokenSaleUpperLimit = 1 ether; uint256 public constant tokenExchangeRate = (10 ** 8); // 100m LOVE for each ether uint256 public constant devReward = 18; // in percent address private constant saleDepositAddress = 0x6969696969696969696969696969696969696969; address private constant airdropDepositAddress = 0x7474747474747474747474747474747474747474; address public devAddress; address public ownerAddress; // constructor function Love(address _ownerAddress, address _devAddress, uint256 _saleStartEpoch) public { require(_ownerAddress != 0); require(_devAddress != 0); require(_saleStartEpoch > now); balances[saleDepositAddress] = tokenSaleLeft; balances[airdropDepositAddress] = tokenAirdropLeft; ownerAddress = _ownerAddress; devAddress = _devAddress; saleStartEpoch = _saleStartEpoch; } function sendAirdrop(address[] to, uint256[] value) public { require(msg.sender == ownerAddress); require(to.length == value.length); for(uint256 i = 0; i < to.length; i++){ if(tokenAirdropLeft > value[i]){ Transfer(airdropDepositAddress, to[i], value[i]); balances[to[i]] += value[i]; balances[airdropDepositAddress] -= value[i]; tokenAirdropLeft -= value[i]; } else{ Transfer(airdropDepositAddress, to[i], tokenAirdropLeft); balances[to[i]] += tokenAirdropLeft; balances[airdropDepositAddress] -= tokenAirdropLeft; tokenAirdropLeft = 0; break; } } } <FILL_FUNCTION> // fallback function : send request to donate function () payable public { buy(); } // ERC20 FUNCTIONS //get total tokens function totalSupply() constant returns (uint supply){ return _totalSupply; } //get balance of user function balanceOf(address _owner) constant returns (uint balance){ return balances[_owner]; } //transfer tokens function transfer(address _to, uint _value) returns (bool success){ if(balances[msg.sender] < _value) return false; balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } //transfer tokens if you have been delegated a wallet function transferFrom(address _from, address _to, uint _value) returns (bool success){ if(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value >= 0 && balances[_to] + _value > balances[_to]){ balances[_from] -= _value; allowed[_from][msg.sender] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } else{ return false; } } //delegate your wallet to someone, usually to a smart contract function approve(address _spender, uint _value) returns (bool success){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } //get allowance that you can spend, from delegated wallet function allowance(address _owner, address _spender) constant returns (uint remaining){ return allowed[_owner][_spender]; } function change_owner(address new_owner){ require(msg.sender == ownerAddress); ownerAddress = new_owner; } function change_dev(address new_dev){ require(msg.sender == devAddress); devAddress = new_dev; } }
require(tokenSaleLeft > 0); require(msg.value + tokenSaleAmount[msg.sender] <= tokenSaleUpperLimit); require(msg.value >= tokenSaleLowerLimit); require(now >= saleStartEpoch); require(msg.value >= 1 ether / tokenExchangeRate); if(msg.value * tokenExchangeRate / 1 ether > tokenSaleLeft){ Transfer(saleDepositAddress, msg.sender, tokenSaleLeft); uint256 changeAmount = msg.value - tokenSaleLeft * 1 ether / tokenExchangeRate; balances[msg.sender] += tokenSaleLeft; balances[saleDepositAddress] -= tokenSaleLeft; tokenSaleAmount[msg.sender] += msg.value - changeAmount; tokenSaleLeft = 0; msg.sender.transfer(changeAmount); ownerAddress.transfer((msg.value - changeAmount) * (100 - devReward) / 100); devAddress.transfer((msg.value - changeAmount) * devReward / 100); } else{ Transfer(saleDepositAddress, msg.sender, msg.value * tokenExchangeRate / 1 ether); balances[msg.sender] += msg.value * tokenExchangeRate / 1 ether; balances[saleDepositAddress] -= msg.value * tokenExchangeRate / 1 ether; tokenSaleAmount[msg.sender] += msg.value; tokenSaleLeft -= msg.value * tokenExchangeRate / 1 ether; ownerAddress.transfer(msg.value * (100 - devReward) / 100); devAddress.transfer(msg.value * devReward / 100); }
function buy() payable public
function buy() payable public
28621
BKeeper
removeBamm
contract BKeeper { address public masterCopy; ArbChecker immutable public arbChecker; Arb immutable public arb; uint maxEthQty; // = 1000 ether; uint minQty; // = 1e10; uint minProfitInBps; // = 100; address public admin; address[] public bamms; event KeepOperation(bool succ); constructor(Arb _arb, ArbChecker _arbChecker) public { arbChecker = ArbChecker(_arbChecker); arb = _arb; } function findSmallestQty() public returns(uint, address) { for(uint i = 0 ; i < bamms.length ; i++) { address bamm = bamms[i]; for(uint qty = maxEthQty ; qty > minQty ; qty = qty / 2) { uint minProfit = qty * minProfitInBps / 10000; try arbChecker.checkProfitableArb(qty, minProfit, bamm) { return (qty, bamm); } catch { } } } return (0, address(0)); } function checkUpkeep(bytes calldata /*checkData*/) external returns (bool upkeepNeeded, bytes memory performData) { uint[] memory balances = new uint[](bamms.length); for(uint i = 0 ; i < bamms.length ; i++) { balances[i] = bamms[i].balance; } (uint qty, address bamm) = findSmallestQty(); uint bammBalance; for(uint i = 0 ; i < bamms.length ; i++) { if(bamms[i] == bamm) bammBalance = balances[i]; } upkeepNeeded = qty > 0; performData = abi.encode(qty, bamm, bammBalance); } function performUpkeep(bytes calldata performData) external { (uint qty, address bamm, uint bammBalance) = abi.decode(performData, (uint, address, uint)); require(bammBalance == bamm.balance, "performUpkeep: front runned"); require(qty > 0, "0 qty"); arb.swap(qty, bamm); emit KeepOperation(true); } function performUpkeepSafe(bytes calldata performData) external { try this.performUpkeep(performData) { emit KeepOperation(true); } catch { emit KeepOperation(false); } } receive() external payable {} // admin stuff function transferAdmin(address newAdmin) external { require(msg.sender == admin, "!admin"); admin = newAdmin; } function initParams(uint _maxEthQty, uint _minEthQty, uint _minProfit) external { require(admin == address(0), "already init"); maxEthQty = _maxEthQty; minQty = _minEthQty; minProfitInBps = _minProfit; admin = msg.sender; } function setMaxEthQty(uint newVal) external { require(msg.sender == admin, "!admin"); maxEthQty = newVal; } function setMinEthQty(uint newVal) external { require(msg.sender == admin, "!admin"); minQty = newVal; } function setMinProfit(uint newVal) external { require(msg.sender == admin, "!admin"); minProfitInBps = newVal; } function addBamm(address newBamm) external { require(msg.sender == admin, "!admin"); arb.approve(newBamm); bamms.push(newBamm); } function removeBamm(address bamm) external {<FILL_FUNCTION_BODY> } function withdrawEth() external { require(msg.sender == admin, "!admin"); msg.sender.transfer(address(this).balance); } function upgrade(address newMaster) public { require(msg.sender == admin, "!admin"); masterCopy = newMaster; } }
contract BKeeper { address public masterCopy; ArbChecker immutable public arbChecker; Arb immutable public arb; uint maxEthQty; // = 1000 ether; uint minQty; // = 1e10; uint minProfitInBps; // = 100; address public admin; address[] public bamms; event KeepOperation(bool succ); constructor(Arb _arb, ArbChecker _arbChecker) public { arbChecker = ArbChecker(_arbChecker); arb = _arb; } function findSmallestQty() public returns(uint, address) { for(uint i = 0 ; i < bamms.length ; i++) { address bamm = bamms[i]; for(uint qty = maxEthQty ; qty > minQty ; qty = qty / 2) { uint minProfit = qty * minProfitInBps / 10000; try arbChecker.checkProfitableArb(qty, minProfit, bamm) { return (qty, bamm); } catch { } } } return (0, address(0)); } function checkUpkeep(bytes calldata /*checkData*/) external returns (bool upkeepNeeded, bytes memory performData) { uint[] memory balances = new uint[](bamms.length); for(uint i = 0 ; i < bamms.length ; i++) { balances[i] = bamms[i].balance; } (uint qty, address bamm) = findSmallestQty(); uint bammBalance; for(uint i = 0 ; i < bamms.length ; i++) { if(bamms[i] == bamm) bammBalance = balances[i]; } upkeepNeeded = qty > 0; performData = abi.encode(qty, bamm, bammBalance); } function performUpkeep(bytes calldata performData) external { (uint qty, address bamm, uint bammBalance) = abi.decode(performData, (uint, address, uint)); require(bammBalance == bamm.balance, "performUpkeep: front runned"); require(qty > 0, "0 qty"); arb.swap(qty, bamm); emit KeepOperation(true); } function performUpkeepSafe(bytes calldata performData) external { try this.performUpkeep(performData) { emit KeepOperation(true); } catch { emit KeepOperation(false); } } receive() external payable {} // admin stuff function transferAdmin(address newAdmin) external { require(msg.sender == admin, "!admin"); admin = newAdmin; } function initParams(uint _maxEthQty, uint _minEthQty, uint _minProfit) external { require(admin == address(0), "already init"); maxEthQty = _maxEthQty; minQty = _minEthQty; minProfitInBps = _minProfit; admin = msg.sender; } function setMaxEthQty(uint newVal) external { require(msg.sender == admin, "!admin"); maxEthQty = newVal; } function setMinEthQty(uint newVal) external { require(msg.sender == admin, "!admin"); minQty = newVal; } function setMinProfit(uint newVal) external { require(msg.sender == admin, "!admin"); minProfitInBps = newVal; } function addBamm(address newBamm) external { require(msg.sender == admin, "!admin"); arb.approve(newBamm); bamms.push(newBamm); } <FILL_FUNCTION> function withdrawEth() external { require(msg.sender == admin, "!admin"); msg.sender.transfer(address(this).balance); } function upgrade(address newMaster) public { require(msg.sender == admin, "!admin"); masterCopy = newMaster; } }
require(msg.sender == admin, "!admin"); for(uint i = 0 ; i < bamms.length ; i++) { if(bamms[i] == bamm) { bamms[i] = bamms[bamms.length - 1]; bamms.pop(); return; } } revert("bamm does not exist");
function removeBamm(address bamm) external
function removeBamm(address bamm) external
27603
GSNRecipient
_getRelayedCallData
contract GSNRecipient is IRelayRecipient, Context { // Default RelayHub address, deployed on mainnet and all testnets at the same address address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494; uint256 constant private RELAYED_CALL_ACCEPTED = 0; uint256 constant private RELAYED_CALL_REJECTED = 11; // How much gas is forwarded to postRelayedCall uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000; /** * @dev Emitted when a contract changes its {IRelayHub} contract to a new one. */ event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub); /** * @dev Returns the address of the {IRelayHub} contract for this recipient. */ function getHubAddr() public view returns (address) { return _relayHub; } /** * @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not * use the default instance. * * IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old * {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}. */ function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; } /** * @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If * {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version. */ // This function is view for future-proofing, it may require reading from // storage in the future. function relayHubVersion() public view returns (string memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return "1.0.0"; } /** * @dev Withdraws the recipient's deposits in `RelayHub`. * * Derived contracts should expose this in an external interface with proper access control. */ function _withdrawDeposits(uint256 amount, address payable payee) internal { IRelayHub(_relayHub).withdraw(amount, payee); } // Overrides for Context's functions: when called from RelayHub, sender and // data require some pre-processing: the actual sender is stored at the end // of the call data, which in turns means it needs to be removed from it // when handling said data. /** * @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions, * and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. */ function _msgSender() internal view returns (address payable) { if (msg.sender != _relayHub) { return msg.sender; } else { return _getRelayedCallSender(); } } /** * @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions, * and a reduced version for GSN relayed calls (where msg.data contains additional information). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead. */ function _msgData() internal view returns (bytes memory) { if (msg.sender != _relayHub) { return msg.data; } else { return _getRelayedCallData(); } } // Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the // internal hook. /** * @dev See `IRelayRecipient.preRelayedCall`. * * This function should not be overriden directly, use `_preRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function preRelayedCall(bytes calldata context) external returns (bytes32) { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); return _preRelayedCall(context); } /** * @dev See `IRelayRecipient.preRelayedCall`. * * Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call preprocessing they may wish to do. * */ function _preRelayedCall(bytes memory context) internal returns (bytes32); /** * @dev See `IRelayRecipient.postRelayedCall`. * * This function should not be overriden directly, use `_postRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); } /** * @dev See `IRelayRecipient.postRelayedCall`. * * Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call postprocessing they may wish to do. * */ function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal; /** * @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract * will be charged a fee by RelayHub */ function _approveRelayedCall() internal pure returns (uint256, bytes memory) { return _approveRelayedCall(""); } /** * @dev See `GSNRecipient._approveRelayedCall`. * * This overload forwards `context` to _preRelayedCall and _postRelayedCall. */ function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); } /** * @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged. */ function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_REJECTED + errorCode, ""); } /* * @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's * `serviceFee`. */ function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) { // The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be // charged for 1.4 times the spent amount. return (gas * gasPrice * (100 + serviceFee)) / 100; } function _getRelayedCallSender() private pure returns (address payable result) { // We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array // is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing // so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would // require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20 // bytes. This can always be done due to the 32-byte prefix. // The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the // easiest/most-efficient way to perform this operation. // These fields are not accessible from assembly bytes memory array = msg.data; uint256 index = msg.data.length; // solhint-disable-next-line no-inline-assembly assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function _getRelayedCallData() private pure returns (bytes memory) {<FILL_FUNCTION_BODY> } }
contract GSNRecipient is IRelayRecipient, Context { // Default RelayHub address, deployed on mainnet and all testnets at the same address address private _relayHub = 0xD216153c06E857cD7f72665E0aF1d7D82172F494; uint256 constant private RELAYED_CALL_ACCEPTED = 0; uint256 constant private RELAYED_CALL_REJECTED = 11; // How much gas is forwarded to postRelayedCall uint256 constant internal POST_RELAYED_CALL_MAX_GAS = 100000; /** * @dev Emitted when a contract changes its {IRelayHub} contract to a new one. */ event RelayHubChanged(address indexed oldRelayHub, address indexed newRelayHub); /** * @dev Returns the address of the {IRelayHub} contract for this recipient. */ function getHubAddr() public view returns (address) { return _relayHub; } /** * @dev Switches to a new {IRelayHub} instance. This method is added for future-proofing: there's no reason to not * use the default instance. * * IMPORTANT: After upgrading, the {GSNRecipient} will no longer be able to receive relayed calls from the old * {IRelayHub} instance. Additionally, all funds should be previously withdrawn via {_withdrawDeposits}. */ function _upgradeRelayHub(address newRelayHub) internal { address currentRelayHub = _relayHub; require(newRelayHub != address(0), "GSNRecipient: new RelayHub is the zero address"); require(newRelayHub != currentRelayHub, "GSNRecipient: new RelayHub is the current one"); emit RelayHubChanged(currentRelayHub, newRelayHub); _relayHub = newRelayHub; } /** * @dev Returns the version string of the {IRelayHub} for which this recipient implementation was built. If * {_upgradeRelayHub} is used, the new {IRelayHub} instance should be compatible with this version. */ // This function is view for future-proofing, it may require reading from // storage in the future. function relayHubVersion() public view returns (string memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return "1.0.0"; } /** * @dev Withdraws the recipient's deposits in `RelayHub`. * * Derived contracts should expose this in an external interface with proper access control. */ function _withdrawDeposits(uint256 amount, address payable payee) internal { IRelayHub(_relayHub).withdraw(amount, payee); } // Overrides for Context's functions: when called from RelayHub, sender and // data require some pre-processing: the actual sender is stored at the end // of the call data, which in turns means it needs to be removed from it // when handling said data. /** * @dev Replacement for msg.sender. Returns the actual sender of a transaction: msg.sender for regular transactions, * and the end-user for GSN relayed calls (where msg.sender is actually `RelayHub`). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.sender`, and use {_msgSender} instead. */ function _msgSender() internal view returns (address payable) { if (msg.sender != _relayHub) { return msg.sender; } else { return _getRelayedCallSender(); } } /** * @dev Replacement for msg.data. Returns the actual calldata of a transaction: msg.data for regular transactions, * and a reduced version for GSN relayed calls (where msg.data contains additional information). * * IMPORTANT: Contracts derived from {GSNRecipient} should never use `msg.data`, and use {_msgData} instead. */ function _msgData() internal view returns (bytes memory) { if (msg.sender != _relayHub) { return msg.data; } else { return _getRelayedCallData(); } } // Base implementations for pre and post relayedCall: only RelayHub can invoke them, and data is forwarded to the // internal hook. /** * @dev See `IRelayRecipient.preRelayedCall`. * * This function should not be overriden directly, use `_preRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function preRelayedCall(bytes calldata context) external returns (bytes32) { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); return _preRelayedCall(context); } /** * @dev See `IRelayRecipient.preRelayedCall`. * * Called by `GSNRecipient.preRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call preprocessing they may wish to do. * */ function _preRelayedCall(bytes memory context) internal returns (bytes32); /** * @dev See `IRelayRecipient.postRelayedCall`. * * This function should not be overriden directly, use `_postRelayedCall` instead. * * * Requirements: * * - the caller must be the `RelayHub` contract. */ function postRelayedCall(bytes calldata context, bool success, uint256 actualCharge, bytes32 preRetVal) external { require(msg.sender == getHubAddr(), "GSNRecipient: caller is not RelayHub"); _postRelayedCall(context, success, actualCharge, preRetVal); } /** * @dev See `IRelayRecipient.postRelayedCall`. * * Called by `GSNRecipient.postRelayedCall`, which asserts the caller is the `RelayHub` contract. Derived contracts * must implement this function with any relayed-call postprocessing they may wish to do. * */ function _postRelayedCall(bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal) internal; /** * @dev Return this in acceptRelayedCall to proceed with the execution of a relayed call. Note that this contract * will be charged a fee by RelayHub */ function _approveRelayedCall() internal pure returns (uint256, bytes memory) { return _approveRelayedCall(""); } /** * @dev See `GSNRecipient._approveRelayedCall`. * * This overload forwards `context` to _preRelayedCall and _postRelayedCall. */ function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); } /** * @dev Return this in acceptRelayedCall to impede execution of a relayed call. No fees will be charged. */ function _rejectRelayedCall(uint256 errorCode) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_REJECTED + errorCode, ""); } /* * @dev Calculates how much RelayHub will charge a recipient for using `gas` at a `gasPrice`, given a relayer's * `serviceFee`. */ function _computeCharge(uint256 gas, uint256 gasPrice, uint256 serviceFee) internal pure returns (uint256) { // The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be // charged for 1.4 times the spent amount. return (gas * gasPrice * (100 + serviceFee)) / 100; } function _getRelayedCallSender() private pure returns (address payable result) { // We need to read 20 bytes (an address) located at array index msg.data.length - 20. In memory, the array // is prefixed with a 32-byte length value, so we first add 32 to get the memory read index. However, doing // so would leave the address in the upper 20 bytes of the 32-byte word, which is inconvenient and would // require bit shifting. We therefore subtract 12 from the read index so the address lands on the lower 20 // bytes. This can always be done due to the 32-byte prefix. // The final memory read index is msg.data.length - 20 + 32 - 12 = msg.data.length. Using inline assembly is the // easiest/most-efficient way to perform this operation. // These fields are not accessible from assembly bytes memory array = msg.data; uint256 index = msg.data.length; // solhint-disable-next-line no-inline-assembly assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. result := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } <FILL_FUNCTION> }
// RelayHub appends the sender address at the end of the calldata, so in order to retrieve the actual msg.data, // we must strip the last 20 bytes (length of an address type) from it. uint256 actualDataLength = msg.data.length - 20; bytes memory actualData = new bytes(actualDataLength); for (uint256 i = 0; i < actualDataLength; ++i) { actualData[i] = msg.data[i]; } return actualData;
function _getRelayedCallData() private pure returns (bytes memory)
function _getRelayedCallData() private pure returns (bytes memory)
29608
SquidGameCard
tokenURI
contract SquidGameCard is ERC721Enumerable, ReentrancyGuard, Ownable { uint8 private constant _PICKSIZE = 10; uint16 private constant _MAX_CLAIMS = 456 * 20; uint16 private constant _MAX_OWNER_CLAIMS = 456; uint16 private constant _TIMELOCK_COUNT = 456; uint private constant _TIMELOCK_DURATION = 6 hours; uint public constant _MINT_START_TIME = 1633823999; // October 9, 2021 11:59:59 PM GMT for celebrating the Hangul Day! uint private _totalClaims; uint public claimTimeLock; mapping(uint => uint) public _lastClaims; //pick index => last tokenId mapping(uint => uint) public _seeds; //tokenId => seed string[15] private simpleConsonants = [ "&#12593;", //0 ㄱ "&#12596;", //1 ㄴ "&#12599;", //2 ㄷ "&#12601;", //3 ㄹ "&#12609;", //4 ㅁ "&#12610;", //5 ㅂ "&#12613;", //6 ㅅ "&#12615;", //7 o "&#12616;", //8 ㅈ "&#12618;", //9 ㅊ "&#12619;", //10 ㅋ "&#12620;", //11 ㅌ "&#12621;", //12 ㅍ "&#12622;", //13 ㅎ "&#12671;" //14 triangle ]; uint8[7] private baseGenes = [0, 1, 2, 3, 4, 5, 6]; function genSeed(uint _tokenId) private pure returns (uint) { return uint256(keccak256(abi.encodePacked(_tokenId))); } function getSeed(uint _tokenId) public view returns (uint) { return _seeds[_tokenId]; } function getRand(uint _seed, uint _prefix) private pure returns (uint) { return uint256(keccak256(abi.encodePacked(_seed, _prefix))); } function mintPickSize() private onlyOwner { for (uint8 i=1; i <= _PICKSIZE; i++) { if (i == _PICKSIZE) { _lastClaims[0] = _PICKSIZE; } else { _lastClaims[i] = i; } _seeds[i] = genSeed(i); require(safeMint(owner(), i), 'Minting failed'); } _totalClaims = _PICKSIZE; } function pickTokenId() private returns (uint) { require(_totalClaims < _MAX_CLAIMS, 'All regular tokens already minted'); uint tokenId; uint pickIndex = uint256(keccak256(abi.encodePacked(totalSupply(), blockhash(block.number-1)))) % _PICKSIZE; tokenId = _lastClaims[pickIndex] + _PICKSIZE; if (tokenId > _MAX_CLAIMS) { while (tokenId > _MAX_CLAIMS) { pickIndex = (pickIndex + 1) % _PICKSIZE; tokenId = _lastClaims[pickIndex] + _PICKSIZE; } } _lastClaims[pickIndex] += _PICKSIZE; _totalClaims += 1; return tokenId; } function getGenes(uint256 _tokenId) public view returns (uint8[8] memory) { uint8[8] memory genes; uint seed = getSeed(_tokenId); if (seed == 0) { return [0,0,0,0,0,0,0,0]; } uint number = getRand(seed, 20211009); for (uint8 i=0; i<8; i++) { uint8 output = uint8(number % 8); uint greatness = getRand(number, i) % 21; if (greatness > 16) { output += 1; } if (greatness > 17) { output += 1; } if (greatness > 18) { output += 1; } if (output > 9) { output = 9; } genes[i] = output; number = number / 10; } return genes; } function getConsonants(uint256 _tokenId) public view returns (string[3] memory) { uint8[3] memory idx = getConsonantsIndex(_tokenId); string[3] memory consArray; consArray[0] = simpleConsonants[idx[0]]; consArray[1] = simpleConsonants[idx[1]]; consArray[2] = simpleConsonants[idx[2]]; return consArray; } function getConsonantsIndex(uint256 _tokenId) public view returns (uint8[3] memory) { uint8[3] memory consArray; uint seed = getSeed(_tokenId); require(seed != 0); uint q = getRand(seed, 3) % 4; if (_tokenId <= _PICKSIZE || q == 0) { consArray[0] = 7; consArray[1] = 14; consArray[2] = 4; } else { consArray[0] = uint8(getRand(seed, 11) % simpleConsonants.length); consArray[1] = uint8(getRand(seed, 12) % simpleConsonants.length); consArray[2] = uint8(getRand(seed, 13) % simpleConsonants.length); } return consArray; } function tokenURI(uint256 _tokenId) override public view returns (string memory) {<FILL_FUNCTION_BODY> } function safeMint(address _to, uint _amount) private returns (bool) { _safeMint(_to, _amount); return true; } function claim() external nonReentrant { require(_totalClaims < _MAX_CLAIMS, 'Regular claims are over'); require(claimTimeLock < block.timestamp, 'Wait until the claimTimeLock passes'); uint tokenId = pickTokenId(); _seeds[tokenId] = genSeed(tokenId); require(safeMint(_msgSender(), tokenId), 'Minting failed'); checkClaimLock(); } function ownerClaim(uint256 _tokenId) external nonReentrant onlyOwner { require(_tokenId > _MAX_CLAIMS && _tokenId <= _MAX_CLAIMS + _MAX_OWNER_CLAIMS, "Token ID invalid"); require(claimTimeLock < block.timestamp, 'Wait until the claimTimeLock passes'); _seeds[_tokenId] = genSeed(_tokenId); require(safeMint(owner(), _tokenId), 'Minting failed'); checkClaimLock(); } function checkClaimLock() internal { if (totalSupply() % _TIMELOCK_COUNT == 0) { claimTimeLock = block.timestamp + _TIMELOCK_DURATION; } } function isMintable() external view returns (bool) { if (_totalClaims >= _MAX_CLAIMS) return false; if (claimTimeLock >= block.timestamp) return false; return true; } function getMaxSupply() external pure returns (uint) { return _MAX_CLAIMS + _MAX_OWNER_CLAIMS; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } constructor() ERC721("Squid Game Card", "SquidGameCard") Ownable() { mintPickSize(); claimTimeLock = _MINT_START_TIME; } }
contract SquidGameCard is ERC721Enumerable, ReentrancyGuard, Ownable { uint8 private constant _PICKSIZE = 10; uint16 private constant _MAX_CLAIMS = 456 * 20; uint16 private constant _MAX_OWNER_CLAIMS = 456; uint16 private constant _TIMELOCK_COUNT = 456; uint private constant _TIMELOCK_DURATION = 6 hours; uint public constant _MINT_START_TIME = 1633823999; // October 9, 2021 11:59:59 PM GMT for celebrating the Hangul Day! uint private _totalClaims; uint public claimTimeLock; mapping(uint => uint) public _lastClaims; //pick index => last tokenId mapping(uint => uint) public _seeds; //tokenId => seed string[15] private simpleConsonants = [ "&#12593;", //0 ㄱ "&#12596;", //1 ㄴ "&#12599;", //2 ㄷ "&#12601;", //3 ㄹ "&#12609;", //4 ㅁ "&#12610;", //5 ㅂ "&#12613;", //6 ㅅ "&#12615;", //7 o "&#12616;", //8 ㅈ "&#12618;", //9 ㅊ "&#12619;", //10 ㅋ "&#12620;", //11 ㅌ "&#12621;", //12 ㅍ "&#12622;", //13 ㅎ "&#12671;" //14 triangle ]; uint8[7] private baseGenes = [0, 1, 2, 3, 4, 5, 6]; function genSeed(uint _tokenId) private pure returns (uint) { return uint256(keccak256(abi.encodePacked(_tokenId))); } function getSeed(uint _tokenId) public view returns (uint) { return _seeds[_tokenId]; } function getRand(uint _seed, uint _prefix) private pure returns (uint) { return uint256(keccak256(abi.encodePacked(_seed, _prefix))); } function mintPickSize() private onlyOwner { for (uint8 i=1; i <= _PICKSIZE; i++) { if (i == _PICKSIZE) { _lastClaims[0] = _PICKSIZE; } else { _lastClaims[i] = i; } _seeds[i] = genSeed(i); require(safeMint(owner(), i), 'Minting failed'); } _totalClaims = _PICKSIZE; } function pickTokenId() private returns (uint) { require(_totalClaims < _MAX_CLAIMS, 'All regular tokens already minted'); uint tokenId; uint pickIndex = uint256(keccak256(abi.encodePacked(totalSupply(), blockhash(block.number-1)))) % _PICKSIZE; tokenId = _lastClaims[pickIndex] + _PICKSIZE; if (tokenId > _MAX_CLAIMS) { while (tokenId > _MAX_CLAIMS) { pickIndex = (pickIndex + 1) % _PICKSIZE; tokenId = _lastClaims[pickIndex] + _PICKSIZE; } } _lastClaims[pickIndex] += _PICKSIZE; _totalClaims += 1; return tokenId; } function getGenes(uint256 _tokenId) public view returns (uint8[8] memory) { uint8[8] memory genes; uint seed = getSeed(_tokenId); if (seed == 0) { return [0,0,0,0,0,0,0,0]; } uint number = getRand(seed, 20211009); for (uint8 i=0; i<8; i++) { uint8 output = uint8(number % 8); uint greatness = getRand(number, i) % 21; if (greatness > 16) { output += 1; } if (greatness > 17) { output += 1; } if (greatness > 18) { output += 1; } if (output > 9) { output = 9; } genes[i] = output; number = number / 10; } return genes; } function getConsonants(uint256 _tokenId) public view returns (string[3] memory) { uint8[3] memory idx = getConsonantsIndex(_tokenId); string[3] memory consArray; consArray[0] = simpleConsonants[idx[0]]; consArray[1] = simpleConsonants[idx[1]]; consArray[2] = simpleConsonants[idx[2]]; return consArray; } function getConsonantsIndex(uint256 _tokenId) public view returns (uint8[3] memory) { uint8[3] memory consArray; uint seed = getSeed(_tokenId); require(seed != 0); uint q = getRand(seed, 3) % 4; if (_tokenId <= _PICKSIZE || q == 0) { consArray[0] = 7; consArray[1] = 14; consArray[2] = 4; } else { consArray[0] = uint8(getRand(seed, 11) % simpleConsonants.length); consArray[1] = uint8(getRand(seed, 12) % simpleConsonants.length); consArray[2] = uint8(getRand(seed, 13) % simpleConsonants.length); } return consArray; } <FILL_FUNCTION> function safeMint(address _to, uint _amount) private returns (bool) { _safeMint(_to, _amount); return true; } function claim() external nonReentrant { require(_totalClaims < _MAX_CLAIMS, 'Regular claims are over'); require(claimTimeLock < block.timestamp, 'Wait until the claimTimeLock passes'); uint tokenId = pickTokenId(); _seeds[tokenId] = genSeed(tokenId); require(safeMint(_msgSender(), tokenId), 'Minting failed'); checkClaimLock(); } function ownerClaim(uint256 _tokenId) external nonReentrant onlyOwner { require(_tokenId > _MAX_CLAIMS && _tokenId <= _MAX_CLAIMS + _MAX_OWNER_CLAIMS, "Token ID invalid"); require(claimTimeLock < block.timestamp, 'Wait until the claimTimeLock passes'); _seeds[_tokenId] = genSeed(_tokenId); require(safeMint(owner(), _tokenId), 'Minting failed'); checkClaimLock(); } function checkClaimLock() internal { if (totalSupply() % _TIMELOCK_COUNT == 0) { claimTimeLock = block.timestamp + _TIMELOCK_DURATION; } } function isMintable() external view returns (bool) { if (_totalClaims >= _MAX_CLAIMS) return false; if (claimTimeLock >= block.timestamp) return false; return true; } function getMaxSupply() external pure returns (uint) { return _MAX_CLAIMS + _MAX_OWNER_CLAIMS; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } constructor() ERC721("Squid Game Card", "SquidGameCard") Ownable() { mintPickSize(); claimTimeLock = _MINT_START_TIME; } }
string[9] memory parts; string[27] memory attrParts; string memory ojingeo; string memory sameConsonants; uint8[8] memory geneArray = getGenes(_tokenId); string[3] memory consArray = getConsonants(_tokenId); uint8[3] memory consIndex = getConsonantsIndex(_tokenId); if (consIndex[0] == 7 && consIndex[1] == 14 && consIndex[2] == 4) { ojingeo = 'Y'; } else { ojingeo = 'N'; } if (consIndex[0] == consIndex[1] && consIndex[0] == consIndex[2]) { sameConsonants = 'Y'; } else { sameConsonants = 'N'; } parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 220">'; parts[1] = '<style>.base {font-family: Verdana; fill: black;}</style>'; parts[2] = '<rect width="100%" height="100%" fill="#CF9857" />'; parts[3] = '<text x="50%" y="100" dominant-baseline="middle" text-anchor="middle" class="base" style="font-size:700%; letter-spacing: -0.2em;">'; parts[4] = string(abi.encodePacked(consArray[0], ' ', consArray[1], ' ', consArray[2])); parts[5] = '</text><text x="50%" y="180" dominant-baseline="middle" text-anchor="middle" class="base" style="font-size:150%;">&#937; '; parts[6] = string(abi.encodePacked(toString(geneArray[0]), toString(geneArray[1]), toString(geneArray[2]), toString(geneArray[3]), ' ')); parts[7] = string(abi.encodePacked(toString(geneArray[4]), toString(geneArray[5]), toString(geneArray[6]), toString(geneArray[7]) )); parts[8] ='</text></svg>'; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])); attrParts[0] = '[{"trait_type": "Left Consonant", "value": "'; attrParts[1] = consArray[0]; attrParts[2] = '"}, {"trait_type": "Center Consonant", "value": "'; attrParts[3] = consArray[1]; attrParts[4] = '"}, {"trait_type": "Right Consonant", "value": "'; attrParts[5] = consArray[2]; attrParts[6] = '"}, {"trait_type": "Gene0", "value": "'; attrParts[7] = toString(geneArray[0]); attrParts[8] = '"}, {"trait_type": "Gene1", "value": "'; attrParts[9] = toString(geneArray[1]); attrParts[10] = '"}, {"trait_type": "Gene2", "value": "'; attrParts[11] = toString(geneArray[2]); attrParts[12] = '"}, {"trait_type": "Gene3", "value": "'; attrParts[13] = toString(geneArray[3]); attrParts[14] = '"}, {"trait_type": "Gene4", "value": "'; attrParts[15] = toString(geneArray[4]); attrParts[16] = '"}, {"trait_type": "Gene5", "value": "'; attrParts[17] = toString(geneArray[5]); attrParts[18] = '"}, {"trait_type": "Gene6", "value": "'; attrParts[19] = toString(geneArray[6]); attrParts[20] = '"}, {"trait_type": "Gene7", "value": "'; attrParts[21] = toString(geneArray[7]); attrParts[22] = '"}, {"trait_type": "Ojingeo", "value": "'; attrParts[23] = ojingeo; attrParts[24] = '"}, {"trait_type": "Same Consonants", "value": "'; attrParts[25] = sameConsonants; attrParts[26] = '"}]'; string memory attrs = string(abi.encodePacked(attrParts[0], attrParts[1], attrParts[2], attrParts[3], attrParts[4], attrParts[5], attrParts[6], attrParts[7])); attrs = string(abi.encodePacked(attrs, attrParts[8], attrParts[9], attrParts[10], attrParts[11], attrParts[12], attrParts[13], attrParts[14])); attrs = string(abi.encodePacked(attrs, attrParts[15], attrParts[16], attrParts[17], attrParts[18], attrParts[19], attrParts[20])); attrs = string(abi.encodePacked(attrs, attrParts[21], attrParts[22], attrParts[23], attrParts[24], attrParts[25], attrParts[26])); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Squid Game Card NFT #', toString(_tokenId), '", "attributes": ', attrs ,', "description": "The squid game cards are invitation to enter the adventurous and mysterious metaverse games. Genes characteristics and other functionality are intentionally omitted for unlimited imagination and community-driven game development. Start your journey now!", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output;
function tokenURI(uint256 _tokenId) override public view returns (string memory)
function tokenURI(uint256 _tokenId) override public view returns (string memory)
24782
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 _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; <FILL_FUNCTION> /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); 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)
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
16182
REAPITToken
approve
contract REAPITToken is ERC20Interface, 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 = "REAP"; name = "REAPIT Token"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0x3953017AF23aB99a7d40f3D26F1595f27c91345f] = _totalSupply; emit Transfer(address(0), 0x3953017AF23aB99a7d40f3D26F1595f27c91345f, _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) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // 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) { 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(); } }
contract REAPITToken is ERC20Interface, 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 = "REAP"; name = "REAPIT Token"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0x3953017AF23aB99a7d40f3D26F1595f27c91345f] = _totalSupply; emit Transfer(address(0), 0x3953017AF23aB99a7d40f3D26F1595f27c91345f, _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; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // 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) { 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(); } }
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true;
function approve(address spender, uint tokens) public returns (bool success)
// ------------------------------------------------------------------------ // 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)
30139
FuckPutin
_transfer
contract FuckPutin is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public ukraineWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyUkraineFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellUkraineFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForUkraine; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; // _isBlacklisted = can not buy or sell or transfer tokens at all <---- bot protection mapping(address => bool) public _isBlacklisted; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event ukraineWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("FuckPutin", "FPUT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 2; uint256 _buyLiquidityFee = 6; uint256 _buyUkraineFee = 5; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 6; uint256 _sellUkraineFee = 5; uint256 totalSupply = 1 * 1e27; maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 2 / 100; // 2% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyUkraineFee = _buyUkraineFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyUkraineFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellUkraineFee = _sellUkraineFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellUkraineFee; marketingWallet = address(owner()); // set as marketing wallet ukraineWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 100)/1e18, "Cannot set maxTransactionAmount lower than 1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 2 / 100)/1e18, "Cannot set maxWallet lower than 2%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _ukraineFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyUkraineFee = _ukraineFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyUkraineFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _ukraineFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellUkraineFee = _ukraineFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellUkraineFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateUkraineWallet(address newWallet) external onlyOwner { emit ukraineWalletUpdated(newWallet, ukraineWallet); ukraineWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function addToBlacklist(address[] calldata addresses) external onlyOwner{ for (uint256 i; i <addresses.length; i++){ _isBlacklisted[addresses[i]] = true; } } function removeFromBlacklist(address account) external onlyOwner{ _isBlacklisted[account] = false; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override {<FILL_FUNCTION_BODY> } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForUkraine; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForUkraine).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForUkraine = 0; (success,) = address(ukraineWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } }
contract FuckPutin is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public ukraineWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyUkraineFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellUkraineFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForUkraine; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; // _isBlacklisted = can not buy or sell or transfer tokens at all <---- bot protection mapping(address => bool) public _isBlacklisted; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event ukraineWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("FuckPutin", "FPUT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 2; uint256 _buyLiquidityFee = 6; uint256 _buyUkraineFee = 5; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 6; uint256 _sellUkraineFee = 5; uint256 totalSupply = 1 * 1e27; maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 2 / 100; // 2% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyUkraineFee = _buyUkraineFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyUkraineFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellUkraineFee = _sellUkraineFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellUkraineFee; marketingWallet = address(owner()); // set as marketing wallet ukraineWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 100)/1e18, "Cannot set maxTransactionAmount lower than 1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 2 / 100)/1e18, "Cannot set maxWallet lower than 2%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _ukraineFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyUkraineFee = _ukraineFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyUkraineFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _ukraineFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellUkraineFee = _ukraineFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellUkraineFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateUkraineWallet(address newWallet) external onlyOwner { emit ukraineWalletUpdated(newWallet, ukraineWallet); ukraineWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function addToBlacklist(address[] calldata addresses) external onlyOwner{ for (uint256 i; i <addresses.length; i++){ _isBlacklisted[addresses[i]] = true; } } function removeFromBlacklist(address account) external onlyOwner{ _isBlacklisted[account] = false; } event BoughtEarly(address indexed sniper); <FILL_FUNCTION> function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForUkraine; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForUkraine).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForUkraine = 0; (success,) = address(ukraineWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } }
// makes sure seller or buyer is not blacklisted require(!_isBlacklisted[from] && !_isBlacklisted[to], "This account is blacklisted: If you feel this is incorrect please contac us and we will remove you"); require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForUkraine += fees * sellUkraineFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForUkraine += fees * buyUkraineFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount);
function _transfer( address from, address to, uint256 amount ) internal override
function _transfer( address from, address to, uint256 amount ) internal override
85687
ERC1155Tradable
_exists
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable, MinterRole, WhitelistAdminRole { using Strings for string; address proxyRegistryAddress; uint256 private _currentTokenID = 0; mapping(uint256 => address) public creators; mapping(uint256 => uint256) public tokenSupply; mapping(uint256 => uint256) public tokenMaxSupply; // Contract name string public name; // Contract symbol string public symbol; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; proxyRegistryAddress = _proxyRegistryAddress; } function removeWhitelistAdmin(address account) public onlyOwner { _removeWhitelistAdmin(account); } function removeMinter(address account) public onlyOwner { _removeMinter(account); } function uri(uint256 _id) public view returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return Strings.strConcat(baseMetadataURI, Strings.uint2str(_id)); } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Returns the max quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function maxSupply(uint256 _id) public view returns (uint256) { return tokenMaxSupply[_id]; } /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyWhitelistAdmin { _setBaseMetadataURI(_newBaseMetadataURI); } /** * @dev Creates a new token type and assigns _initialSupply to an address * @param _maxSupply max supply allowed * @param _initialSupply Optional amount to supply the first owner * @param _uri Optional URI for this token type * @param _data Optional data to pass if receiver is contract * @return The newly created token ID */ function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyWhitelistAdmin returns (uint256 tokenId) { require(_initialSupply <= _maxSupply, "Initial supply cannot be more than max supply"); uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data); tokenSupply[_id] = _initialSupply; tokenMaxSupply[_id] = _maxSupply; return _id; } /** * @dev Mints some amount of tokens to an address * @param _to Address of the future owner of the token * @param _id Token ID to mint * @param _quantity Amount of tokens to mint * @param _data Data to pass if receiver is contract */ function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public onlyMinter { uint256 tokenId = _id; require(tokenSupply[tokenId] < tokenMaxSupply[tokenId], "Max supply reached"); _mint(_to, _id, _quantity, _data); tokenSupply[_id] = tokenSupply[_id].add(_quantity); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 _id) internal view returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } }
contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable, MinterRole, WhitelistAdminRole { using Strings for string; address proxyRegistryAddress; uint256 private _currentTokenID = 0; mapping(uint256 => address) public creators; mapping(uint256 => uint256) public tokenSupply; mapping(uint256 => uint256) public tokenMaxSupply; // Contract name string public name; // Contract symbol string public symbol; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; proxyRegistryAddress = _proxyRegistryAddress; } function removeWhitelistAdmin(address account) public onlyOwner { _removeWhitelistAdmin(account); } function removeMinter(address account) public onlyOwner { _removeMinter(account); } function uri(uint256 _id) public view returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return Strings.strConcat(baseMetadataURI, Strings.uint2str(_id)); } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Returns the max quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function maxSupply(uint256 _id) public view returns (uint256) { return tokenMaxSupply[_id]; } /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyWhitelistAdmin { _setBaseMetadataURI(_newBaseMetadataURI); } /** * @dev Creates a new token type and assigns _initialSupply to an address * @param _maxSupply max supply allowed * @param _initialSupply Optional amount to supply the first owner * @param _uri Optional URI for this token type * @param _data Optional data to pass if receiver is contract * @return The newly created token ID */ function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyWhitelistAdmin returns (uint256 tokenId) { require(_initialSupply <= _maxSupply, "Initial supply cannot be more than max supply"); uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data); tokenSupply[_id] = _initialSupply; tokenMaxSupply[_id] = _maxSupply; return _id; } /** * @dev Mints some amount of tokens to an address * @param _to Address of the future owner of the token * @param _id Token ID to mint * @param _quantity Amount of tokens to mint * @param _data Data to pass if receiver is contract */ function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public onlyMinter { uint256 tokenId = _id; require(tokenSupply[tokenId] < tokenMaxSupply[tokenId], "Max supply reached"); _mint(_to, _id, _quantity, _data); tokenSupply[_id] = tokenSupply[_id].add(_quantity); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } <FILL_FUNCTION> /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } }
return creators[_id] != address(0);
function _exists(uint256 _id) internal view returns (bool)
/** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 _id) internal view returns (bool)
79503
TokenVesting
vestedAmount
contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; bool public revoked; bool public initialized; uint256 public released; ERC20 public token; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not * @param _token address of the ERC20 token contract */ function initialize( address _owner, address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, address _token ) public { require(!initialized); require(_beneficiary != 0x0); require(_cliff <= _duration); initialized = true; owner = _owner; beneficiary = _beneficiary; start = _start; cliff = _start.add(_cliff); duration = _duration; revocable = _revocable; token = ERC20(_token); } /** * @notice Only allow calls from the beneficiary of the vesting contract */ modifier onlyBeneficiary() { require(msg.sender == beneficiary); _; } /** * @notice Allow the beneficiary to change its address * @param target the address to transfer the right to */ function changeBeneficiary(address target) onlyBeneficiary public { require(target != 0); beneficiary = target; } /** * @notice Transfers vested tokens to beneficiary. */ function release() onlyBeneficiary public { require(now >= cliff); _releaseTo(beneficiary); } /** * @notice Transfers vested tokens to a target address. * @param target the address to send the tokens to */ function releaseTo(address target) onlyBeneficiary public { require(now >= cliff); _releaseTo(target); } /** * @notice Transfers vested tokens to beneficiary. */ function _releaseTo(address target) internal { uint256 unreleased = releasableAmount(); released = released.add(unreleased); token.safeTransfer(target, unreleased); Released(released); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested are sent to the beneficiary. */ function revoke() onlyOwner public { require(revocable); require(!revoked); // Release all vested tokens _releaseTo(beneficiary); // Send the remainder to the owner token.safeTransfer(owner, token.balanceOf(this)); revoked = true; Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public constant returns (uint256) { return vestedAmount().sub(released); } /** * @dev Calculates the amount that has already vested. */ function vestedAmount() public constant returns (uint256) {<FILL_FUNCTION_BODY> } /** * @notice Allow withdrawing any token other than the relevant one */ function releaseForeignToken(ERC20 _token, uint256 amount) onlyOwner { require(_token != token); _token.transfer(owner, amount); } }
contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; bool public revoked; bool public initialized; uint256 public released; ERC20 public token; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not * @param _token address of the ERC20 token contract */ function initialize( address _owner, address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, address _token ) public { require(!initialized); require(_beneficiary != 0x0); require(_cliff <= _duration); initialized = true; owner = _owner; beneficiary = _beneficiary; start = _start; cliff = _start.add(_cliff); duration = _duration; revocable = _revocable; token = ERC20(_token); } /** * @notice Only allow calls from the beneficiary of the vesting contract */ modifier onlyBeneficiary() { require(msg.sender == beneficiary); _; } /** * @notice Allow the beneficiary to change its address * @param target the address to transfer the right to */ function changeBeneficiary(address target) onlyBeneficiary public { require(target != 0); beneficiary = target; } /** * @notice Transfers vested tokens to beneficiary. */ function release() onlyBeneficiary public { require(now >= cliff); _releaseTo(beneficiary); } /** * @notice Transfers vested tokens to a target address. * @param target the address to send the tokens to */ function releaseTo(address target) onlyBeneficiary public { require(now >= cliff); _releaseTo(target); } /** * @notice Transfers vested tokens to beneficiary. */ function _releaseTo(address target) internal { uint256 unreleased = releasableAmount(); released = released.add(unreleased); token.safeTransfer(target, unreleased); Released(released); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested are sent to the beneficiary. */ function revoke() onlyOwner public { require(revocable); require(!revoked); // Release all vested tokens _releaseTo(beneficiary); // Send the remainder to the owner token.safeTransfer(owner, token.balanceOf(this)); revoked = true; Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public constant returns (uint256) { return vestedAmount().sub(released); } <FILL_FUNCTION> /** * @notice Allow withdrawing any token other than the relevant one */ function releaseForeignToken(ERC20 _token, uint256 amount) onlyOwner { require(_token != token); _token.transfer(owner, amount); } }
uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); }
function vestedAmount() public constant returns (uint256)
/** * @dev Calculates the amount that has already vested. */ function vestedAmount() public constant returns (uint256)
62545
ERC20Impl
transfer
contract ERC20Impl is ERC20Interface { // 存储每个地址的余额(因为是public的所以会自动生成balanceOf方法) mapping (address => uint256) public balanceOf; // 存储每个地址可操作的地址及其可操作的金额 mapping (address => mapping (address => uint256)) internal allowed; // 初始化属性 constructor() public { decimals = 7; totalSupply = 100000000000 * 10 ** uint256(decimals); name = "统御 Token"; symbol = "Mars"; // 初始化该代币的账户会拥有的代币 balanceOf[msg.sender] = 100000000* 10 ** uint256(decimals); } 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(to != address(0) && from != address(0)); // 检验发送者账户余额是否足够 require(balanceOf[from] >= tokens); // 检验操作的金额是否是被允许的 require(allowed[from][msg.sender] <= tokens); // 检验是否会发生溢出 require(balanceOf[to] + tokens >= balanceOf[to]); // 扣除发送者账户余额 balanceOf[from] -= tokens; // 增加接收者账户余额 balanceOf[to] += tokens; // 触发相应的事件 emit Transfer(from, to, tokens); success = true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; // 触发相应的事件 emit Approval(msg.sender, spender, tokens); success = true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } }
contract ERC20Impl is ERC20Interface { // 存储每个地址的余额(因为是public的所以会自动生成balanceOf方法) mapping (address => uint256) public balanceOf; // 存储每个地址可操作的地址及其可操作的金额 mapping (address => mapping (address => uint256)) internal allowed; // 初始化属性 constructor() public { decimals = 7; totalSupply = 100000000000 * 10 ** uint256(decimals); name = "统御 Token"; symbol = "Mars"; // 初始化该代币的账户会拥有的代币 balanceOf[msg.sender] = 100000000* 10 ** uint256(decimals); } <FILL_FUNCTION> function transferFrom(address from, address to, uint tokens) public returns (bool success) { // 检验地址是否合法 require(to != address(0) && from != address(0)); // 检验发送者账户余额是否足够 require(balanceOf[from] >= tokens); // 检验操作的金额是否是被允许的 require(allowed[from][msg.sender] <= tokens); // 检验是否会发生溢出 require(balanceOf[to] + tokens >= balanceOf[to]); // 扣除发送者账户余额 balanceOf[from] -= tokens; // 增加接收者账户余额 balanceOf[to] += tokens; // 触发相应的事件 emit Transfer(from, to, tokens); success = true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; // 触发相应的事件 emit Approval(msg.sender, spender, tokens); success = true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } }
// 检验接收者地址是否合法 require(to != address(0)); // 检验发送者账户余额是否足够 require(balanceOf[msg.sender] >= tokens); // 检验是否会发生溢出 require(balanceOf[to] + tokens >= balanceOf[to]); // 扣除发送者账户余额 balanceOf[msg.sender] -= tokens; // 增加接收者账户余额 balanceOf[to] += tokens; // 触发相应的事件 emit Transfer(msg.sender, to, tokens); success = true;
function transfer(address to, uint tokens) public returns (bool success)
function transfer(address to, uint tokens) public returns (bool success)
7967
StrategyBalancerEthWbtc
_buyWantAndReinvest
contract StrategyBalancerEthWbtc is StrategyBase { uint public blocksToReleaseCompound = 7 * 6500; // 7 days to release all the new compounding amount // lpPair = 0x1efF8aF5D577060BA4ac8A29A13525bb0Ee2A3D5 (BPT ETH-WBTC 50/50) // token0 = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 (WBTC) // token1 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 (WETH) // farmingToken = 0xba100000625a3754423978a60c9317c58a424e3D (BAL) constructor(address _converter, address _farmingToken, address _weth, address _controller) public StrategyBase(_converter, _farmingToken, _weth, _controller) { } function getName() public override pure returns (string memory) { return "StrategyBalancerEthWbtc"; } function deposit() public override { // do nothing } function _withdrawSome(uint) internal override returns (uint) { return 0; } function _withdrawAll() internal override { // do nothing } function claimReward() public override { // do nothing } function _buyWantAndReinvest() internal override {<FILL_FUNCTION_BODY> } function balanceOfPool() public override view returns (uint) { return 0; } function claimable_tokens() external override view returns (uint) { return 0; } function setBlocksToReleaseCompound(uint _blocks) external onlyStrategist { blocksToReleaseCompound = _blocks; } }
contract StrategyBalancerEthWbtc is StrategyBase { uint public blocksToReleaseCompound = 7 * 6500; // 7 days to release all the new compounding amount // lpPair = 0x1efF8aF5D577060BA4ac8A29A13525bb0Ee2A3D5 (BPT ETH-WBTC 50/50) // token0 = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 (WBTC) // token1 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 (WETH) // farmingToken = 0xba100000625a3754423978a60c9317c58a424e3D (BAL) constructor(address _converter, address _farmingToken, address _weth, address _controller) public StrategyBase(_converter, _farmingToken, _weth, _controller) { } function getName() public override pure returns (string memory) { return "StrategyBalancerEthWbtc"; } function deposit() public override { // do nothing } function _withdrawSome(uint) internal override returns (uint) { return 0; } function _withdrawAll() internal override { // do nothing } function claimReward() public override { // do nothing } <FILL_FUNCTION> function balanceOfPool() public override view returns (uint) { return 0; } function claimable_tokens() external override view returns (uint) { return 0; } function setBlocksToReleaseCompound(uint _blocks) external onlyStrategist { blocksToReleaseCompound = _blocks; } }
uint256 _wethBal = IERC20(weth).balanceOf(address(this)); uint256 _wethToBuyToken0 = _wethBal.mul(495).div(1000); // we have Token1 (WETH) already, so use 49.5% balance to buy Token0 (WBTC) _swapTokens(weth, token0, _wethToBuyToken0); uint _before = IERC20(lpPair).balanceOf(address(this)); _addLiquidity(); uint _after = IERC20(lpPair).balanceOf(address(this)); if (_after > 0) { if (_after > _before) { uint _compound = _after.sub(_before); vault.addNewCompound(_compound, blocksToReleaseCompound); } }
function _buyWantAndReinvest() internal override
function _buyWantAndReinvest() internal override
35126
DTDToken
getPrice
contract DTDToken is IERC20 { using SafeMath for uint256; // Token properties string public name = "Dontoshi Token"; string public symbol = "DTD"; uint public decimals = 18; uint public _totalSupply = 100000000e18; uint public _tokenLeft = 100000000e18; uint public _round1Limit = 2300000e18; uint public _round2Limit = 5300000e18; uint public _round3Limit = 9800000e18; uint public _developmentReserve = 20200000e18; uint public _endDate = 1544918399; uint public _minInvest = 0.5 ether; uint public _maxInvest = 100 ether; // Invested ether mapping (address => uint256) _investedEth; // Balances for each account mapping (address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping (address => mapping(address => uint256)) allowed; // Owner of Token address public owner; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // modifier to allow only owner has full control on the function modifier onlyOwner { require(msg.sender == owner); _; } // Constructor // @notice DTDToken Contract // @return the transaction address constructor() public payable { owner = 0x9FD6977e609AA945C6b6e40537dCF0A791775279; balances[owner] = _totalSupply; } // Payable method // @notice Anyone can buy the tokens on tokensale by paying ether function () external payable { tokensale(msg.sender); } // @notice tokensale // @param recipient The address of the recipient // @return the transaction address and send the event as Transfer function tokensale(address recipient) public payable { require(recipient != 0x0); uint256 weiAmount = msg.value; uint tokens = weiAmount.mul(getPrice()); _investedEth[msg.sender] = _investedEth[msg.sender].add(weiAmount); require( weiAmount >= _minInvest ); require(_investedEth[msg.sender] <= _maxInvest); require(_tokenLeft >= tokens + _developmentReserve); balances[owner] = balances[owner].sub(tokens); balances[recipient] = balances[recipient].add(tokens); _tokenLeft = _tokenLeft.sub(tokens); owner.transfer(msg.value); TokenPurchase(msg.sender, recipient, weiAmount, tokens); } // @return total tokens supplied function totalSupply() public view returns (uint256) { return _totalSupply; } // What is the balance of a particular account? // @param who The address of the particular account // @return the balanace the particular account function balanceOf(address who) public view returns (uint256) { return balances[who]; } // Token distribution to founder, develoment team, partners, charity, and bounty function sendDTDToken(address to, uint256 value) public onlyOwner { require ( to != 0x0 && value > 0 && _tokenLeft >= value ); balances[owner] = balances[owner].sub(value); balances[to] = balances[to].add(value); _tokenLeft = _tokenLeft.sub(value); Transfer(owner, to, value); } function sendDTDTokenToMultiAddr(address[] memory listAddresses, uint256[] memory amount) public onlyOwner { require(listAddresses.length == amount.length); for (uint256 i = 0; i < listAddresses.length; i++) { require(listAddresses[i] != 0x0); balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]); balances[owner] = balances[owner].sub(amount[i]); Transfer(owner, listAddresses[i], amount[i]); _tokenLeft = _tokenLeft.sub(amount[i]); } } function destroyDTDToken(address to, uint256 value) public onlyOwner { require ( to != 0x0 && value > 0 && _totalSupply >= value ); balances[to] = balances[to].sub(value); } // @notice send value token to to from msg.sender // @param to The address of the recipient // @param value The amount of token to be transferred // @return the transaction address and send the event as Transfer function transfer(address to, uint256 value) public { require ( balances[msg.sender] >= value && value > 0 ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); } // @notice send value token to to from from // @param from The address of the sender // @param to The address of the recipient // @param value The amount of token to be transferred // @return the transaction address and send the event as Transfer function transferFrom(address from, address to, uint256 value) public { require ( allowed[from][msg.sender] >= value && balances[from] >= value && value > 0 ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); Transfer(from, to, value); } // Allow spender to withdraw from your account, multiple times, up to the value amount. // If this function is called again it overwrites the current allowance with value. // @param spender The address of the sender // @param value The amount to be approved // @return the transaction address and send the event as Approval function approve(address spender, uint256 value) external { require ( balances[msg.sender] >= value && value > 0 ); allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); } // Check the allowed value for the spender to withdraw from owner // @param owner The address of the owner // @param spender The address of the spender // @return the amount which spender is still allowed to withdraw from owner function allowance(address _owner, address spender) public view returns (uint256) { return allowed[_owner][spender]; } // Get current price of a Token // @return the price or token value for a ether function getPrice() public constant returns (uint result) {<FILL_FUNCTION_BODY> } function getTokenDetail() public view returns (string memory, string memory, uint256) { return (name, symbol, _totalSupply); } }
contract DTDToken is IERC20 { using SafeMath for uint256; // Token properties string public name = "Dontoshi Token"; string public symbol = "DTD"; uint public decimals = 18; uint public _totalSupply = 100000000e18; uint public _tokenLeft = 100000000e18; uint public _round1Limit = 2300000e18; uint public _round2Limit = 5300000e18; uint public _round3Limit = 9800000e18; uint public _developmentReserve = 20200000e18; uint public _endDate = 1544918399; uint public _minInvest = 0.5 ether; uint public _maxInvest = 100 ether; // Invested ether mapping (address => uint256) _investedEth; // Balances for each account mapping (address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping (address => mapping(address => uint256)) allowed; // Owner of Token address public owner; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // modifier to allow only owner has full control on the function modifier onlyOwner { require(msg.sender == owner); _; } // Constructor // @notice DTDToken Contract // @return the transaction address constructor() public payable { owner = 0x9FD6977e609AA945C6b6e40537dCF0A791775279; balances[owner] = _totalSupply; } // Payable method // @notice Anyone can buy the tokens on tokensale by paying ether function () external payable { tokensale(msg.sender); } // @notice tokensale // @param recipient The address of the recipient // @return the transaction address and send the event as Transfer function tokensale(address recipient) public payable { require(recipient != 0x0); uint256 weiAmount = msg.value; uint tokens = weiAmount.mul(getPrice()); _investedEth[msg.sender] = _investedEth[msg.sender].add(weiAmount); require( weiAmount >= _minInvest ); require(_investedEth[msg.sender] <= _maxInvest); require(_tokenLeft >= tokens + _developmentReserve); balances[owner] = balances[owner].sub(tokens); balances[recipient] = balances[recipient].add(tokens); _tokenLeft = _tokenLeft.sub(tokens); owner.transfer(msg.value); TokenPurchase(msg.sender, recipient, weiAmount, tokens); } // @return total tokens supplied function totalSupply() public view returns (uint256) { return _totalSupply; } // What is the balance of a particular account? // @param who The address of the particular account // @return the balanace the particular account function balanceOf(address who) public view returns (uint256) { return balances[who]; } // Token distribution to founder, develoment team, partners, charity, and bounty function sendDTDToken(address to, uint256 value) public onlyOwner { require ( to != 0x0 && value > 0 && _tokenLeft >= value ); balances[owner] = balances[owner].sub(value); balances[to] = balances[to].add(value); _tokenLeft = _tokenLeft.sub(value); Transfer(owner, to, value); } function sendDTDTokenToMultiAddr(address[] memory listAddresses, uint256[] memory amount) public onlyOwner { require(listAddresses.length == amount.length); for (uint256 i = 0; i < listAddresses.length; i++) { require(listAddresses[i] != 0x0); balances[listAddresses[i]] = balances[listAddresses[i]].add(amount[i]); balances[owner] = balances[owner].sub(amount[i]); Transfer(owner, listAddresses[i], amount[i]); _tokenLeft = _tokenLeft.sub(amount[i]); } } function destroyDTDToken(address to, uint256 value) public onlyOwner { require ( to != 0x0 && value > 0 && _totalSupply >= value ); balances[to] = balances[to].sub(value); } // @notice send value token to to from msg.sender // @param to The address of the recipient // @param value The amount of token to be transferred // @return the transaction address and send the event as Transfer function transfer(address to, uint256 value) public { require ( balances[msg.sender] >= value && value > 0 ); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); } // @notice send value token to to from from // @param from The address of the sender // @param to The address of the recipient // @param value The amount of token to be transferred // @return the transaction address and send the event as Transfer function transferFrom(address from, address to, uint256 value) public { require ( allowed[from][msg.sender] >= value && balances[from] >= value && value > 0 ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); Transfer(from, to, value); } // Allow spender to withdraw from your account, multiple times, up to the value amount. // If this function is called again it overwrites the current allowance with value. // @param spender The address of the sender // @param value The amount to be approved // @return the transaction address and send the event as Approval function approve(address spender, uint256 value) external { require ( balances[msg.sender] >= value && value > 0 ); allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); } // Check the allowed value for the spender to withdraw from owner // @param owner The address of the owner // @param spender The address of the spender // @return the amount which spender is still allowed to withdraw from owner function allowance(address _owner, address spender) public view returns (uint256) { return allowed[_owner][spender]; } <FILL_FUNCTION> function getTokenDetail() public view returns (string memory, string memory, uint256) { return (name, symbol, _totalSupply); } }
if ( _totalSupply - _tokenLeft < _round1Limit ) return 650; else if ( _totalSupply - _tokenLeft < _round2Limit ) return 500; else if ( _totalSupply - _tokenLeft < _round3Limit ) return 400; else return 0;
function getPrice() public constant returns (uint result)
// Get current price of a Token // @return the price or token value for a ether function getPrice() public constant returns (uint result)
66304
Trade
withdrawEth
contract Trade is Ownable { using SafeMath for uint; uint public cursETHtoUSD = 15000; uint public costClientBuyETH = 1 ether / 10000; uint public costClientSellETH = 1 ether / 100000; uint public costClientBuyUSD = costClientBuyETH * cursETHtoUSD / 100; uint public costClientSellUSD = costClientSellETH * cursETHtoUSD / 100; uint private DEC = 10 ** 18; bool public clientBuyOpen = true; bool public clientSellOpen = true; uint public clientBuyTimeWorkFrom = 1545264000; uint public clientBuyTimeWork = 24 hours; uint public clientSellTimeWorkFrom = 1545264000; uint public clientSellTimeWork = 24 hours; address public tokenAddress; event clientBuy(address user, uint valueETH, uint amount); event clientSell(address user, uint valueETH, uint amount); event Deposit(address user, uint value); event DepositToken(address user, uint value); event WithdrawEth(address user, uint value); event WithdrawTokens(address user, uint value); modifier buyIsOpen() { require(clientBuyOpen == true, "Buying are closed"); require((now - clientBuyTimeWorkFrom) % 24 hours <= clientBuyTimeWork, "Now buying are closed"); _; } modifier sellIsOpen() { require(clientSellOpen == true, "Selling are closed"); require((now - clientSellTimeWorkFrom) % 24 hours <= clientSellTimeWork, "Now selling are closed"); _; } function updateCursETHtoUSD(uint _value) onlyOwner public { cursETHtoUSD = _value; costClientBuyUSD = costClientBuyETH.mul(cursETHtoUSD).div(100); costClientSellUSD = costClientSellETH.mul(cursETHtoUSD).div(100); } function contractSalesAtUsd(uint _value) onlyOwner public { costClientBuyUSD = _value; costClientBuyETH = costClientBuyUSD.div(cursETHtoUSD).mul(100); } function contractBuysAtUsd(uint _value) onlyOwner public { costClientSellUSD = _value; costClientSellETH = costClientSellUSD.div(cursETHtoUSD).mul(100); } function contractSalesAtEth(uint _value) onlyOwner public { costClientBuyETH = _value; costClientBuyUSD = costClientBuyETH.mul(cursETHtoUSD).div(100); } function contractBuysAtEth(uint _value) onlyOwner public { costClientSellETH = _value; costClientSellUSD = costClientSellETH.mul(cursETHtoUSD).div(100); } function closeClientBuy() onlyOwner public { clientBuyOpen = false; } function openClientBuy() onlyOwner public { clientBuyOpen = true; } function closeClientSell() onlyOwner public { clientSellOpen = false; } function openClientSell() onlyOwner public { clientSellOpen = true; } function setClientBuyingTime(uint _from, uint _time) onlyOwner public { clientBuyTimeWorkFrom = _from; clientBuyTimeWork = _time; } function setClientSellingTime(uint _from, uint _time) onlyOwner public { clientSellTimeWorkFrom = _from; clientSellTimeWork = _time; } function contractSellTokens() buyIsOpen payable public { require(msg.value > 0, "ETH amount must be greater than 0"); uint amount = msg.value.mul(DEC).div(costClientBuyETH); require(IERC20(tokenAddress).balanceOf(this) >= amount, "Not enough tokens"); IERC20(tokenAddress).transfer(msg.sender, amount); emit clientBuy(msg.sender, msg.value, amount); } function() external payable { contractSellTokens(); } function contractBuyTokens(uint amount) sellIsOpen public { require(amount > 0, "Tokens amount must be greater than 0"); require(IERC20(tokenAddress).balanceOf(msg.sender) >= amount, "Not enough tokens on balance"); uint valueETH = amount.mul(costClientSellETH).div(DEC); require(valueETH <= address(this).balance, "Not enough balance on the contract"); IERC20(tokenAddress).transferTrade(msg.sender, this, amount); msg.sender.transfer(valueETH); emit clientSell(msg.sender, valueETH, amount); } function contractBuyTokensFrom(address from, uint amount) sellIsOpen public { require(keccak256(msg.sender) == keccak256(tokenAddress), "Only for token"); require(amount > 0, "Tokens amount must be greater than 0"); require(IERC20(tokenAddress).balanceOf(from) >= amount, "Not enough tokens on balance"); uint valueETH = amount.mul(costClientSellETH).div(DEC); require(valueETH <= address(this).balance, "Not enough balance on the contract"); IERC20(tokenAddress).transferTrade(from, this, amount); from.transfer(valueETH); emit clientSell(from, valueETH, amount); } function withdrawEth(address to, uint256 value) onlyOwner public {<FILL_FUNCTION_BODY> } function withdrawTokens(address to, uint256 value) onlyOwner public { require(IERC20(tokenAddress).balanceOf(this) >= value, "Not enough token balance on the contract"); IERC20(tokenAddress).transferTrade(this, to, value); emit WithdrawTokens(to, value); } function depositEther() onlyOwner payable public { emit Deposit(msg.sender, msg.value); } function depositToken(uint _value) onlyOwner public { IERC20(tokenAddress).transferTrade(msg.sender, this, _value); } function changeTokenAddress(address newTokenAddress) onlyOwner public { tokenAddress = newTokenAddress; } }
contract Trade is Ownable { using SafeMath for uint; uint public cursETHtoUSD = 15000; uint public costClientBuyETH = 1 ether / 10000; uint public costClientSellETH = 1 ether / 100000; uint public costClientBuyUSD = costClientBuyETH * cursETHtoUSD / 100; uint public costClientSellUSD = costClientSellETH * cursETHtoUSD / 100; uint private DEC = 10 ** 18; bool public clientBuyOpen = true; bool public clientSellOpen = true; uint public clientBuyTimeWorkFrom = 1545264000; uint public clientBuyTimeWork = 24 hours; uint public clientSellTimeWorkFrom = 1545264000; uint public clientSellTimeWork = 24 hours; address public tokenAddress; event clientBuy(address user, uint valueETH, uint amount); event clientSell(address user, uint valueETH, uint amount); event Deposit(address user, uint value); event DepositToken(address user, uint value); event WithdrawEth(address user, uint value); event WithdrawTokens(address user, uint value); modifier buyIsOpen() { require(clientBuyOpen == true, "Buying are closed"); require((now - clientBuyTimeWorkFrom) % 24 hours <= clientBuyTimeWork, "Now buying are closed"); _; } modifier sellIsOpen() { require(clientSellOpen == true, "Selling are closed"); require((now - clientSellTimeWorkFrom) % 24 hours <= clientSellTimeWork, "Now selling are closed"); _; } function updateCursETHtoUSD(uint _value) onlyOwner public { cursETHtoUSD = _value; costClientBuyUSD = costClientBuyETH.mul(cursETHtoUSD).div(100); costClientSellUSD = costClientSellETH.mul(cursETHtoUSD).div(100); } function contractSalesAtUsd(uint _value) onlyOwner public { costClientBuyUSD = _value; costClientBuyETH = costClientBuyUSD.div(cursETHtoUSD).mul(100); } function contractBuysAtUsd(uint _value) onlyOwner public { costClientSellUSD = _value; costClientSellETH = costClientSellUSD.div(cursETHtoUSD).mul(100); } function contractSalesAtEth(uint _value) onlyOwner public { costClientBuyETH = _value; costClientBuyUSD = costClientBuyETH.mul(cursETHtoUSD).div(100); } function contractBuysAtEth(uint _value) onlyOwner public { costClientSellETH = _value; costClientSellUSD = costClientSellETH.mul(cursETHtoUSD).div(100); } function closeClientBuy() onlyOwner public { clientBuyOpen = false; } function openClientBuy() onlyOwner public { clientBuyOpen = true; } function closeClientSell() onlyOwner public { clientSellOpen = false; } function openClientSell() onlyOwner public { clientSellOpen = true; } function setClientBuyingTime(uint _from, uint _time) onlyOwner public { clientBuyTimeWorkFrom = _from; clientBuyTimeWork = _time; } function setClientSellingTime(uint _from, uint _time) onlyOwner public { clientSellTimeWorkFrom = _from; clientSellTimeWork = _time; } function contractSellTokens() buyIsOpen payable public { require(msg.value > 0, "ETH amount must be greater than 0"); uint amount = msg.value.mul(DEC).div(costClientBuyETH); require(IERC20(tokenAddress).balanceOf(this) >= amount, "Not enough tokens"); IERC20(tokenAddress).transfer(msg.sender, amount); emit clientBuy(msg.sender, msg.value, amount); } function() external payable { contractSellTokens(); } function contractBuyTokens(uint amount) sellIsOpen public { require(amount > 0, "Tokens amount must be greater than 0"); require(IERC20(tokenAddress).balanceOf(msg.sender) >= amount, "Not enough tokens on balance"); uint valueETH = amount.mul(costClientSellETH).div(DEC); require(valueETH <= address(this).balance, "Not enough balance on the contract"); IERC20(tokenAddress).transferTrade(msg.sender, this, amount); msg.sender.transfer(valueETH); emit clientSell(msg.sender, valueETH, amount); } function contractBuyTokensFrom(address from, uint amount) sellIsOpen public { require(keccak256(msg.sender) == keccak256(tokenAddress), "Only for token"); require(amount > 0, "Tokens amount must be greater than 0"); require(IERC20(tokenAddress).balanceOf(from) >= amount, "Not enough tokens on balance"); uint valueETH = amount.mul(costClientSellETH).div(DEC); require(valueETH <= address(this).balance, "Not enough balance on the contract"); IERC20(tokenAddress).transferTrade(from, this, amount); from.transfer(valueETH); emit clientSell(from, valueETH, amount); } <FILL_FUNCTION> function withdrawTokens(address to, uint256 value) onlyOwner public { require(IERC20(tokenAddress).balanceOf(this) >= value, "Not enough token balance on the contract"); IERC20(tokenAddress).transferTrade(this, to, value); emit WithdrawTokens(to, value); } function depositEther() onlyOwner payable public { emit Deposit(msg.sender, msg.value); } function depositToken(uint _value) onlyOwner public { IERC20(tokenAddress).transferTrade(msg.sender, this, _value); } function changeTokenAddress(address newTokenAddress) onlyOwner public { tokenAddress = newTokenAddress; } }
require(address(this).balance >= value, "Not enough balance on the contract"); to.transfer(value); emit WithdrawEth(to, value);
function withdrawEth(address to, uint256 value) onlyOwner public
function withdrawEth(address to, uint256 value) onlyOwner public
23628
MultiSender
multisendEth
contract MultiSender { function tokenFallback(address /*_from*/, uint _value, bytes /*_data*/) public { require(false); } function multisendToken(address tokAddress, address[] _dests, uint256[] _amounts) public { ERC20 tok = ERC20(tokAddress); for (uint i = 0; i < _dests.length; i++){ tok.transferFrom(msg.sender, _dests[i], _amounts[i]); } } function multisendEth(address[] _dests, uint256[] _amounts) public payable {<FILL_FUNCTION_BODY> } }
contract MultiSender { function tokenFallback(address /*_from*/, uint _value, bytes /*_data*/) public { require(false); } function multisendToken(address tokAddress, address[] _dests, uint256[] _amounts) public { ERC20 tok = ERC20(tokAddress); for (uint i = 0; i < _dests.length; i++){ tok.transferFrom(msg.sender, _dests[i], _amounts[i]); } } <FILL_FUNCTION> }
for (uint i = 0; i < _dests.length; i++){ _dests[i].transfer(_amounts[i]); } require(this.balance == 0);
function multisendEth(address[] _dests, uint256[] _amounts) public payable
function multisendEth(address[] _dests, uint256[] _amounts) public payable
91102
ERC20Token
null
contract ERC20Token is ERC20Interface, Pausable { using SafeMath for uint256; using AddressUtils for address; string public symbol; string public name; uint8 public decimals; uint256 public totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; /** * @dev 1 eth this token = price other token which in address, * @notice the decimals of price */ mapping(address => uint256) price; /** * @dev Constructor */ constructor(string _symbol, string _name, uint256 _totalSupply) public {<FILL_FUNCTION_BODY> } function totalSupply() public view returns (uint256) { return totalSupply; } function balanceOf(address _tokenOwner) public view returns (uint256 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, uint256 _tokens) public whenNotPaused returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_tokens); balances[_to] = balances[_to].add(_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, uint256 _tokens) public whenNotPaused 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, uint256 _tokens) public whenNotPaused 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); 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 view returns (uint256 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, uint256 _tokens, bytes _data) public whenNotPaused 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 mintToken(address _target, uint256 _mintedAmount) public onlyAdmins whenNotPaused returns(bool success) { require(_target != address(0), "ERC20: mint to the zero address"); balances[_target] = balances[_target].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); emit Transfer(address(0), _target, _mintedAmount); return true; } function burnToken(uint256 _burnedAmount) public onlyAdmins whenNotPaused { require(balances[msg.sender] >= _burnedAmount); balances[msg.sender] = balances[msg.sender].sub(_burnedAmount); totalSupply = totalSupply.sub(_burnedAmount); emit Transfer(msg.sender, address(0), _burnedAmount); } /* * Don't accept ETH **/ function () public payable { revert(); } /** * @dev Owner can transfer out any accidentally sent ERC20 tokens */ function withDrawAnyERC20Token(address tokenAddress, uint256 tokens) public onlyAdmins returns (bool success) { require(tokenAddress.isContract()); return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract ERC20Token is ERC20Interface, Pausable { using SafeMath for uint256; using AddressUtils for address; string public symbol; string public name; uint8 public decimals; uint256 public totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; /** * @dev 1 eth this token = price other token which in address, * @notice the decimals of price */ mapping(address => uint256) price; <FILL_FUNCTION> function totalSupply() public view returns (uint256) { return totalSupply; } function balanceOf(address _tokenOwner) public view returns (uint256 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, uint256 _tokens) public whenNotPaused returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(_tokens); balances[_to] = balances[_to].add(_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, uint256 _tokens) public whenNotPaused 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, uint256 _tokens) public whenNotPaused 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); 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 view returns (uint256 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, uint256 _tokens, bytes _data) public whenNotPaused 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 mintToken(address _target, uint256 _mintedAmount) public onlyAdmins whenNotPaused returns(bool success) { require(_target != address(0), "ERC20: mint to the zero address"); balances[_target] = balances[_target].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); emit Transfer(address(0), _target, _mintedAmount); return true; } function burnToken(uint256 _burnedAmount) public onlyAdmins whenNotPaused { require(balances[msg.sender] >= _burnedAmount); balances[msg.sender] = balances[msg.sender].sub(_burnedAmount); totalSupply = totalSupply.sub(_burnedAmount); emit Transfer(msg.sender, address(0), _burnedAmount); } /* * Don't accept ETH **/ function () public payable { revert(); } /** * @dev Owner can transfer out any accidentally sent ERC20 tokens */ function withDrawAnyERC20Token(address tokenAddress, uint256 tokens) public onlyAdmins returns (bool success) { require(tokenAddress.isContract()); return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
owner = msg.sender; admins[msg.sender] = true; symbol = _symbol; name = _name; decimals = 18; totalSupply = _totalSupply * 10**uint(decimals); balances[owner] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply);
constructor(string _symbol, string _name, uint256 _totalSupply) public
/** * @dev Constructor */ constructor(string _symbol, string _name, uint256 _totalSupply) public
23129
Numa
updateMessage
contract Numa { mapping(address => bytes32) public users; Message[] public messages; struct Message { address sender; bytes32 ipfsHash; } event UserUpdated( address indexed sender, bytes32 indexed ipfsHash ); event MessageCreated( uint indexed id, address indexed sender, bytes32 indexed ipfsHash ); event MessageUpdated( uint indexed id, address indexed sender, bytes32 indexed ipfsHash ); function Numa() public { } function messagesLength() public view returns (uint) { return messages.length; } function createMessage(bytes32 ipfsHash) public { messages.length++; uint index = messages.length - 1; messages[index].ipfsHash = ipfsHash; messages[index].sender = msg.sender; MessageCreated(index, msg.sender, ipfsHash); } function updateMessage(uint id, bytes32 ipfsHash) public {<FILL_FUNCTION_BODY> } function updateUser(bytes32 ipfsHash) public { users[msg.sender] = ipfsHash; UserUpdated(msg.sender, ipfsHash); } }
contract Numa { mapping(address => bytes32) public users; Message[] public messages; struct Message { address sender; bytes32 ipfsHash; } event UserUpdated( address indexed sender, bytes32 indexed ipfsHash ); event MessageCreated( uint indexed id, address indexed sender, bytes32 indexed ipfsHash ); event MessageUpdated( uint indexed id, address indexed sender, bytes32 indexed ipfsHash ); function Numa() public { } function messagesLength() public view returns (uint) { return messages.length; } function createMessage(bytes32 ipfsHash) public { messages.length++; uint index = messages.length - 1; messages[index].ipfsHash = ipfsHash; messages[index].sender = msg.sender; MessageCreated(index, msg.sender, ipfsHash); } <FILL_FUNCTION> function updateUser(bytes32 ipfsHash) public { users[msg.sender] = ipfsHash; UserUpdated(msg.sender, ipfsHash); } }
require(messages.length > id); require(messages[id].sender == msg.sender); messages[id].ipfsHash = ipfsHash; MessageUpdated(id, msg.sender, ipfsHash);
function updateMessage(uint id, bytes32 ipfsHash) public
function updateMessage(uint id, bytes32 ipfsHash) public
34870
Simply
contract Simply { mapping (address => uint256) dates; mapping (address => uint256) invests; function() external payable {<FILL_FUNCTION_BODY> } }
contract Simply { mapping (address => uint256) dates; mapping (address => uint256) invests; <FILL_FUNCTION> }
address sender = msg.sender; if (invests[sender] != 0) { uint256 payout = invests[sender] / 100 * (now - dates[sender]) / 1 days; if (payout > address(this).balance) { payout = address(this).balance; } sender.transfer(payout); } dates[sender] = now; invests[sender] += msg.value;
function() external payable
function() external payable
70676
STARBITToken
STARBITToken
contract STARBITToken is StandardToken, Ownable { string constant public name = "Star Bit Token"; string constant public symbol = "SBT"; uint8 constant public decimals = 6; bool public isLocked = true; function STARBITToken(address STARBITWallet) public {<FILL_FUNCTION_BODY> } function unlock() onlyOwner { isLocked = false; } modifier verification() { require(!isLocked || msg.sender == owner); _; } function transfer(address _to, uint256 _value) verification public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) verification public returns (bool) { return super.transferFrom(_from, _to, _value); } }
contract STARBITToken is StandardToken, Ownable { string constant public name = "Star Bit Token"; string constant public symbol = "SBT"; uint8 constant public decimals = 6; bool public isLocked = true; <FILL_FUNCTION> function unlock() onlyOwner { isLocked = false; } modifier verification() { require(!isLocked || msg.sender == owner); _; } function transfer(address _to, uint256 _value) verification public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) verification public returns (bool) { return super.transferFrom(_from, _to, _value); } }
totalSupply = 1 * 10 ** (8+6); balances[STARBITWallet] = totalSupply;
function STARBITToken(address STARBITWallet) public
function STARBITToken(address STARBITWallet) public
70737
HelperPushStakingData
pushStakingData
contract HelperPushStakingData is LnAdmin { constructor(address _admin) public LnAdmin(_admin) {} function pushStakingData( address _storage, address[] calldata account, uint256[] calldata amount, uint256[] calldata staketime ) external {<FILL_FUNCTION_BODY> } //unstaking. }
contract HelperPushStakingData is LnAdmin { constructor(address _admin) public LnAdmin(_admin) {} <FILL_FUNCTION> //unstaking. }
require(account.length > 0, "array length zero"); require(account.length == amount.length, "array length not eq"); require(account.length == staketime.length, "array length not eq"); LnLinearStakingStorage stakingStorage = LnLinearStakingStorage( _storage ); for (uint256 i = 0; i < account.length; i++) { stakingStorage.PushStakingData(account[i], amount[i], staketime[i]); stakingStorage.AddWeeksTotal(staketime[i], amount[i]); }
function pushStakingData( address _storage, address[] calldata account, uint256[] calldata amount, uint256[] calldata staketime ) external
function pushStakingData( address _storage, address[] calldata account, uint256[] calldata amount, uint256[] calldata staketime ) external
46437
DeMarco
_transfer
contract DeMarco is IERC20, Ownable { using SafeMath for uint256; string public constant name = "DeMarco"; string public constant symbol = "DMARCO"; uint8 public constant decimals = 0; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; constructor(uint256 totalSupply) public { _totalSupply = totalSupply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query 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]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev 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 Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal {<FILL_FUNCTION_BODY> } // -------------------------------------------------------------------------------- // *** hint *** // -------------------------------------------------------------------------------- bool public funded = false; function() external payable { require(funded == false, "Already funded"); funded = true; } // Just a plain little boolean flag bool public claimed = false; // Hmmm ... interesting. function tellMeASecret(string _data) external onlyOwner { bytes32 input = keccak256(abi.encodePacked(keccak256(abi.encodePacked(_data)))); bytes32 secret = keccak256(abi.encodePacked(0x59a1fa9f9ea2f92d3ebf4aa606d774f5b686ebbb12da71e6036df86323995769)); require(input == secret, "Invalid secret!"); require(claimed == false, "Already claimed!"); _balances[msg.sender] = totalSupply(); claimed = true; emit Transfer(address(0), msg.sender, totalSupply()); } // What's that? function aaandItBurnsBurnsBurns(address _account, uint256 _value) external onlyOwner { require(_balances[_account] > 42, "No more tokens can be burned!"); require(_value == 1, "That did not work. You still need to find the meaning of life!"); // Watch out! Don't get burned :P _burn(_account, _value); // Niceee #ttfm _account.transfer(address(this).balance); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0), "Invalid address!"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } // -------------------------------------------------------------------------------- // *** hint *** // -------------------------------------------------------------------------------- }
contract DeMarco is IERC20, Ownable { using SafeMath for uint256; string public constant name = "DeMarco"; string public constant symbol = "DMARCO"; uint8 public constant decimals = 0; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; constructor(uint256 totalSupply) public { _totalSupply = totalSupply; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query 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]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev 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 Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } <FILL_FUNCTION> // -------------------------------------------------------------------------------- // *** hint *** // -------------------------------------------------------------------------------- bool public funded = false; function() external payable { require(funded == false, "Already funded"); funded = true; } // Just a plain little boolean flag bool public claimed = false; // Hmmm ... interesting. function tellMeASecret(string _data) external onlyOwner { bytes32 input = keccak256(abi.encodePacked(keccak256(abi.encodePacked(_data)))); bytes32 secret = keccak256(abi.encodePacked(0x59a1fa9f9ea2f92d3ebf4aa606d774f5b686ebbb12da71e6036df86323995769)); require(input == secret, "Invalid secret!"); require(claimed == false, "Already claimed!"); _balances[msg.sender] = totalSupply(); claimed = true; emit Transfer(address(0), msg.sender, totalSupply()); } // What's that? function aaandItBurnsBurnsBurns(address _account, uint256 _value) external onlyOwner { require(_balances[_account] > 42, "No more tokens can be burned!"); require(_value == 1, "That did not work. You still need to find the meaning of life!"); // Watch out! Don't get burned :P _burn(_account, _value); // Niceee #ttfm _account.transfer(address(this).balance); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0), "Invalid address!"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } // -------------------------------------------------------------------------------- // *** hint *** // -------------------------------------------------------------------------------- }
require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value);
function _transfer(address from, address to, uint256 value) internal
/** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal
12231
DemeterCrowdsale
createTokenContract
contract DemeterCrowdsale is Crowdsale, CappedCrowdsale, RefundableCrowdsale, WhiteListCrowdsale, ReferedCrowdsale, BonusWhiteListCrowdsale, BonusReferrerCrowdsale, PartialOwnershipCrowdsale { uint256 endBlock; function DemeterCrowdsale( uint256 _startBlock, uint256 _endBlock, uint256 _rate, address _wallet, uint256 _cap, uint256 _goal, uint256 _whiteListEndBlock, uint256 _bonusWhiteListRate, uint256 _bonusReferredRate, uint256 _percentToInvestor ) Crowdsale(_startBlock, _endBlock, _rate, _wallet) CappedCrowdsale(_cap) RefundableCrowdsale(_goal) WhiteListCrowdsale(_whiteListEndBlock) ReferedCrowdsale() BonusWhiteListCrowdsale(_bonusWhiteListRate) BonusReferrerCrowdsale(_bonusReferredRate) PartialOwnershipCrowdsale(_percentToInvestor) { DemeterToken(token).setEndBlock(_endBlock); } // creates the token to be sold. // override this method to have crowdsale of a specific MintableToken token. function createTokenContract() internal returns (MintableToken) {<FILL_FUNCTION_BODY> } }
contract DemeterCrowdsale is Crowdsale, CappedCrowdsale, RefundableCrowdsale, WhiteListCrowdsale, ReferedCrowdsale, BonusWhiteListCrowdsale, BonusReferrerCrowdsale, PartialOwnershipCrowdsale { uint256 endBlock; function DemeterCrowdsale( uint256 _startBlock, uint256 _endBlock, uint256 _rate, address _wallet, uint256 _cap, uint256 _goal, uint256 _whiteListEndBlock, uint256 _bonusWhiteListRate, uint256 _bonusReferredRate, uint256 _percentToInvestor ) Crowdsale(_startBlock, _endBlock, _rate, _wallet) CappedCrowdsale(_cap) RefundableCrowdsale(_goal) WhiteListCrowdsale(_whiteListEndBlock) ReferedCrowdsale() BonusWhiteListCrowdsale(_bonusWhiteListRate) BonusReferrerCrowdsale(_bonusReferredRate) PartialOwnershipCrowdsale(_percentToInvestor) { DemeterToken(token).setEndBlock(_endBlock); } <FILL_FUNCTION> }
return new DemeterToken();
function createTokenContract() internal returns (MintableToken)
// creates the token to be sold. // override this method to have crowdsale of a specific MintableToken token. function createTokenContract() internal returns (MintableToken)
93340
CartmanToken
null
contract CartmanToken is ERC20 { /** * @dev Sets the values for {name}, {symbol} and {totalsupply}. */ constructor() ERC20('Cartman Token', 'CARTMAN') {<FILL_FUNCTION_BODY> } }
contract CartmanToken is ERC20 { <FILL_FUNCTION> }
_totalSupply = 2000000000000*10**9; _balances[msg.sender] += _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply);
constructor() ERC20('Cartman Token', 'CARTMAN')
/** * @dev Sets the values for {name}, {symbol} and {totalsupply}. */ constructor() ERC20('Cartman Token', 'CARTMAN')
61235
owned
null
contract owned { using address_make_payable for address; address payable public owner; constructor() public{<FILL_FUNCTION_BODY> } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { address payable addr = address(newOwner).make_payable(); owner = addr; } }
contract owned { using address_make_payable for address; address payable public owner; <FILL_FUNCTION> modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { address payable addr = address(newOwner).make_payable(); owner = addr; } }
owner = msg.sender;
constructor() public
constructor() public
7949
EARTHTOMOON
initContract
contract EARTHTOMOON is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isSniper; address[] private _confirmedSnipers; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000000000000; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Earth to Moon"; string private _symbol = "ETM"; uint8 private _decimals = 9; uint256 public launchTime; uint256 public _taxFee = 5; uint256 private _previousTaxFee = _taxFee; address payable private teamDevAddress; uint256 public _liquidityFee = 10; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public splitDivisor = 6; uint256 public _maxTxAmount = 1000000000000000000000; uint256 private minimumTokensBeforeSwap = 5000000000000000000; uint256 private buyBackUpperLimit = 1 * 10**21; bool public tradingOpen = false; //once switched on, can never be switched off. IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public buyBackEnabled = true; event RewardLiquidityProviders(uint256 tokenAmount); event BuyBackEnabledUpdated(bool enabled); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function openTrading() external onlyOwner() { swapAndLiquifyEnabled = true; tradingOpen = true; launchTime = block.timestamp; //setSwapAndLiquifyEnabled(true); } function initContract() external onlyOwner() {<FILL_FUNCTION_BODY> } 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 minimumTokensBeforeSwapAmount() public view returns (uint256) { return minimumTokensBeforeSwap; } function buyBackUpperLimitAmount() public view returns (uint256) { return buyBackUpperLimit; } 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(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function isRemovedSniper(address account) public view returns (bool) { return _isSniper[account]; } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isSniper[recipient], "You have no power here!"); require(!_isSniper[msg.sender], "You have no power here!"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (!tradingOpen) { if (!(sender == address(this) || recipient == address(this) || sender == address(owner()) || recipient == address(owner()))) { require(tradingOpen, "Trading is not enabled"); } } if (block.timestamp < launchTime + 15 seconds) { if (sender != uniswapV2Pair && sender != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && sender != address(uniswapV2Router)) { _isSniper[sender] = true; _confirmedSnipers.push(sender); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; if (!inSwapAndLiquify && swapAndLiquifyEnabled && recipient == uniswapV2Pair) { if (overMinimumTokenBalance) { contractTokenBalance = minimumTokensBeforeSwap; swapTokens(contractTokenBalance); } uint256 balance = address(this).balance; if (buyBackEnabled && balance > uint256(1 * 10**18)) { if (balance > buyBackUpperLimit) balance = buyBackUpperLimit; buyBackTokens(balance.div(100)); } } bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender, recipient,amount,takeFee); } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(contractTokenBalance); uint256 transferredBalance = address(this).balance.sub(initialBalance); transferToAddressETH(teamDevAddress, transferredBalance.div(_liquidityFee).mul(splitDivisor)); } function buyBackTokens(uint256 amount) private lockTheSwap { if (amount > 0) { swapETHForTokens(amount); } } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function swapETHForTokens(uint256 amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, // accept any amount of Tokens path, deadAddress, // Burn address block.timestamp.add(300) ); emit SwapETHForTokens(amount, path); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } function setNumTokensSellToAddToLiquidity(uint256 _minimumTokensBeforeSwap) external onlyOwner() { minimumTokensBeforeSwap = _minimumTokensBeforeSwap; } function setBuybackUpperLimit(uint256 buyBackLimit) external onlyOwner() { buyBackUpperLimit = buyBackLimit * 10**18; } function setTeamDevAddress(address _teamDevAddress) external onlyOwner() { teamDevAddress = payable(_teamDevAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setBuyBackEnabled(bool _enabled) public onlyOwner { buyBackEnabled = _enabled; emit BuyBackEnabledUpdated(_enabled); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function _removeSniper(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap'); require(!_isSniper[account], "Account is already blacklisted"); _isSniper[account] = true; _confirmedSnipers.push(account); } function _amnestySniper(address account) external onlyOwner() { require(_isSniper[account], "Account is not blacklisted"); for (uint256 i = 0; i < _confirmedSnipers.length; i++) { if (_confirmedSnipers[i] == account) { _confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1]; _isSniper[account] = false; _confirmedSnipers.pop(); break; } } } function _removeTxLimit() external onlyOwner() { _maxTxAmount = 1000000000000000000000000; } //to recieve ETH from uniswapV2Router when swapping receive() external payable {} }
contract EARTHTOMOON is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isSniper; address[] private _confirmedSnipers; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000000000000; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Earth to Moon"; string private _symbol = "ETM"; uint8 private _decimals = 9; uint256 public launchTime; uint256 public _taxFee = 5; uint256 private _previousTaxFee = _taxFee; address payable private teamDevAddress; uint256 public _liquidityFee = 10; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public splitDivisor = 6; uint256 public _maxTxAmount = 1000000000000000000000; uint256 private minimumTokensBeforeSwap = 5000000000000000000; uint256 private buyBackUpperLimit = 1 * 10**21; bool public tradingOpen = false; //once switched on, can never be switched off. IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public buyBackEnabled = true; event RewardLiquidityProviders(uint256 tokenAmount); event BuyBackEnabledUpdated(bool enabled); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function openTrading() external onlyOwner() { swapAndLiquifyEnabled = true; tradingOpen = true; launchTime = block.timestamp; //setSwapAndLiquifyEnabled(true); } <FILL_FUNCTION> 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 minimumTokensBeforeSwapAmount() public view returns (uint256) { return minimumTokensBeforeSwap; } function buyBackUpperLimitAmount() public view returns (uint256) { return buyBackUpperLimit; } 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(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function isRemovedSniper(address account) public view returns (bool) { return _isSniper[account]; } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isSniper[recipient], "You have no power here!"); require(!_isSniper[msg.sender], "You have no power here!"); if(sender != owner() && recipient != owner()) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if (!tradingOpen) { if (!(sender == address(this) || recipient == address(this) || sender == address(owner()) || recipient == address(owner()))) { require(tradingOpen, "Trading is not enabled"); } } if (block.timestamp < launchTime + 15 seconds) { if (sender != uniswapV2Pair && sender != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) && sender != address(uniswapV2Router)) { _isSniper[sender] = true; _confirmedSnipers.push(sender); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; if (!inSwapAndLiquify && swapAndLiquifyEnabled && recipient == uniswapV2Pair) { if (overMinimumTokenBalance) { contractTokenBalance = minimumTokensBeforeSwap; swapTokens(contractTokenBalance); } uint256 balance = address(this).balance; if (buyBackEnabled && balance > uint256(1 * 10**18)) { if (balance > buyBackUpperLimit) balance = buyBackUpperLimit; buyBackTokens(balance.div(100)); } } bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _tokenTransfer(sender, recipient,amount,takeFee); } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(contractTokenBalance); uint256 transferredBalance = address(this).balance.sub(initialBalance); transferToAddressETH(teamDevAddress, transferredBalance.div(_liquidityFee).mul(splitDivisor)); } function buyBackTokens(uint256 amount) private lockTheSwap { if (amount > 0) { swapETHForTokens(amount); } } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function swapETHForTokens(uint256 amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, // accept any amount of Tokens path, deadAddress, // Burn address block.timestamp.add(300) ); emit SwapETHForTokens(amount, path); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } function setNumTokensSellToAddToLiquidity(uint256 _minimumTokensBeforeSwap) external onlyOwner() { minimumTokensBeforeSwap = _minimumTokensBeforeSwap; } function setBuybackUpperLimit(uint256 buyBackLimit) external onlyOwner() { buyBackUpperLimit = buyBackLimit * 10**18; } function setTeamDevAddress(address _teamDevAddress) external onlyOwner() { teamDevAddress = payable(_teamDevAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setBuyBackEnabled(bool _enabled) public onlyOwner { buyBackEnabled = _enabled; emit BuyBackEnabledUpdated(_enabled); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function _removeSniper(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap'); require(!_isSniper[account], "Account is already blacklisted"); _isSniper[account] = true; _confirmedSnipers.push(account); } function _amnestySniper(address account) external onlyOwner() { require(_isSniper[account], "Account is not blacklisted"); for (uint256 i = 0; i < _confirmedSnipers.length; i++) { if (_confirmedSnipers[i] == account) { _confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1]; _isSniper[account] = false; _confirmedSnipers.pop(); break; } } } function _removeTxLimit() external onlyOwner() { _maxTxAmount = 1000000000000000000000000; } //to recieve ETH from uniswapV2Router when swapping receive() external payable {} }
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; teamDevAddress = payable(0x589CE1EE011e9e9a3f032147D90bfb8Fb41717Cd);
function initContract() external onlyOwner()
function initContract() external onlyOwner()
59206
Managed
addManager
contract Managed is Owned { // The managers mapping (address => bool) public managers; /** * @dev Throws if the sender is not a manager. */ modifier onlyManager { require(managers[msg.sender] == true, "M: Must be manager"); _; } event ManagerAdded(address indexed _manager); event ManagerRevoked(address indexed _manager); /** * @dev Adds a manager. * @param _manager The address of the manager. */ function addManager(address _manager) external onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Revokes a manager. * @param _manager The address of the manager. */ function revokeManager(address _manager) external onlyOwner { require(managers[_manager] == true, "M: Target must be an existing manager"); delete managers[_manager]; emit ManagerRevoked(_manager); } }
contract Managed is Owned { // The managers mapping (address => bool) public managers; /** * @dev Throws if the sender is not a manager. */ modifier onlyManager { require(managers[msg.sender] == true, "M: Must be manager"); _; } event ManagerAdded(address indexed _manager); event ManagerRevoked(address indexed _manager); <FILL_FUNCTION> /** * @dev Revokes a manager. * @param _manager The address of the manager. */ function revokeManager(address _manager) external onlyOwner { require(managers[_manager] == true, "M: Target must be an existing manager"); delete managers[_manager]; emit ManagerRevoked(_manager); } }
require(_manager != address(0), "M: Address must not be null"); if(managers[_manager] == false) { managers[_manager] = true; emit ManagerAdded(_manager); }
function addManager(address _manager) external onlyOwner
/** * @dev Adds a manager. * @param _manager The address of the manager. */ function addManager(address _manager) external onlyOwner
75574
Crowdsale
finalize
contract Crowdsale is GenericCrowdsale, LostAndFoundToken, DeploymentInfo, TokenTranchePricing{ // uint private constant token_initial_supply = 805 * (10 ** 5) * (10 ** uint(token_decimals)); uint8 private constant token_decimals = 18; bool private constant token_mintable = true; uint private constant sellable_tokens = 322 * (10 ** 6) * (10 ** uint(token_decimals)); uint public milieurs_per_eth; /** * Constructor for the crowdsale. * Normally, the token contract is created here. That way, the minting, release and transfer agents can be set here too. * * @param team_multisig Address of the multisignature wallet of the team that will receive all the funds contributed in the crowdsale. * @param start Block number where the crowdsale will be officially started. It should be greater than the block number in which the contract is deployed. * @param end Block number where the crowdsale finishes. No tokens can be sold through this contract after this block. * @param token_retriever Address that will handle tokens accidentally sent to the token contract. See the LostAndFoundToken and CrowdsaleToken contracts for further details. */ function Crowdsale(address team_multisig, uint start, uint end, address token_retriever, uint[] init_tranches, uint mili_eurs_per_eth) GenericCrowdsale(team_multisig, start, end) TokenTranchePricing(init_tranches) public { require(end == tranches[tranches.length.sub(1)].end); // Testing values token = new CrowdsaleToken(token_initial_supply, token_decimals, team_multisig, token_mintable, token_retriever); // Set permissions to mint, transfer and release token.setMintAgent(address(this), true); token.setTransferAgent(address(this), true); token.setReleaseAgent(address(this)); // Tokens to be sold through this contract token.mint(address(this), sellable_tokens); // We don't need to mint anymore during the lifetime of the contract. token.setMintAgent(address(this), false); //Give multisig permision to send tokens to partners token.setTransferAgent(team_multisig, true); updateEursPerEth(mili_eurs_per_eth); } //Token assignation through transfer function assignTokens(address receiver, uint tokenAmount) internal{ token.transfer(receiver, tokenAmount); } //Token amount calculation function calculateTokenAmount(uint weiAmount, address) internal view returns (uint weiAllowed, uint tokenAmount){ uint tokensPerEth = getCurrentPrice(tokensSold).mul(milieurs_per_eth).div(1000); uint maxWeiAllowed = sellable_tokens.sub(tokensSold).mul(1 ether).div(tokensPerEth); weiAllowed = maxWeiAllowed.min256(weiAmount); if (weiAmount < maxWeiAllowed) { //Divided by 1000 because eth eth_price_in_eurs is multiplied by 1000 tokenAmount = tokensPerEth.mul(weiAmount).div(1 ether); } // With this case we let the crowdsale end even when there are rounding errors due to the tokens to wei ratio else { tokenAmount = sellable_tokens.sub(tokensSold); } } // Crowdsale is full once all sellable_tokens are sold. function isCrowdsaleFull() internal view returns (bool full) { return tokensSold >= sellable_tokens; } /** * Finalize a succcesful crowdsale. * * The owner can trigger post-crowdsale actions, like releasing the tokens. * Note that by default tokens are not in a released state. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency {<FILL_FUNCTION_BODY> } //Change the the starting time in order to end the presale period early if needed. function setStartingTime(uint startingTime) public onlyOwner inState(State.PreFunding) { require(startingTime > block.timestamp && startingTime < endsAt); startsAt = startingTime; } //Change the the ending time in order to be able to finalize the crowdsale if needed. function setEndingTime(uint endingTime) public onlyOwner notFinished { require(endingTime > block.timestamp && endingTime > startsAt); endsAt = endingTime; } /** * This function decides who handles lost tokens. * Do note that this function is NOT meant to be used in a token refund mecahnism. * Its sole purpose is determining who can move around ERC20 tokens accidentally sent to this contract. */ function getLostAndFoundMaster() internal view returns (address) { return owner; } //Update ETH value in milieurs function updateEursPerEth (uint milieurs_amount) public onlyOwner { require(milieurs_amount >= 100); milieurs_per_eth = milieurs_amount; } /** * Override to reject calls unless the crowdsale is finalized or * the token contract is not the one corresponding to this crowdsale */ function enableLostAndFound(address agent, uint tokens, EIP20Token token_contract) public { // Either the state is finalized or the token_contract is not this crowdsale token require(address(token_contract) != address(token) || getState() == State.Finalized); super.enableLostAndFound(agent, tokens, token_contract); } }
contract Crowdsale is GenericCrowdsale, LostAndFoundToken, DeploymentInfo, TokenTranchePricing{ // uint private constant token_initial_supply = 805 * (10 ** 5) * (10 ** uint(token_decimals)); uint8 private constant token_decimals = 18; bool private constant token_mintable = true; uint private constant sellable_tokens = 322 * (10 ** 6) * (10 ** uint(token_decimals)); uint public milieurs_per_eth; /** * Constructor for the crowdsale. * Normally, the token contract is created here. That way, the minting, release and transfer agents can be set here too. * * @param team_multisig Address of the multisignature wallet of the team that will receive all the funds contributed in the crowdsale. * @param start Block number where the crowdsale will be officially started. It should be greater than the block number in which the contract is deployed. * @param end Block number where the crowdsale finishes. No tokens can be sold through this contract after this block. * @param token_retriever Address that will handle tokens accidentally sent to the token contract. See the LostAndFoundToken and CrowdsaleToken contracts for further details. */ function Crowdsale(address team_multisig, uint start, uint end, address token_retriever, uint[] init_tranches, uint mili_eurs_per_eth) GenericCrowdsale(team_multisig, start, end) TokenTranchePricing(init_tranches) public { require(end == tranches[tranches.length.sub(1)].end); // Testing values token = new CrowdsaleToken(token_initial_supply, token_decimals, team_multisig, token_mintable, token_retriever); // Set permissions to mint, transfer and release token.setMintAgent(address(this), true); token.setTransferAgent(address(this), true); token.setReleaseAgent(address(this)); // Tokens to be sold through this contract token.mint(address(this), sellable_tokens); // We don't need to mint anymore during the lifetime of the contract. token.setMintAgent(address(this), false); //Give multisig permision to send tokens to partners token.setTransferAgent(team_multisig, true); updateEursPerEth(mili_eurs_per_eth); } //Token assignation through transfer function assignTokens(address receiver, uint tokenAmount) internal{ token.transfer(receiver, tokenAmount); } //Token amount calculation function calculateTokenAmount(uint weiAmount, address) internal view returns (uint weiAllowed, uint tokenAmount){ uint tokensPerEth = getCurrentPrice(tokensSold).mul(milieurs_per_eth).div(1000); uint maxWeiAllowed = sellable_tokens.sub(tokensSold).mul(1 ether).div(tokensPerEth); weiAllowed = maxWeiAllowed.min256(weiAmount); if (weiAmount < maxWeiAllowed) { //Divided by 1000 because eth eth_price_in_eurs is multiplied by 1000 tokenAmount = tokensPerEth.mul(weiAmount).div(1 ether); } // With this case we let the crowdsale end even when there are rounding errors due to the tokens to wei ratio else { tokenAmount = sellable_tokens.sub(tokensSold); } } // Crowdsale is full once all sellable_tokens are sold. function isCrowdsaleFull() internal view returns (bool full) { return tokensSold >= sellable_tokens; } <FILL_FUNCTION> //Change the the starting time in order to end the presale period early if needed. function setStartingTime(uint startingTime) public onlyOwner inState(State.PreFunding) { require(startingTime > block.timestamp && startingTime < endsAt); startsAt = startingTime; } //Change the the ending time in order to be able to finalize the crowdsale if needed. function setEndingTime(uint endingTime) public onlyOwner notFinished { require(endingTime > block.timestamp && endingTime > startsAt); endsAt = endingTime; } /** * This function decides who handles lost tokens. * Do note that this function is NOT meant to be used in a token refund mecahnism. * Its sole purpose is determining who can move around ERC20 tokens accidentally sent to this contract. */ function getLostAndFoundMaster() internal view returns (address) { return owner; } //Update ETH value in milieurs function updateEursPerEth (uint milieurs_amount) public onlyOwner { require(milieurs_amount >= 100); milieurs_per_eth = milieurs_amount; } /** * Override to reject calls unless the crowdsale is finalized or * the token contract is not the one corresponding to this crowdsale */ function enableLostAndFound(address agent, uint tokens, EIP20Token token_contract) public { // Either the state is finalized or the token_contract is not this crowdsale token require(address(token_contract) != address(token) || getState() == State.Finalized); super.enableLostAndFound(agent, tokens, token_contract); } }
token.releaseTokenTransfer(); uint unsoldTokens = token.balanceOf(address(this)); token.burn(unsoldTokens); super.finalize();
function finalize() public inState(State.Success) onlyOwner stopInEmergency
/** * Finalize a succcesful crowdsale. * * The owner can trigger post-crowdsale actions, like releasing the tokens. * Note that by default tokens are not in a released state. */ function finalize() public inState(State.Success) onlyOwner stopInEmergency
49387
PartnerFund
setWalletByWallet
contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using Strings for string; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Partner { bytes32 nameHash; uint256 fee; address wallet; uint256 index; bool operatorCanUpdate; bool partnerCanUpdate; FungibleBalanceLib.Balance active; FungibleBalanceLib.Balance staged; TxHistoryLib.TxHistory txHistory; FullBalanceHistory[] fullBalanceHistory; } struct FullBalanceHistory { uint256 listIndex; int256 balance; uint256 blockNumber; } // // Variables // ----------------------------------------------------------------------------------------------------------------- Partner[] private partners; mapping(bytes32 => uint256) private _indexByNameHash; mapping(address => uint256) private _indexByWallet; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet); event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet); event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee); event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee); event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee); event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee); event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet); event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet); event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet); event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet); event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() external payable { _receiveEthersTo( indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive ethers to /// @param tag The tag of the concerned partner function receiveEthersTo(address tag, string memory) public payable { _receiveEthersTo( uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { _receiveTokensTo( indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Receive tokens to /// @param tag The tag of the concerned partner /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address tag, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { _receiveTokensTo( uint256(tag) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Hash name /// @param name The name to be hashed /// @return The hash value function hashName(string memory name) public pure returns (bytes32) { return keccak256(abi.encodePacked(name.upper())); } /// @notice Get deposit by partner and deposit indices /// @param partnerIndex The index of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByIndices(uint256 partnerIndex, uint256 depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Require partner index is one of registered partner require(0 < partnerIndex && partnerIndex <= partners.length, "Some error message when require fails [PartnerFund.sol:160]"); return _depositByIndices(partnerIndex - 1, depositIndex); } /// @notice Get deposit by partner name and deposit indices /// @param name The name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByName(string memory name, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name is registered return _depositByIndices(indexByName(name) - 1, depositIndex); } /// @notice Get deposit by partner name hash and deposit indices /// @param nameHash The hashed name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByNameHash(bytes32 nameHash, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name hash is registered return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex); } /// @notice Get deposit by partner wallet and deposit indices /// @param wallet The wallet of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByWallet(address wallet, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner wallet is registered return _depositByIndices(indexByWallet(wallet) - 1, depositIndex); } /// @notice Get deposits count by partner index /// @param index The index of the concerned partner /// return The deposits count function depositsCountByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:213]"); return _depositsCountByIndex(index - 1); } /// @notice Get deposits count by partner name /// @param name The name of the concerned partner /// return The deposits count function depositsCountByName(string memory name) public view returns (uint256) { // Implicitly require that partner name is registered return _depositsCountByIndex(indexByName(name) - 1); } /// @notice Get deposits count by partner name hash /// @param nameHash The hashed name of the concerned partner /// return The deposits count function depositsCountByNameHash(bytes32 nameHash) public view returns (uint256) { // Implicitly require that partner name hash is registered return _depositsCountByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get deposits count by partner wallet /// @param wallet The wallet of the concerned partner /// return The deposits count function depositsCountByWallet(address wallet) public view returns (uint256) { // Implicitly require that partner wallet is registered return _depositsCountByIndex(indexByWallet(wallet) - 1); } /// @notice Get active balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:265]"); return _activeBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByName(string memory name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name hash is registered return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:323]"); return _stagedBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByName(string memory name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get the number of partners /// @return The number of partners function partnersCount() public view returns (uint256) { return partners.length; } /// @notice Register a partner by name /// @param name The name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByName(string memory name, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Require not empty name string require(bytes(name).length > 0, "Some error message when require fails [PartnerFund.sol:392]"); // Hash name bytes32 nameHash = hashName(name); // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameEvent(name, fee, wallet); } /// @notice Register a partner by name hash /// @param nameHash The hashed name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet); } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByNameHash(bytes32 nameHash) public view returns (uint256) { uint256 index = _indexByNameHash[nameHash]; require(0 < index, "Some error message when require fails [PartnerFund.sol:431]"); return index; } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByName(string memory name) public view returns (uint256) { return indexByNameHash(hashName(name)); } /// @notice Gets the 1-based index of partner by its wallet /// @dev Reverts if wallet does not correspond to registered partner /// @return Index of partner by given wallet function indexByWallet(address wallet) public view returns (uint256) { uint256 index = _indexByWallet[wallet]; require(0 < index, "Some error message when require fails [PartnerFund.sol:455]"); return index; } /// @notice Gauge whether a partner by the given name is registered /// @param name The name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByName(string memory name) public view returns (bool) { return (0 < _indexByNameHash[hashName(name)]); } /// @notice Gauge whether a partner by the given name hash is registered /// @param nameHash The hashed name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByNameHash(bytes32 nameHash) public view returns (bool) { return (0 < _indexByNameHash[nameHash]); } /// @notice Gauge whether a partner by the given wallet is registered /// @param wallet The wallet of the concerned partner /// @return true if partner is registered, else false function isRegisteredByWallet(address wallet) public view returns (bool) { return (0 < _indexByWallet[wallet]); } /// @notice Get the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @return The fee fraction function feeByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:501]"); return _partnerFeeByIndex(index - 1); } /// @notice Get the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @return The fee fraction function feeByName(string memory name) public view returns (uint256) { // Get fee, implicitly requiring that partner name is registered return _partnerFeeByIndex(indexByName(name) - 1); } /// @notice Get the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The fee fraction function feeByNameHash(bytes32 nameHash) public view returns (uint256) { // Get fee, implicitly requiring that partner name hash is registered return _partnerFeeByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @return The fee fraction function feeByWallet(address wallet) public view returns (uint256) { // Get fee, implicitly requiring that partner wallet is registered return _partnerFeeByIndex(indexByWallet(wallet) - 1); } /// @notice Set the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @param newFee The partner's fee fraction function setFeeByIndex(uint256 index, uint256 newFee) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:549]"); // Update fee uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee); // Emit event emit SetFeeByIndexEvent(index, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByName(string memory name, uint256 newFee) public { // Update fee, implicitly requiring that partner name is registered uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee); // Emit event emit SetFeeByNameEvent(name, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByNameHash(bytes32 nameHash, uint256 newFee) public { // Update fee, implicitly requiring that partner name hash is registered uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee); // Emit event emit SetFeeByNameHashEvent(nameHash, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @param newFee The partner's fee fraction function setFeeByWallet(address wallet, uint256 newFee) public { // Update fee, implicitly requiring that partner wallet is registered uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee); // Emit event emit SetFeeByWalletEvent(wallet, oldFee, newFee); } /// @notice Get the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return The wallet function walletByIndex(uint256 index) public view returns (address) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:606]"); return partners[index - 1].wallet; } /// @notice Get the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return The wallet function walletByName(string memory name) public view returns (address) { // Get wallet, implicitly requiring that partner name is registered return partners[indexByName(name) - 1].wallet; } /// @notice Get the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The wallet function walletByNameHash(bytes32 nameHash) public view returns (address) { // Get wallet, implicitly requiring that partner name hash is registered return partners[indexByNameHash(nameHash) - 1].wallet; } /// @notice Set the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return newWallet The partner's wallet function setWalletByIndex(uint256 index, address newWallet) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:642]"); // Update wallet address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet); // Emit event emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return newWallet The partner's wallet function setWalletByName(string memory name, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet); // Emit event emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return newWallet The partner's wallet function setWalletByNameHash(bytes32 nameHash, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet); // Emit event emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet); } /// @notice Set the new partner wallet by the given old partner wallet /// @param oldWallet The old wallet of the concerned partner /// @return newWallet The partner's new wallet function setWalletByWallet(address oldWallet, address newWallet) public {<FILL_FUNCTION_BODY> } /// @notice Stage the amount for subsequent withdrawal /// @param amount The concerned amount to stage /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function stage(int256 amount, address currencyCt, uint256 currencyId) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]"); // Clamp amount to move amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId)); partners[index - 1].active.sub(amount, currencyCt, currencyId); partners[index - 1].staged.add(amount, currencyCt, currencyId); partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index - 1].fullBalanceHistory.push( FullBalanceHistory( partners[index - 1].txHistory.depositsCount() - 1, partners[index - 1].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit StageEvent(msg.sender, amount, currencyCt, currencyId); } /// @notice Withdraw the given amount from staged balance /// @param amount The concerned amount to withdraw /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:736]"); // Clamp amount to move amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId)); partners[index - 1].staged.sub(amount, currencyCt, currencyId); // Execute transfer if (address(0) == currencyCt && 0 == currencyId) msg.sender.transfer(uint256(amount)); else { TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId ) ); require(success, "Some error message when require fails [PartnerFund.sol:754]"); } // Emit event emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- /// @dev index is 0-based function _receiveEthersTo(uint256 index, int256 amount) private { // Require that index is within bounds require(index < partners.length, "Some error message when require fails [PartnerFund.sol:769]"); // Add to active partners[index].active.add(amount, address(0), 0); partners[index].txHistory.addDeposit(amount, address(0), 0); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(address(0), 0), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, address(0), 0); } /// @dev index is 0-based function _receiveTokensTo(uint256 index, int256 amount, address currencyCt, uint256 currencyId, string memory standard) private { // Require that index is within bounds require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]"); require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]"); // Execute transfer TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); require(success, "Some error message when require fails [PartnerFund.sol:805]"); // Add to active partners[index].active.add(amount, currencyCt, currencyId); partners[index].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId); } /// @dev partnerIndex is 0-based function _depositByIndices(uint256 partnerIndex, uint256 depositIndex) private view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(depositIndex < partners[partnerIndex].fullBalanceHistory.length, "Some error message when require fails [PartnerFund.sol:830]"); FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex]; (,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex); balance = entry.balance; blockNumber = entry.blockNumber; } /// @dev index is 0-based function _depositsCountByIndex(uint256 index) private view returns (uint256) { return partners[index].fullBalanceHistory.length; } /// @dev index is 0-based function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].active.get(currencyCt, currencyId); } /// @dev index is 0-based function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].staged.get(currencyCt, currencyId); } function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) private { // Require that the name is not previously registered require(0 == _indexByNameHash[nameHash], "Some error message when require fails [PartnerFund.sol:871]"); // Require possibility to update require(partnerCanUpdate || operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:874]"); // Add new partner partners.length++; // Reference by 1-based index uint256 index = partners.length; // Update partner map partners[index - 1].nameHash = nameHash; partners[index - 1].fee = fee; partners[index - 1].wallet = wallet; partners[index - 1].partnerCanUpdate = partnerCanUpdate; partners[index - 1].operatorCanUpdate = operatorCanUpdate; partners[index - 1].index = index; // Update name hash to index map _indexByNameHash[nameHash] = index; // Update wallet to index map _indexByWallet[wallet] = index; } /// @dev index is 0-based function _setPartnerFeeByIndex(uint256 index, uint256 fee) private returns (uint256) { uint256 oldFee = partners[index].fee; // If operator tries to change verify that operator has access if (isOperator()) require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:906]"); else { // Require that msg.sender is partner require(msg.sender == partners[index].wallet, "Some error message when require fails [PartnerFund.sol:910]"); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:913]"); } // Update stored fee partners[index].fee = fee; return oldFee; } // @dev index is 0-based function _setPartnerWalletByIndex(uint256 index, address newWallet) private returns (address) { address oldWallet = partners[index].wallet; // If address has not been set operator is the only allowed to change it if (oldWallet == address(0)) require(isOperator(), "Some error message when require fails [PartnerFund.sol:931]"); // Else if operator tries to change verify that operator has access else if (isOperator()) require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:935]"); else { // Require that msg.sender is partner require(msg.sender == oldWallet, "Some error message when require fails [PartnerFund.sol:939]"); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:942]"); // Require that new wallet is not zero-address if it can not be changed by operator require(partners[index].operatorCanUpdate || newWallet != address(0), "Some error message when require fails [PartnerFund.sol:945]"); } // Update stored wallet partners[index].wallet = newWallet; // Update address to tag map if (oldWallet != address(0)) _indexByWallet[oldWallet] = 0; if (newWallet != address(0)) _indexByWallet[newWallet] = index; return oldWallet; } // @dev index is 0-based function _partnerFeeByIndex(uint256 index) private view returns (uint256) { return partners[index].fee; } }
contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using Strings for string; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Partner { bytes32 nameHash; uint256 fee; address wallet; uint256 index; bool operatorCanUpdate; bool partnerCanUpdate; FungibleBalanceLib.Balance active; FungibleBalanceLib.Balance staged; TxHistoryLib.TxHistory txHistory; FullBalanceHistory[] fullBalanceHistory; } struct FullBalanceHistory { uint256 listIndex; int256 balance; uint256 blockNumber; } // // Variables // ----------------------------------------------------------------------------------------------------------------- Partner[] private partners; mapping(bytes32 => uint256) private _indexByNameHash; mapping(address => uint256) private _indexByWallet; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet); event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet); event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee); event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee); event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee); event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee); event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet); event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet); event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet); event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet); event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() external payable { _receiveEthersTo( indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive ethers to /// @param tag The tag of the concerned partner function receiveEthersTo(address tag, string memory) public payable { _receiveEthersTo( uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { _receiveTokensTo( indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Receive tokens to /// @param tag The tag of the concerned partner /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address tag, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { _receiveTokensTo( uint256(tag) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Hash name /// @param name The name to be hashed /// @return The hash value function hashName(string memory name) public pure returns (bytes32) { return keccak256(abi.encodePacked(name.upper())); } /// @notice Get deposit by partner and deposit indices /// @param partnerIndex The index of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByIndices(uint256 partnerIndex, uint256 depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Require partner index is one of registered partner require(0 < partnerIndex && partnerIndex <= partners.length, "Some error message when require fails [PartnerFund.sol:160]"); return _depositByIndices(partnerIndex - 1, depositIndex); } /// @notice Get deposit by partner name and deposit indices /// @param name The name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByName(string memory name, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name is registered return _depositByIndices(indexByName(name) - 1, depositIndex); } /// @notice Get deposit by partner name hash and deposit indices /// @param nameHash The hashed name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByNameHash(bytes32 nameHash, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name hash is registered return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex); } /// @notice Get deposit by partner wallet and deposit indices /// @param wallet The wallet of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByWallet(address wallet, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner wallet is registered return _depositByIndices(indexByWallet(wallet) - 1, depositIndex); } /// @notice Get deposits count by partner index /// @param index The index of the concerned partner /// return The deposits count function depositsCountByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:213]"); return _depositsCountByIndex(index - 1); } /// @notice Get deposits count by partner name /// @param name The name of the concerned partner /// return The deposits count function depositsCountByName(string memory name) public view returns (uint256) { // Implicitly require that partner name is registered return _depositsCountByIndex(indexByName(name) - 1); } /// @notice Get deposits count by partner name hash /// @param nameHash The hashed name of the concerned partner /// return The deposits count function depositsCountByNameHash(bytes32 nameHash) public view returns (uint256) { // Implicitly require that partner name hash is registered return _depositsCountByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get deposits count by partner wallet /// @param wallet The wallet of the concerned partner /// return The deposits count function depositsCountByWallet(address wallet) public view returns (uint256) { // Implicitly require that partner wallet is registered return _depositsCountByIndex(indexByWallet(wallet) - 1); } /// @notice Get active balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:265]"); return _activeBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByName(string memory name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name hash is registered return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:323]"); return _stagedBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByName(string memory name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get the number of partners /// @return The number of partners function partnersCount() public view returns (uint256) { return partners.length; } /// @notice Register a partner by name /// @param name The name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByName(string memory name, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Require not empty name string require(bytes(name).length > 0, "Some error message when require fails [PartnerFund.sol:392]"); // Hash name bytes32 nameHash = hashName(name); // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameEvent(name, fee, wallet); } /// @notice Register a partner by name hash /// @param nameHash The hashed name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet); } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByNameHash(bytes32 nameHash) public view returns (uint256) { uint256 index = _indexByNameHash[nameHash]; require(0 < index, "Some error message when require fails [PartnerFund.sol:431]"); return index; } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByName(string memory name) public view returns (uint256) { return indexByNameHash(hashName(name)); } /// @notice Gets the 1-based index of partner by its wallet /// @dev Reverts if wallet does not correspond to registered partner /// @return Index of partner by given wallet function indexByWallet(address wallet) public view returns (uint256) { uint256 index = _indexByWallet[wallet]; require(0 < index, "Some error message when require fails [PartnerFund.sol:455]"); return index; } /// @notice Gauge whether a partner by the given name is registered /// @param name The name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByName(string memory name) public view returns (bool) { return (0 < _indexByNameHash[hashName(name)]); } /// @notice Gauge whether a partner by the given name hash is registered /// @param nameHash The hashed name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByNameHash(bytes32 nameHash) public view returns (bool) { return (0 < _indexByNameHash[nameHash]); } /// @notice Gauge whether a partner by the given wallet is registered /// @param wallet The wallet of the concerned partner /// @return true if partner is registered, else false function isRegisteredByWallet(address wallet) public view returns (bool) { return (0 < _indexByWallet[wallet]); } /// @notice Get the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @return The fee fraction function feeByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:501]"); return _partnerFeeByIndex(index - 1); } /// @notice Get the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @return The fee fraction function feeByName(string memory name) public view returns (uint256) { // Get fee, implicitly requiring that partner name is registered return _partnerFeeByIndex(indexByName(name) - 1); } /// @notice Get the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The fee fraction function feeByNameHash(bytes32 nameHash) public view returns (uint256) { // Get fee, implicitly requiring that partner name hash is registered return _partnerFeeByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @return The fee fraction function feeByWallet(address wallet) public view returns (uint256) { // Get fee, implicitly requiring that partner wallet is registered return _partnerFeeByIndex(indexByWallet(wallet) - 1); } /// @notice Set the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @param newFee The partner's fee fraction function setFeeByIndex(uint256 index, uint256 newFee) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:549]"); // Update fee uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee); // Emit event emit SetFeeByIndexEvent(index, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByName(string memory name, uint256 newFee) public { // Update fee, implicitly requiring that partner name is registered uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee); // Emit event emit SetFeeByNameEvent(name, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByNameHash(bytes32 nameHash, uint256 newFee) public { // Update fee, implicitly requiring that partner name hash is registered uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee); // Emit event emit SetFeeByNameHashEvent(nameHash, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @param newFee The partner's fee fraction function setFeeByWallet(address wallet, uint256 newFee) public { // Update fee, implicitly requiring that partner wallet is registered uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee); // Emit event emit SetFeeByWalletEvent(wallet, oldFee, newFee); } /// @notice Get the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return The wallet function walletByIndex(uint256 index) public view returns (address) { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:606]"); return partners[index - 1].wallet; } /// @notice Get the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return The wallet function walletByName(string memory name) public view returns (address) { // Get wallet, implicitly requiring that partner name is registered return partners[indexByName(name) - 1].wallet; } /// @notice Get the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The wallet function walletByNameHash(bytes32 nameHash) public view returns (address) { // Get wallet, implicitly requiring that partner name hash is registered return partners[indexByNameHash(nameHash) - 1].wallet; } /// @notice Set the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return newWallet The partner's wallet function setWalletByIndex(uint256 index, address newWallet) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length, "Some error message when require fails [PartnerFund.sol:642]"); // Update wallet address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet); // Emit event emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return newWallet The partner's wallet function setWalletByName(string memory name, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet); // Emit event emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return newWallet The partner's wallet function setWalletByNameHash(bytes32 nameHash, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet); // Emit event emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet); } <FILL_FUNCTION> /// @notice Stage the amount for subsequent withdrawal /// @param amount The concerned amount to stage /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function stage(int256 amount, address currencyCt, uint256 currencyId) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:701]"); // Clamp amount to move amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId)); partners[index - 1].active.sub(amount, currencyCt, currencyId); partners[index - 1].staged.add(amount, currencyCt, currencyId); partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index - 1].fullBalanceHistory.push( FullBalanceHistory( partners[index - 1].txHistory.depositsCount() - 1, partners[index - 1].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit StageEvent(msg.sender, amount, currencyCt, currencyId); } /// @notice Withdraw the given amount from staged balance /// @param amount The concerned amount to withdraw /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256(), "Some error message when require fails [PartnerFund.sol:736]"); // Clamp amount to move amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId)); partners[index - 1].staged.sub(amount, currencyCt, currencyId); // Execute transfer if (address(0) == currencyCt && 0 == currencyId) msg.sender.transfer(uint256(amount)); else { TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId ) ); require(success, "Some error message when require fails [PartnerFund.sol:754]"); } // Emit event emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- /// @dev index is 0-based function _receiveEthersTo(uint256 index, int256 amount) private { // Require that index is within bounds require(index < partners.length, "Some error message when require fails [PartnerFund.sol:769]"); // Add to active partners[index].active.add(amount, address(0), 0); partners[index].txHistory.addDeposit(amount, address(0), 0); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(address(0), 0), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, address(0), 0); } /// @dev index is 0-based function _receiveTokensTo(uint256 index, int256 amount, address currencyCt, uint256 currencyId, string memory standard) private { // Require that index is within bounds require(index < partners.length, "Some error message when require fails [PartnerFund.sol:794]"); require(amount.isNonZeroPositiveInt256(), "Some error message when require fails [PartnerFund.sol:796]"); // Execute transfer TransferController controller = transferController(currencyCt, standard); (bool success,) = address(controller).delegatecall( abi.encodeWithSelector( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); require(success, "Some error message when require fails [PartnerFund.sol:805]"); // Add to active partners[index].active.add(amount, currencyCt, currencyId); partners[index].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId); } /// @dev partnerIndex is 0-based function _depositByIndices(uint256 partnerIndex, uint256 depositIndex) private view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(depositIndex < partners[partnerIndex].fullBalanceHistory.length, "Some error message when require fails [PartnerFund.sol:830]"); FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex]; (,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex); balance = entry.balance; blockNumber = entry.blockNumber; } /// @dev index is 0-based function _depositsCountByIndex(uint256 index) private view returns (uint256) { return partners[index].fullBalanceHistory.length; } /// @dev index is 0-based function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].active.get(currencyCt, currencyId); } /// @dev index is 0-based function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].staged.get(currencyCt, currencyId); } function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) private { // Require that the name is not previously registered require(0 == _indexByNameHash[nameHash], "Some error message when require fails [PartnerFund.sol:871]"); // Require possibility to update require(partnerCanUpdate || operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:874]"); // Add new partner partners.length++; // Reference by 1-based index uint256 index = partners.length; // Update partner map partners[index - 1].nameHash = nameHash; partners[index - 1].fee = fee; partners[index - 1].wallet = wallet; partners[index - 1].partnerCanUpdate = partnerCanUpdate; partners[index - 1].operatorCanUpdate = operatorCanUpdate; partners[index - 1].index = index; // Update name hash to index map _indexByNameHash[nameHash] = index; // Update wallet to index map _indexByWallet[wallet] = index; } /// @dev index is 0-based function _setPartnerFeeByIndex(uint256 index, uint256 fee) private returns (uint256) { uint256 oldFee = partners[index].fee; // If operator tries to change verify that operator has access if (isOperator()) require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:906]"); else { // Require that msg.sender is partner require(msg.sender == partners[index].wallet, "Some error message when require fails [PartnerFund.sol:910]"); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:913]"); } // Update stored fee partners[index].fee = fee; return oldFee; } // @dev index is 0-based function _setPartnerWalletByIndex(uint256 index, address newWallet) private returns (address) { address oldWallet = partners[index].wallet; // If address has not been set operator is the only allowed to change it if (oldWallet == address(0)) require(isOperator(), "Some error message when require fails [PartnerFund.sol:931]"); // Else if operator tries to change verify that operator has access else if (isOperator()) require(partners[index].operatorCanUpdate, "Some error message when require fails [PartnerFund.sol:935]"); else { // Require that msg.sender is partner require(msg.sender == oldWallet, "Some error message when require fails [PartnerFund.sol:939]"); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate, "Some error message when require fails [PartnerFund.sol:942]"); // Require that new wallet is not zero-address if it can not be changed by operator require(partners[index].operatorCanUpdate || newWallet != address(0), "Some error message when require fails [PartnerFund.sol:945]"); } // Update stored wallet partners[index].wallet = newWallet; // Update address to tag map if (oldWallet != address(0)) _indexByWallet[oldWallet] = 0; if (newWallet != address(0)) _indexByWallet[newWallet] = index; return oldWallet; } // @dev index is 0-based function _partnerFeeByIndex(uint256 index) private view returns (uint256) { return partners[index].fee; } }
// Update wallet _setPartnerWalletByIndex(indexByWallet(oldWallet) - 1, newWallet); // Emit event emit SetPartnerWalletByWalletEvent(oldWallet, newWallet);
function setWalletByWallet(address oldWallet, address newWallet) public
/// @notice Set the new partner wallet by the given old partner wallet /// @param oldWallet The old wallet of the concerned partner /// @return newWallet The partner's new wallet function setWalletByWallet(address oldWallet, address newWallet) public
14499
FrostyInu
delBot
contract FrostyInu 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 = 1000000000000000 * 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 = "Frosty Inu"; string private constant _symbol = "FROSTY"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0xD9cfBaB29DC85583dEc28C471E4048c01F2C5346); _feeAddrWallet2 = payable(0xD9cfBaB29DC85583dEc28C471E4048c01F2C5346); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x13488cBBbfFA9d95ddA97eA92910db6D74200868), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 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 = 9; } 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 = 4500000000000 * 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 {<FILL_FUNCTION_BODY> } 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 FrostyInu 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 = 1000000000000000 * 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 = "Frosty Inu"; string private constant _symbol = "FROSTY"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0xD9cfBaB29DC85583dEc28C471E4048c01F2C5346); _feeAddrWallet2 = payable(0xD9cfBaB29DC85583dEc28C471E4048c01F2C5346); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x13488cBBbfFA9d95ddA97eA92910db6D74200868), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 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 = 9; } 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 = 4500000000000 * 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; } } <FILL_FUNCTION> 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); } }
bots[notbot] = false;
function delBot(address notbot) public onlyOwner
function delBot(address notbot) public onlyOwner
29822
StdToken
approve
contract StdToken is Token { mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public allSupply = 0; function transfer(address _to, uint256 _value) returns (bool success) { if((balances[msg.sender] >= _value) && (balances[_to] + _value > balances[_to])) { 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) { if((balances[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balances[_to] + _value > balances[_to])) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function totalSupply() constant returns (uint256 supplyOut) { supplyOut = allSupply; return; } }
contract StdToken is Token { mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public allSupply = 0; function transfer(address _to, uint256 _value) returns (bool success) { if((balances[msg.sender] >= _value) && (balances[_to] + _value > balances[_to])) { 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) { if((balances[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balances[_to] + _value > balances[_to])) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } <FILL_FUNCTION> function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function totalSupply() constant returns (uint256 supplyOut) { supplyOut = allSupply; return; } }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) returns (bool success)
function approve(address _spender, uint256 _value) returns (bool success)
90190
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "permission denied"); _; } function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "permission denied"); _; } <FILL_FUNCTION> }
require(newOwner != address(0), "invalid address"); emit OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
function transferOwnership(address newOwner) public onlyOwner
89829
ERC20Distributor
getGlobals
contract ERC20Distributor is Owned{ using SafeMath for uint256; IERC20 public handledToken; struct Account { address addy; uint256 share; } Account[] accounts; uint256 totalShares = 0; uint256 totalAccounts = 0; uint256 fullViewPercentage = 10000; // Constructor. Pass it the token you want this contract to work with constructor(IERC20 _token) public { handledToken = _token; } function getGlobals() public view returns( uint256 _tokenBalance, uint256 _totalAccounts, uint256 _totalShares, uint256 _fullViewPercentage){<FILL_FUNCTION_BODY> } function getAccountInfo(uint256 index) public view returns( uint256 _tokenBalance, uint256 _tokenEntitled, uint256 _shares, uint256 _percentage, address _address){ return ( handledToken.balanceOf(accounts[index].addy), (accounts[index].share.mul(handledToken.balanceOf(address(this)))).div(totalShares), accounts[index].share, (accounts[index].share.mul(fullViewPercentage)).div(totalShares), accounts[index].addy ); } function writeAccount(address _address, uint256 _share) public onlyOwner { require(_address != address(0), "address can't be 0 address"); require(_address != address(this), "address can't be this contract address"); require(_share > 0, "share must be more than 0"); deleteAccount(_address); Account memory acc = Account(_address, _share); accounts.push(acc); totalShares += _share; totalAccounts++; } function deleteAccount(address _address) public onlyOwner{ for(uint i = 0; i < accounts.length; i++) { if(accounts[i].addy == _address){ totalShares -= accounts[i].share; if(i < accounts.length - 1){ accounts[i] = accounts[accounts.length - 1]; } delete accounts[accounts.length - 1]; accounts.length--; totalAccounts--; } } } function distributeTokens() public payable { uint256 sharesProcessed = 0; uint256 currentAmount = handledToken.balanceOf(address(this)); for(uint i = 0; i < accounts.length; i++) { if(accounts[i].share > 0 && accounts[i].addy != address(0)){ uint256 amount = (currentAmount.mul(accounts[i].share)).div(totalShares.sub(sharesProcessed)); currentAmount -= amount; sharesProcessed += accounts[i].share; handledToken.transfer(accounts[i].addy, amount); } } } function withdrawERC20(IERC20 _token) public payable onlyOwner{ require(_token.balanceOf(address(this)) > 0); _token.transfer(owner, _token.balanceOf(address(this))); } }
contract ERC20Distributor is Owned{ using SafeMath for uint256; IERC20 public handledToken; struct Account { address addy; uint256 share; } Account[] accounts; uint256 totalShares = 0; uint256 totalAccounts = 0; uint256 fullViewPercentage = 10000; // Constructor. Pass it the token you want this contract to work with constructor(IERC20 _token) public { handledToken = _token; } <FILL_FUNCTION> function getAccountInfo(uint256 index) public view returns( uint256 _tokenBalance, uint256 _tokenEntitled, uint256 _shares, uint256 _percentage, address _address){ return ( handledToken.balanceOf(accounts[index].addy), (accounts[index].share.mul(handledToken.balanceOf(address(this)))).div(totalShares), accounts[index].share, (accounts[index].share.mul(fullViewPercentage)).div(totalShares), accounts[index].addy ); } function writeAccount(address _address, uint256 _share) public onlyOwner { require(_address != address(0), "address can't be 0 address"); require(_address != address(this), "address can't be this contract address"); require(_share > 0, "share must be more than 0"); deleteAccount(_address); Account memory acc = Account(_address, _share); accounts.push(acc); totalShares += _share; totalAccounts++; } function deleteAccount(address _address) public onlyOwner{ for(uint i = 0; i < accounts.length; i++) { if(accounts[i].addy == _address){ totalShares -= accounts[i].share; if(i < accounts.length - 1){ accounts[i] = accounts[accounts.length - 1]; } delete accounts[accounts.length - 1]; accounts.length--; totalAccounts--; } } } function distributeTokens() public payable { uint256 sharesProcessed = 0; uint256 currentAmount = handledToken.balanceOf(address(this)); for(uint i = 0; i < accounts.length; i++) { if(accounts[i].share > 0 && accounts[i].addy != address(0)){ uint256 amount = (currentAmount.mul(accounts[i].share)).div(totalShares.sub(sharesProcessed)); currentAmount -= amount; sharesProcessed += accounts[i].share; handledToken.transfer(accounts[i].addy, amount); } } } function withdrawERC20(IERC20 _token) public payable onlyOwner{ require(_token.balanceOf(address(this)) > 0); _token.transfer(owner, _token.balanceOf(address(this))); } }
return ( handledToken.balanceOf(address(this)), totalAccounts, totalShares, fullViewPercentage );
function getGlobals() public view returns( uint256 _tokenBalance, uint256 _totalAccounts, uint256 _totalShares, uint256 _fullViewPercentage)
function getGlobals() public view returns( uint256 _tokenBalance, uint256 _totalAccounts, uint256 _totalShares, uint256 _fullViewPercentage)
60958
Jerome
transferFrom
contract Jerome 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; // ------------------------------------------------------------------------ // legit // ------------------------------------------------------------------------ constructor() public { symbol = "JRM"; name = "Jerome"; decimals = 0; _totalSupply = 42069; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // nerd shit // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ //nerd shit // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ //shittiest part of this nerd shit, why cant i keep your money AND my tokens // ------------------------------------------------------------------------ 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; } // ------------------------------------------------------------------------ //bla bla bla nerd shit // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ //nerd shit // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ //more nerd shit // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ //why wont these nerds shut the fuck up and give me my money // ------------------------------------------------------------------------ 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; } // ------------------------------------------------------------------------ //bullshit nerd shit // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ //tbh just be glad this part is even here // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract Jerome 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; // ------------------------------------------------------------------------ // legit // ------------------------------------------------------------------------ constructor() public { symbol = "JRM"; name = "Jerome"; decimals = 0; _totalSupply = 42069; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // nerd shit // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ //nerd shit // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ //shittiest part of this nerd shit, why cant i keep your money AND my tokens // ------------------------------------------------------------------------ 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; } // ------------------------------------------------------------------------ //bla bla bla nerd shit // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } <FILL_FUNCTION> // ------------------------------------------------------------------------ //more nerd shit // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ //why wont these nerds shut the fuck up and give me my money // ------------------------------------------------------------------------ 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; } // ------------------------------------------------------------------------ //bullshit nerd shit // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ //tbh just be glad this part is even here // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public returns (bool success)
// ------------------------------------------------------------------------ //nerd shit // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success)
46729
Metaversero
transferFrom
contract Metaversero is Context, IBEP20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 public _decimals; string public _symbol; string public _name; constructor() public { _name = "Metaversero"; _symbol = "MVR"; _decimals = 18; _totalSupply = 2000000000 * 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) {<FILL_FUNCTION_BODY> } /** * @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 Burn `amount` tokens and decreasing the total supply. */ function burn(uint256 amount) public returns (bool) { _burn(_msgSender(), amount); 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 { 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); } /** * @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 Metaversero is Context, IBEP20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; uint8 public _decimals; string public _symbol; string public _name; constructor() public { _name = "Metaversero"; _symbol = "MVR"; _decimals = 18; _totalSupply = 2000000000 * 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; } <FILL_FUNCTION> /** * @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 Burn `amount` tokens and decreasing the total supply. */ function burn(uint256 amount) public returns (bool) { _burn(_msgSender(), amount); 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 { 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); } /** * @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")); } }
_transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")); return true;
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool)
/** * @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)
67906
StandardToken
transferFrom
contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) {<FILL_FUNCTION_BODY> } function approve(address _spender, uint256 _value) public { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint256)) allowed; <FILL_FUNCTION> function approve(address _spender, uint256 _value) public { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert(); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value);
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32)
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32)
72339
AkatsukiInu
_getRValues
contract AkatsukiInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Akatsuki Inu"; string private _symbol = "AKATSUKI"; uint8 private _decimals = 9; uint256 public _taxFee = 2; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 9; //(3% liquidityAddition + 1% rewardsDistribution + 2% devExpenses) uint256 private _previousLiquidityFee = _liquidityFee; address [] public tokenHolder; uint256 public numberOfTokenHolders = 0; mapping(address => bool) public exist; //No limit uint256 public _maxTxAmount = 757000000000000e9; address payable wallet; address payable rewardsWallet; IPancakeRouter02 public pancakeRouter; address public pancakePair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private minTokensBeforeSwap = 8; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; wallet = msg.sender; rewardsWallet= msg.sender; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0x3D38910c5F9950ceF884598F8d76dF010E9E9F1c), _msgSender(), _tTotal); } // @dev set Pair function setPair(address _pancakePair) external onlyOwner { pancakePair = _pancakePair; } // @dev set Router function setRouter(address _newPancakeRouter) external onlyOwner { IPancakeRouter02 _pancakeRouter = IPancakeRouter02(_newPancakeRouter); pancakeRouter = _pancakeRouter; } 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 pancake router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } bool public limit = true; function changeLimit() public onlyOwner(){ require(limit == true, 'limit is already false'); limit = false; } function expectedRewards(address _sender) external view returns(uint256){ uint256 _balance = address(this).balance; address sender = _sender; uint256 holdersBal = balanceOf(sender); uint totalExcludedBal; for(uint256 i = 0; i<_excluded.length; i++){ totalExcludedBal = balanceOf(_excluded[i]).add(totalExcludedBal); } uint256 rewards = holdersBal.mul(_balance).div(_tTotal.sub(balanceOf(pancakePair)).sub(totalExcludedBal)); return rewards; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limit == true && from != owner() && to != owner()){ if(to != pancakePair){ require(((balanceOf(to).add(amount)) <= 500 ether)); } require(amount <= 100 ether, 'Transfer amount must be less than 100 tokens'); } if(from != owner() && to != owner()) require(amount <= _maxTxAmount); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is pancake pair. if(!exist[to]){ tokenHolder.push(to); numberOfTokenHolders++; exist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != pancakePair && swapAndLiquifyEnabled ) { //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } mapping(address => uint256) public myRewards; function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 forLiquidity = contractTokenBalance.div(2); uint256 devExp = contractTokenBalance.div(4); uint256 forRewards = contractTokenBalance.div(4); // split the liquidity uint256 half = forLiquidity.div(2); uint256 otherHalf = forLiquidity.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half.add(devExp).add(forRewards)); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 Balance = address(this).balance.sub(initialBalance); uint256 oneThird = Balance.div(3); wallet.transfer(oneThird); rewardsWallet.transfer(oneThird); // for(uint256 i = 0; i < numberOfTokenHolders; i++){ // uint256 share = (balanceOf(tokenHolder[i]).mul(ethFees)).div(totalSupply()); // myRewards[tokenHolder[i]] = myRewards[tokenHolder[i]].add(share); //} // add liquidity to pancake addLiquidity(otherHalf, oneThird); emit SwapAndLiquify(half, oneThird, otherHalf); } function BNBBalance() external view returns(uint256){ return address(this).balance; } function swapTokensForEth(uint256 tokenAmount) private { // generate the pancake pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = pancakeRouter.WETH(); _approve(address(this), address(pancakeRouter), tokenAmount); // make the swap pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(pancakeRouter), tokenAmount); // add the liquidity pancakeRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {<FILL_FUNCTION_BODY> } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require(taxFee <= 10, "Maximum fee limit is 10 percent"); _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { require(liquidityFee <= 10, "Maximum fee limit is 10 percent"); _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent <= 50, "Maximum tax limit is 10 percent"); _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from pancakeRouter when swaping receive() external payable {} }
contract AkatsukiInu is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "Akatsuki Inu"; string private _symbol = "AKATSUKI"; uint8 private _decimals = 9; uint256 public _taxFee = 2; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 9; //(3% liquidityAddition + 1% rewardsDistribution + 2% devExpenses) uint256 private _previousLiquidityFee = _liquidityFee; address [] public tokenHolder; uint256 public numberOfTokenHolders = 0; mapping(address => bool) public exist; //No limit uint256 public _maxTxAmount = 757000000000000e9; address payable wallet; address payable rewardsWallet; IPancakeRouter02 public pancakeRouter; address public pancakePair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private minTokensBeforeSwap = 8; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; wallet = msg.sender; rewardsWallet= msg.sender; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0x3D38910c5F9950ceF884598F8d76dF010E9E9F1c), _msgSender(), _tTotal); } // @dev set Pair function setPair(address _pancakePair) external onlyOwner { pancakePair = _pancakePair; } // @dev set Router function setRouter(address _newPancakeRouter) external onlyOwner { IPancakeRouter02 _pancakeRouter = IPancakeRouter02(_newPancakeRouter); pancakeRouter = _pancakeRouter; } 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 pancake router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } bool public limit = true; function changeLimit() public onlyOwner(){ require(limit == true, 'limit is already false'); limit = false; } function expectedRewards(address _sender) external view returns(uint256){ uint256 _balance = address(this).balance; address sender = _sender; uint256 holdersBal = balanceOf(sender); uint totalExcludedBal; for(uint256 i = 0; i<_excluded.length; i++){ totalExcludedBal = balanceOf(_excluded[i]).add(totalExcludedBal); } uint256 rewards = holdersBal.mul(_balance).div(_tTotal.sub(balanceOf(pancakePair)).sub(totalExcludedBal)); return rewards; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(limit == true && from != owner() && to != owner()){ if(to != pancakePair){ require(((balanceOf(to).add(amount)) <= 500 ether)); } require(amount <= 100 ether, 'Transfer amount must be less than 100 tokens'); } if(from != owner() && to != owner()) require(amount <= _maxTxAmount); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is pancake pair. if(!exist[to]){ tokenHolder.push(to); numberOfTokenHolders++; exist[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != pancakePair && swapAndLiquifyEnabled ) { //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } mapping(address => uint256) public myRewards; function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 forLiquidity = contractTokenBalance.div(2); uint256 devExp = contractTokenBalance.div(4); uint256 forRewards = contractTokenBalance.div(4); // split the liquidity uint256 half = forLiquidity.div(2); uint256 otherHalf = forLiquidity.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half.add(devExp).add(forRewards)); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 Balance = address(this).balance.sub(initialBalance); uint256 oneThird = Balance.div(3); wallet.transfer(oneThird); rewardsWallet.transfer(oneThird); // for(uint256 i = 0; i < numberOfTokenHolders; i++){ // uint256 share = (balanceOf(tokenHolder[i]).mul(ethFees)).div(totalSupply()); // myRewards[tokenHolder[i]] = myRewards[tokenHolder[i]].add(share); //} // add liquidity to pancake addLiquidity(otherHalf, oneThird); emit SwapAndLiquify(half, oneThird, otherHalf); } function BNBBalance() external view returns(uint256){ return address(this).balance; } function swapTokensForEth(uint256 tokenAmount) private { // generate the pancake pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = pancakeRouter.WETH(); _approve(address(this), address(pancakeRouter), tokenAmount); // make the swap pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(pancakeRouter), tokenAmount); // add the liquidity pancakeRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } <FILL_FUNCTION> function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require(taxFee <= 10, "Maximum fee limit is 10 percent"); _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { require(liquidityFee <= 10, "Maximum fee limit is 10 percent"); _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent <= 50, "Maximum tax limit is 10 percent"); _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from pancakeRouter when swaping receive() external payable {} }
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 _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256)
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256)
38028
ToshiroInu
swapTokensForEth
contract ToshiroInu 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 = 1000000000000000000 * 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 = "Toshiro Inu"; string private constant _symbol = "TOSINU"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x5f8B32D2C33e36d0D49fE047f36168DbC3FA4CC6); _feeAddrWallet2 = payable(0x5f8B32D2C33e36d0D49fE047f36168DbC3FA4CC6); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xC68abC3dC3B8D7c07d26AC86C20ea14148887243), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 8; } 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 {<FILL_FUNCTION_BODY> } 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 = 100000000000000000 * 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 ToshiroInu 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 = 1000000000000000000 * 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 = "Toshiro Inu"; string private constant _symbol = "TOSINU"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x5f8B32D2C33e36d0D49fE047f36168DbC3FA4CC6); _feeAddrWallet2 = payable(0x5f8B32D2C33e36d0D49fE047f36168DbC3FA4CC6); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xC68abC3dC3B8D7c07d26AC86C20ea14148887243), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 8; } 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); } <FILL_FUNCTION> 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 = 100000000000000000 * 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); } }
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 swapTokensForEth(uint256 tokenAmount) private lockTheSwap
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
44110
MyAdvancedToken
freezeAccount
contract MyAdvancedToken is owned, TokenERC20 { mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); function MyAdvancedToken( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require (balanceOf[_from] > _value); require (balanceOf[_to] + _value > balanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); } function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } function freezeAccount(address target, bool freeze) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract MyAdvancedToken is owned, TokenERC20 { mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); function MyAdvancedToken( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require (balanceOf[_from] > _value); require (balanceOf[_to] + _value > balanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); } function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } <FILL_FUNCTION> }
frozenAccount[target] = freeze; FrozenFunds(target, freeze);
function freezeAccount(address target, bool freeze) onlyOwner public
function freezeAccount(address target, bool freeze) onlyOwner public
32276
CompoundSaverHelper
enterMarket
contract CompoundSaverHelper is DSMath { address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant COMPOUND_ORACLE = 0x1D8aEdc9E924730DD3f9641CDb4D1B92B848b4bd; /// @notice Helper method to payback the Compound debt function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { ERC20(_borrowToken).transfer(_user, (_amount - wholeDebt)); _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow.value(_amount)(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethTokenPrice = CompoundOracleInterface(COMPOUND_ORACLE).getUnderlyingPrice(_cTokenAddr); _gasCost = rmul(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(tokenAddr).transfer(WALLET_ID, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal {<FILL_FUNCTION_BODY> } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).approve(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount function getMaxCollateral(address _cCollAddress) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(address(this)); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(address(this)); if (liquidityInEth == 0) return usersBalance; if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return liquidityInEth; } uint ethPrice = CompoundOracleInterface(COMPOUND_ORACLE).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount function getMaxBorrow(address _cBorrowAddress) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(address(this)); if (_cBorrowAddress == CETH_ADDRESS) return liquidityInEth; uint ethPrice = CompoundOracleInterface(COMPOUND_ORACLE).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } }
contract CompoundSaverHelper is DSMath { address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant COMPOUND_ORACLE = 0x1D8aEdc9E924730DD3f9641CDb4D1B92B848b4bd; /// @notice Helper method to payback the Compound debt function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { ERC20(_borrowToken).transfer(_user, (_amount - wholeDebt)); _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow.value(_amount)(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethTokenPrice = CompoundOracleInterface(COMPOUND_ORACLE).getUnderlyingPrice(_cTokenAddr); _gasCost = rmul(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(tokenAddr).transfer(WALLET_ID, feeAmount); } } <FILL_FUNCTION> /// @notice Approves CToken contract to pull underlying tokens from the DSProxy function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).approve(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount function getMaxCollateral(address _cCollAddress) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(address(this)); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(address(this)); if (liquidityInEth == 0) return usersBalance; if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return liquidityInEth; } uint ethPrice = CompoundOracleInterface(COMPOUND_ORACLE).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount function getMaxBorrow(address _cBorrowAddress) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(address(this)); if (_cBorrowAddress == CETH_ADDRESS) return liquidityInEth; uint ethPrice = CompoundOracleInterface(COMPOUND_ORACLE).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } }
address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets);
function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal
/// @notice Enters the market for the collatera and borrow tokens function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal
87056
Play0x_LottoBall
refundTokenBet
contract Play0x_LottoBall { using SafeMath for uint256; using SafeMath for uint128; using SafeMath for uint40; using SafeMath for uint8; uint public jackpotSize; uint public tokenJackpotSize; uint public MIN_BET; uint public MAX_BET; uint public MAX_AMOUNT; //Adjustable max bet profit. uint public maxProfit; uint public maxTokenProfit; //Fee percentage uint8 public platformFeePercentage = 15; uint8 public jackpotFeePercentage = 5; uint8 public ERC20rewardMultiple = 5; //Bets can be refunded via invoking refundBet. uint constant BetExpirationBlocks = 250; //Funds that are locked in potentially winning bets. uint public lockedInBets; uint public lockedTokenInBets; bytes32 bitComparisonMask = 0xF; //Standard contract ownership transfer. address public owner; address private nextOwner; address public manager; address private nextManager; //The address corresponding to a private key used to sign placeBet commits. address public secretSigner; address public ERC20ContractAddres; address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //Single bet. struct Bet { //Amount in wei. uint amount; //place tx Block number. uint40 placeBlockNumber; // Address of a gambler. address gambler; } //Mapping from commits mapping (uint => Bet) public bets; //Withdrawal mode data. uint32[] public withdrawalMode; // Events that are issued to make statistic recovery easier. event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime); //Admin Payment event ToManagerPayment(address indexed beneficiary, uint amount); event ToManagerFailedPayment(address indexed beneficiary, uint amount); event ToOwnerPayment(address indexed beneficiary, uint amount); event ToOwnerFailedPayment(address indexed beneficiary, uint amount); //Bet Payment event Payment(address indexed beneficiary, uint amount); event FailedPayment(address indexed beneficiary, uint amount); event TokenPayment(address indexed beneficiary, uint amount); //JACKPOT event JackpotBouns(address indexed beneficiary, uint amount); event TokenJackpotBouns(address indexed beneficiary, uint amount); //Play0x_LottoBall_Event event BetRelatedData( address indexed player, uint playerBetAmount, uint playerGetAmount, bytes32 entropy, bytes32 entropy2, uint8 Uplimit, uint8 rotateTime ); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; manager = DUMMY_ADDRESS; secretSigner = DUMMY_ADDRESS; ERC20ContractAddres = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner); _; } modifier onlyManager { require (msg.sender == manager); _; } modifier onlyOwnerManager { require (msg.sender == owner || msg.sender == manager); _; } modifier onlySigner { require (msg.sender == secretSigner); _; } //Init Parameter. function initialParameter(address _manager,address _secretSigner,address _erc20tokenAddress ,uint _MIN_BET,uint _MAX_BET,uint _maxProfit,uint _maxTokenProfit, uint _MAX_AMOUNT, uint8 _platformFeePercentage,uint8 _jackpotFeePercentage,uint8 _ERC20rewardMultiple,uint32[] _withdrawalMode)external onlyOwner{ manager = _manager; secretSigner = _secretSigner; ERC20ContractAddres = _erc20tokenAddress; MIN_BET = _MIN_BET; MAX_BET = _MAX_BET; maxProfit = _maxProfit; maxTokenProfit = _maxTokenProfit; MAX_AMOUNT = _MAX_AMOUNT; platformFeePercentage = _platformFeePercentage; jackpotFeePercentage = _jackpotFeePercentage; ERC20rewardMultiple = _ERC20rewardMultiple; withdrawalMode = _withdrawalMode; } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) external onlyOwner { require (_nextOwner != owner); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner); owner = nextOwner; } // Standard contract ownership transfer implementation, function approveNextManager(address _nextManager) external onlyManager { require (_nextManager != manager); nextManager = _nextManager; } function acceptNextManager() external { require (msg.sender == nextManager); manager = nextManager; } // Fallback function deliberately left empty. function () public payable { } //Set signer. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } //Set tokenAddress. function setTokenAddress(address _tokenAddress) external onlyManager { ERC20ContractAddres = _tokenAddress; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT); maxProfit = _maxProfit; } // Funds withdrawal. function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance); uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount); safetyAmount = safetyAmount.add(withdrawAmount); require (safetyAmount <= address(this).balance); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Token withdrawal. function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this))); uint safetyAmount = tokenJackpotSize.add(lockedTokenInBets); safetyAmount = safetyAmount.add(withdrawAmount); require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this))); ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount); emit TokenPayment(beneficiary, withdrawAmount); } //Recovery of funds function withdrawAllFunds(address beneficiary) external onlyOwner { if (beneficiary.send(address(this).balance)) { lockedInBets = 0; emit Payment(beneficiary, address(this).balance); } else { emit FailedPayment(beneficiary, address(this).balance); } } //Recovery of Token funds function withdrawAlltokenFunds(address beneficiary) external onlyOwner { ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this))); lockedTokenInBets = 0; emit TokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this))); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require (lockedInBets == 0); require (lockedTokenInBets == 0); selfdestruct(owner); } function getContractInformation()public view returns( uint _jackpotSize, uint _tokenJackpotSize, uint _MIN_BET, uint _MAX_BET, uint _MAX_AMOUNT, uint8 _platformFeePercentage, uint8 _jackpotFeePercentage, uint _maxProfit, uint _maxTokenProfit, uint _lockedInBets, uint _lockedTokenInBets, uint32[] _withdrawalMode){ _jackpotSize = jackpotSize; _tokenJackpotSize = tokenJackpotSize; _MIN_BET = MIN_BET; _MAX_BET = MAX_BET; _MAX_AMOUNT = MAX_AMOUNT; _platformFeePercentage = platformFeePercentage; _jackpotFeePercentage = jackpotFeePercentage; _maxProfit = maxProfit; _maxTokenProfit = maxTokenProfit; _lockedInBets = lockedInBets; _lockedTokenInBets = lockedTokenInBets; _withdrawalMode = withdrawalMode; } function getContractAddress()public view returns( address _owner, address _manager, address _secretSigner, address _ERC20ContractAddres ){ _owner = owner; _manager= manager; _secretSigner = secretSigner; _ERC20ContractAddres = ERC20ContractAddres; } // Settlement transaction enum PlaceParam { RotateTime, possibleWinAmount } //Bet by ether: Commits are signed with a block limit to ensure that they are used at most once. function placeBet(uint[] placParameter, bytes32 _signatureHash , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint8 v) external payable { require (uint8(placParameter[uint8(PlaceParam.RotateTime)]) != 0); require (block.number <= _commitLastBlock ); require (secretSigner == ecrecover(_signatureHash, v, r, s)); // Check that the bet is in 'clean' state. Bet storage bet = bets[_commit]; require (bet.gambler == address(0)); //Ether balanceet lockedInBets = lockedInBets.add(uint(placParameter[uint8(PlaceParam.possibleWinAmount)])); require (uint(placParameter[uint8(PlaceParam.possibleWinAmount)]) <= msg.value.add(maxProfit)); require (lockedInBets <= address(this).balance); // Store bet parameters on blockchain. bet.amount = msg.value; bet.placeBlockNumber = uint40(block.number); bet.gambler = msg.sender; emit PlaceBetLog(msg.sender, msg.value, uint8(placParameter[uint8(PlaceParam.RotateTime)])); } function placeTokenBet(uint[] placParameter,bytes32 _signatureHash , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint8 v,uint _amount,address _playerAddress) external { require (placParameter[uint8(PlaceParam.RotateTime)] != 0); require (block.number <= _commitLastBlock ); require (secretSigner == ecrecover(_signatureHash, v, r, s)); // Check that the bet is in 'clean' state. Bet storage bet = bets[_commit]; require (bet.gambler == address(0)); //Token bet lockedTokenInBets = lockedTokenInBets.add(uint(placParameter[uint8(PlaceParam.possibleWinAmount)])); require (uint(placParameter[uint8(PlaceParam.possibleWinAmount)]) <= _amount.add(maxTokenProfit)); require (lockedTokenInBets <= ERC20(ERC20ContractAddres).balanceOf(address(this))); // Store bet parameters on blockchain. bet.amount = _amount; bet.placeBlockNumber = uint40(block.number); bet.gambler = _playerAddress; emit PlaceBetLog(_playerAddress, _amount, uint8(placParameter[uint8(PlaceParam.RotateTime)])); } //Estimated maximum award amount function getBonusPercentageByMachineMode(uint8 machineMode)public view returns( uint upperLimit,uint maxWithdrawalPercentage ){ uint limitIndex = machineMode.mul(2); upperLimit = withdrawalMode[limitIndex]; maxWithdrawalPercentage = withdrawalMode[(limitIndex.add(1))]; } // Settlement transaction enum SettleParam { Uplimit, BonusPercentage, RotateTime, CurrencyType, MachineMode, PerWinAmount, PerBetAmount, PossibleWinAmount, LuckySeed, jackpotFee } function settleBet(uint[] combinationParameter, uint reveal) external { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); // Fetch bet parameters into local variables (to save gas). Bet storage bet = bets[commit]; // Check that bet is in 'active' state and check that bet has not expired yet. require (bet.amount != 0); require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks)); //The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256. bytes32 _entropy = keccak256( abi.encodePacked( uint( keccak256( abi.encodePacked( uint( keccak256( abi.encodePacked( reveal, blockhash(combinationParameter[uint8(SettleParam.LuckySeed)]) ) ) ), blockhash(block.number) ) ) ), blockhash(block.timestamp) ) ); uint totalAmount = 0; uint totalTokenAmount = 0; uint totalJackpotWin = 0; (totalAmount,totalTokenAmount,totalJackpotWin) = runRotateTime(combinationParameter,_entropy,keccak256(abi.encodePacked(uint(_entropy), blockhash(combinationParameter[uint8(SettleParam.LuckySeed)])))); // Add ether JackpotBouns if (totalJackpotWin > 0 && combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { emit JackpotBouns(bet.gambler,totalJackpotWin); totalAmount = totalAmount.add(totalJackpotWin); jackpotSize = uint128(jackpotSize.sub(totalJackpotWin)); }else if (totalJackpotWin > 0 && combinationParameter[uint8(SettleParam.CurrencyType)] == 1) { // Add token TokenJackpotBouns emit TokenJackpotBouns(bet.gambler,totalJackpotWin); totalAmount = totalAmount.add(totalJackpotWin); tokenJackpotSize = uint128(tokenJackpotSize.sub(totalJackpotWin)); } emit BetRelatedData(bet.gambler,bet.amount,totalAmount,_entropy,keccak256(abi.encodePacked(uint(_entropy), blockhash(combinationParameter[uint8(SettleParam.LuckySeed)]))),uint8(combinationParameter[uint8(SettleParam.Uplimit)]),uint8(combinationParameter[uint8(SettleParam.RotateTime)])); if (combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { //Ether game if (totalAmount != 0){ sendFunds(bet.gambler, totalAmount , totalAmount); } //Send ERC20 Token if (totalTokenAmount != 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount); emit TokenPayment(bet.gambler, totalTokenAmount); } } }else if(combinationParameter[uint8(SettleParam.CurrencyType)] == 1){ //ERC20 game //Send ERC20 Token if (totalAmount != 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount); emit TokenPayment(bet.gambler, totalAmount); } } } // Unlock the bet amount, regardless of the outcome. if (combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { lockedInBets = lockedInBets.sub(combinationParameter[uint8(SettleParam.PossibleWinAmount)]); } else if (combinationParameter[uint8(SettleParam.CurrencyType)] == 1){ lockedTokenInBets = lockedTokenInBets.sub(combinationParameter[uint8(SettleParam.PossibleWinAmount)]); } //Move bet into 'processed' state already. bet.amount = 0; //Save jackpotSize if (uint16(combinationParameter[uint8(SettleParam.CurrencyType)]) == 0) { jackpotSize = jackpotSize.add(uint(combinationParameter[uint8(SettleParam.jackpotFee)])); }else if (uint16(combinationParameter[uint8(SettleParam.CurrencyType)]) == 1) { tokenJackpotSize = tokenJackpotSize.add(uint(combinationParameter[uint8(SettleParam.jackpotFee)])); } } function runRotateTime ( uint[] combinationParameter, bytes32 _entropy ,bytes32 _entropy2)private view returns(uint totalAmount,uint totalTokenAmount,uint totalJackpotWin) { bytes32 resultMask = 0xF000000000000000000000000000000000000000000000000000000000000000; bytes32 tmp_entropy; bytes32 tmp_Mask = resultMask; bool isGetJackpot = false; for (uint8 i = 0; i < combinationParameter[uint8(SettleParam.RotateTime)]; i++) { if (i < 64){ tmp_entropy = _entropy & tmp_Mask; tmp_entropy = tmp_entropy >> (4*(64 - (i.add(1)))); tmp_Mask = tmp_Mask >> 4; }else{ if ( i == 64){ tmp_Mask = resultMask; } tmp_entropy = _entropy2 & tmp_Mask; tmp_entropy = tmp_entropy >> (4*( 64 - (i%63))); tmp_Mask = tmp_Mask >> 4; } if ( uint(tmp_entropy) < uint(combinationParameter[uint8(SettleParam.Uplimit)]) ){ //bet win totalAmount = totalAmount.add(combinationParameter[uint8(SettleParam.PerWinAmount)]); //Platform fee determination:Ether Game Winning players must pay platform fees uint platformFees = combinationParameter[uint8(SettleParam.PerBetAmount)].mul(platformFeePercentage); platformFees = platformFees.div(1000); totalAmount = totalAmount.sub(platformFees); }else{ //bet lose if (uint(combinationParameter[uint8(SettleParam.CurrencyType)]) == 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ //get token reward uint rewardAmount = uint(combinationParameter[uint8(SettleParam.PerBetAmount)]).mul(ERC20rewardMultiple); totalTokenAmount = totalTokenAmount.add(rewardAmount); } } } //Get jackpotWin Result if (isGetJackpot == false){ isGetJackpot = getJackpotWinBonus(i,_entropy,_entropy2); } } if (isGetJackpot == true && combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { //gambler get ether bonus. totalJackpotWin = jackpotSize; }else if (isGetJackpot == true && combinationParameter[uint8(SettleParam.CurrencyType)] == 1) { //gambler get token bonus. totalJackpotWin = tokenJackpotSize; } } function getJackpotWinBonus (uint8 i,bytes32 entropy,bytes32 entropy2) private pure returns (bool isGetJackpot) { bytes32 one; bytes32 two; bytes32 three; bytes32 four; bytes32 resultMask = 0xF000000000000000000000000000000000000000000000000000000000000000; bytes32 jackpo_Mask = resultMask; if (i < 61){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); jackpo_Mask = jackpo_Mask >> 4; two = (entropy & jackpo_Mask) >> (4*(64 - (i + 2))); jackpo_Mask = jackpo_Mask >> 4; three = (entropy & jackpo_Mask) >> (4*(64 - (i + 3))); jackpo_Mask = jackpo_Mask >> 4; four = (entropy & jackpo_Mask) >> (4*(64 - (i + 4))); jackpo_Mask = jackpo_Mask << 8; } else if(i >= 61){ if(i == 61){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); jackpo_Mask = jackpo_Mask >> 4; two = (entropy & jackpo_Mask) >> (4*(64 - (i + 2))); jackpo_Mask = jackpo_Mask >> 4; three = (entropy & jackpo_Mask) >> (4*(64 - (i + 3))); jackpo_Mask = jackpo_Mask << 4; four = (entropy2 & 0xF000000000000000000000000000000000000000000000000000000000000000) >> 4*63; } else if(i == 62){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); jackpo_Mask = jackpo_Mask >> 4; two = (entropy & jackpo_Mask) >> (4*(64 - (i + 2))); three = (entropy2 & 0xF000000000000000000000000000000000000000000000000000000000000000) >> 4*63; four = (entropy2 & 0x0F00000000000000000000000000000000000000000000000000000000000000) >> 4*62; } else if(i == 63){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); two = (entropy2 & 0xF000000000000000000000000000000000000000000000000000000000000000) >> 4*63; jackpo_Mask = jackpo_Mask >> 4; three = (entropy2 & 0x0F00000000000000000000000000000000000000000000000000000000000000) >> 4*62; jackpo_Mask = jackpo_Mask << 4; four = (entropy2 & 0x00F0000000000000000000000000000000000000000000000000000000000000) >> 4*61; jackpo_Mask = 0xF000000000000000000000000000000000000000000000000000000000000000; } else { one = (entropy2 & jackpo_Mask) >> (4*( 64 - (i%64 + 1))); jackpo_Mask = jackpo_Mask >> 4; two = (entropy2 & jackpo_Mask) >> (4*( 64 - (i%64 + 2))) ; jackpo_Mask = jackpo_Mask >> 4; three = (entropy2 & jackpo_Mask) >> (4*( 64 - (i%64 + 3))) ; jackpo_Mask = jackpo_Mask >> 4; four = (entropy2 & jackpo_Mask) >>(4*( 64 - (i%64 + 4))); jackpo_Mask = jackpo_Mask << 8; } } if ((one ^ 0xF) == 0 && (two ^ 0xF) == 0 && (three ^ 0xF) == 0 && (four ^ 0xF) == 0){ isGetJackpot = true; } } //Get deductedBalance function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) { //Platform Fee uint prePlatformFee = (senderValue).mul(platformFeePercentage); platformFee = (prePlatformFee).div(1000); //Get jackpotFee uint preJackpotFee = (senderValue).mul(jackpotFeePercentage); jackpotFee = (preJackpotFee).div(1000); //Win Amount uint preUserGetAmount = senderValue.mul(bonusPercentage); possibleWinAmount = preUserGetAmount.div(10000); } // Refund transaction function refundBet(uint commit,uint8 machineMode) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks)); // Move bet into 'processed' state, release funds. bet.amount = 0; //Maximum amount to be confirmed uint platformFee; uint jackpotFee; uint possibleWinAmount; uint upperLimit; uint maxWithdrawalPercentage; (upperLimit,maxWithdrawalPercentage) = getBonusPercentageByMachineMode(machineMode); (platformFee, jackpotFee, possibleWinAmount) = getPossibleWinAmount(maxWithdrawalPercentage,amount); //Amount unlock lockedInBets = lockedInBets.sub(possibleWinAmount); //Refund sendFunds(bet.gambler, amount, amount); } function refundTokenBet(uint commit,uint8 machineMode) external {<FILL_FUNCTION_BODY> } // A helper routine to bulk clean the storage. function clearStorage(uint[] cleanCommits) external { uint length = cleanCommits.length; for (uint i = 0; i < length; i++) { clearProcessedBet(cleanCommits[i]); } } // Helper routine to move 'processed' bets into 'clean' state. function clearProcessedBet(uint commit) private { Bet storage bet = bets[commit]; // Do not overwrite active bets with zeros if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) { return; } // Zero out the remaining storage bet.placeBlockNumber = 0; bet.gambler = address(0); } // Helper routine to process the payment. function sendFunds(address beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } function sendFundsToManager(uint amount) external onlyOwner { if (manager.send(amount)) { emit ToManagerPayment(manager, amount); } else { emit ToManagerFailedPayment(manager, amount); } } function sendTokenFundsToManager( uint amount) external onlyOwner { ERC20(ERC20ContractAddres).transfer(manager, amount); emit TokenPayment(manager, amount); } function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner { if (beneficiary.send(amount)) { emit ToOwnerPayment(beneficiary, amount); } else { emit ToOwnerFailedPayment(beneficiary, amount); } } //Update function updateMIN_BET(uint _uintNumber)public onlyManager { MIN_BET = _uintNumber; } function updateMAX_BET(uint _uintNumber)public onlyManager { MAX_BET = _uintNumber; } function updateMAX_AMOUNT(uint _uintNumber)public onlyManager { MAX_AMOUNT = _uintNumber; } function updateWithdrawalModeByIndex(uint8 _index, uint32 _value) public onlyManager{ withdrawalMode[_index] = _value; } function updateWithdrawalMode( uint32[] _withdrawalMode) public onlyManager{ withdrawalMode = _withdrawalMode; } function updateBitComparisonMask(bytes32 _newBitComparisonMask ) public onlyOwner{ bitComparisonMask = _newBitComparisonMask; } function updatePlatformFeePercentage(uint8 _platformFeePercentage ) public onlyOwner{ platformFeePercentage = _platformFeePercentage; } function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) public onlyOwner{ jackpotFeePercentage = _jackpotFeePercentage; } function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) public onlyManager{ ERC20rewardMultiple = _ERC20rewardMultiple; } }
contract Play0x_LottoBall { using SafeMath for uint256; using SafeMath for uint128; using SafeMath for uint40; using SafeMath for uint8; uint public jackpotSize; uint public tokenJackpotSize; uint public MIN_BET; uint public MAX_BET; uint public MAX_AMOUNT; //Adjustable max bet profit. uint public maxProfit; uint public maxTokenProfit; //Fee percentage uint8 public platformFeePercentage = 15; uint8 public jackpotFeePercentage = 5; uint8 public ERC20rewardMultiple = 5; //Bets can be refunded via invoking refundBet. uint constant BetExpirationBlocks = 250; //Funds that are locked in potentially winning bets. uint public lockedInBets; uint public lockedTokenInBets; bytes32 bitComparisonMask = 0xF; //Standard contract ownership transfer. address public owner; address private nextOwner; address public manager; address private nextManager; //The address corresponding to a private key used to sign placeBet commits. address public secretSigner; address public ERC20ContractAddres; address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //Single bet. struct Bet { //Amount in wei. uint amount; //place tx Block number. uint40 placeBlockNumber; // Address of a gambler. address gambler; } //Mapping from commits mapping (uint => Bet) public bets; //Withdrawal mode data. uint32[] public withdrawalMode; // Events that are issued to make statistic recovery easier. event PlaceBetLog(address indexed player, uint amount,uint8 rotateTime); //Admin Payment event ToManagerPayment(address indexed beneficiary, uint amount); event ToManagerFailedPayment(address indexed beneficiary, uint amount); event ToOwnerPayment(address indexed beneficiary, uint amount); event ToOwnerFailedPayment(address indexed beneficiary, uint amount); //Bet Payment event Payment(address indexed beneficiary, uint amount); event FailedPayment(address indexed beneficiary, uint amount); event TokenPayment(address indexed beneficiary, uint amount); //JACKPOT event JackpotBouns(address indexed beneficiary, uint amount); event TokenJackpotBouns(address indexed beneficiary, uint amount); //Play0x_LottoBall_Event event BetRelatedData( address indexed player, uint playerBetAmount, uint playerGetAmount, bytes32 entropy, bytes32 entropy2, uint8 Uplimit, uint8 rotateTime ); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; manager = DUMMY_ADDRESS; secretSigner = DUMMY_ADDRESS; ERC20ContractAddres = DUMMY_ADDRESS; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner); _; } modifier onlyManager { require (msg.sender == manager); _; } modifier onlyOwnerManager { require (msg.sender == owner || msg.sender == manager); _; } modifier onlySigner { require (msg.sender == secretSigner); _; } //Init Parameter. function initialParameter(address _manager,address _secretSigner,address _erc20tokenAddress ,uint _MIN_BET,uint _MAX_BET,uint _maxProfit,uint _maxTokenProfit, uint _MAX_AMOUNT, uint8 _platformFeePercentage,uint8 _jackpotFeePercentage,uint8 _ERC20rewardMultiple,uint32[] _withdrawalMode)external onlyOwner{ manager = _manager; secretSigner = _secretSigner; ERC20ContractAddres = _erc20tokenAddress; MIN_BET = _MIN_BET; MAX_BET = _MAX_BET; maxProfit = _maxProfit; maxTokenProfit = _maxTokenProfit; MAX_AMOUNT = _MAX_AMOUNT; platformFeePercentage = _platformFeePercentage; jackpotFeePercentage = _jackpotFeePercentage; ERC20rewardMultiple = _ERC20rewardMultiple; withdrawalMode = _withdrawalMode; } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) external onlyOwner { require (_nextOwner != owner); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner); owner = nextOwner; } // Standard contract ownership transfer implementation, function approveNextManager(address _nextManager) external onlyManager { require (_nextManager != manager); nextManager = _nextManager; } function acceptNextManager() external { require (msg.sender == nextManager); manager = nextManager; } // Fallback function deliberately left empty. function () public payable { } //Set signer. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } //Set tokenAddress. function setTokenAddress(address _tokenAddress) external onlyManager { ERC20ContractAddres = _tokenAddress; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT); maxProfit = _maxProfit; } // Funds withdrawal. function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance); uint safetyAmount = jackpotSize.add(lockedInBets).add(withdrawAmount); safetyAmount = safetyAmount.add(withdrawAmount); require (safetyAmount <= address(this).balance); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Token withdrawal. function withdrawToken(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this))); uint safetyAmount = tokenJackpotSize.add(lockedTokenInBets); safetyAmount = safetyAmount.add(withdrawAmount); require (safetyAmount <= ERC20(ERC20ContractAddres).balanceOf(address(this))); ERC20(ERC20ContractAddres).transfer(beneficiary, withdrawAmount); emit TokenPayment(beneficiary, withdrawAmount); } //Recovery of funds function withdrawAllFunds(address beneficiary) external onlyOwner { if (beneficiary.send(address(this).balance)) { lockedInBets = 0; emit Payment(beneficiary, address(this).balance); } else { emit FailedPayment(beneficiary, address(this).balance); } } //Recovery of Token funds function withdrawAlltokenFunds(address beneficiary) external onlyOwner { ERC20(ERC20ContractAddres).transfer(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this))); lockedTokenInBets = 0; emit TokenPayment(beneficiary, ERC20(ERC20ContractAddres).balanceOf(address(this))); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require (lockedInBets == 0); require (lockedTokenInBets == 0); selfdestruct(owner); } function getContractInformation()public view returns( uint _jackpotSize, uint _tokenJackpotSize, uint _MIN_BET, uint _MAX_BET, uint _MAX_AMOUNT, uint8 _platformFeePercentage, uint8 _jackpotFeePercentage, uint _maxProfit, uint _maxTokenProfit, uint _lockedInBets, uint _lockedTokenInBets, uint32[] _withdrawalMode){ _jackpotSize = jackpotSize; _tokenJackpotSize = tokenJackpotSize; _MIN_BET = MIN_BET; _MAX_BET = MAX_BET; _MAX_AMOUNT = MAX_AMOUNT; _platformFeePercentage = platformFeePercentage; _jackpotFeePercentage = jackpotFeePercentage; _maxProfit = maxProfit; _maxTokenProfit = maxTokenProfit; _lockedInBets = lockedInBets; _lockedTokenInBets = lockedTokenInBets; _withdrawalMode = withdrawalMode; } function getContractAddress()public view returns( address _owner, address _manager, address _secretSigner, address _ERC20ContractAddres ){ _owner = owner; _manager= manager; _secretSigner = secretSigner; _ERC20ContractAddres = ERC20ContractAddres; } // Settlement transaction enum PlaceParam { RotateTime, possibleWinAmount } //Bet by ether: Commits are signed with a block limit to ensure that they are used at most once. function placeBet(uint[] placParameter, bytes32 _signatureHash , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint8 v) external payable { require (uint8(placParameter[uint8(PlaceParam.RotateTime)]) != 0); require (block.number <= _commitLastBlock ); require (secretSigner == ecrecover(_signatureHash, v, r, s)); // Check that the bet is in 'clean' state. Bet storage bet = bets[_commit]; require (bet.gambler == address(0)); //Ether balanceet lockedInBets = lockedInBets.add(uint(placParameter[uint8(PlaceParam.possibleWinAmount)])); require (uint(placParameter[uint8(PlaceParam.possibleWinAmount)]) <= msg.value.add(maxProfit)); require (lockedInBets <= address(this).balance); // Store bet parameters on blockchain. bet.amount = msg.value; bet.placeBlockNumber = uint40(block.number); bet.gambler = msg.sender; emit PlaceBetLog(msg.sender, msg.value, uint8(placParameter[uint8(PlaceParam.RotateTime)])); } function placeTokenBet(uint[] placParameter,bytes32 _signatureHash , uint _commitLastBlock, uint _commit, bytes32 r, bytes32 s, uint8 v,uint _amount,address _playerAddress) external { require (placParameter[uint8(PlaceParam.RotateTime)] != 0); require (block.number <= _commitLastBlock ); require (secretSigner == ecrecover(_signatureHash, v, r, s)); // Check that the bet is in 'clean' state. Bet storage bet = bets[_commit]; require (bet.gambler == address(0)); //Token bet lockedTokenInBets = lockedTokenInBets.add(uint(placParameter[uint8(PlaceParam.possibleWinAmount)])); require (uint(placParameter[uint8(PlaceParam.possibleWinAmount)]) <= _amount.add(maxTokenProfit)); require (lockedTokenInBets <= ERC20(ERC20ContractAddres).balanceOf(address(this))); // Store bet parameters on blockchain. bet.amount = _amount; bet.placeBlockNumber = uint40(block.number); bet.gambler = _playerAddress; emit PlaceBetLog(_playerAddress, _amount, uint8(placParameter[uint8(PlaceParam.RotateTime)])); } //Estimated maximum award amount function getBonusPercentageByMachineMode(uint8 machineMode)public view returns( uint upperLimit,uint maxWithdrawalPercentage ){ uint limitIndex = machineMode.mul(2); upperLimit = withdrawalMode[limitIndex]; maxWithdrawalPercentage = withdrawalMode[(limitIndex.add(1))]; } // Settlement transaction enum SettleParam { Uplimit, BonusPercentage, RotateTime, CurrencyType, MachineMode, PerWinAmount, PerBetAmount, PossibleWinAmount, LuckySeed, jackpotFee } function settleBet(uint[] combinationParameter, uint reveal) external { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); // Fetch bet parameters into local variables (to save gas). Bet storage bet = bets[commit]; // Check that bet is in 'active' state and check that bet has not expired yet. require (bet.amount != 0); require (block.number <= bet.placeBlockNumber.add(BetExpirationBlocks)); //The RNG - combine "reveal" and blockhash of LuckySeed using Keccak256. bytes32 _entropy = keccak256( abi.encodePacked( uint( keccak256( abi.encodePacked( uint( keccak256( abi.encodePacked( reveal, blockhash(combinationParameter[uint8(SettleParam.LuckySeed)]) ) ) ), blockhash(block.number) ) ) ), blockhash(block.timestamp) ) ); uint totalAmount = 0; uint totalTokenAmount = 0; uint totalJackpotWin = 0; (totalAmount,totalTokenAmount,totalJackpotWin) = runRotateTime(combinationParameter,_entropy,keccak256(abi.encodePacked(uint(_entropy), blockhash(combinationParameter[uint8(SettleParam.LuckySeed)])))); // Add ether JackpotBouns if (totalJackpotWin > 0 && combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { emit JackpotBouns(bet.gambler,totalJackpotWin); totalAmount = totalAmount.add(totalJackpotWin); jackpotSize = uint128(jackpotSize.sub(totalJackpotWin)); }else if (totalJackpotWin > 0 && combinationParameter[uint8(SettleParam.CurrencyType)] == 1) { // Add token TokenJackpotBouns emit TokenJackpotBouns(bet.gambler,totalJackpotWin); totalAmount = totalAmount.add(totalJackpotWin); tokenJackpotSize = uint128(tokenJackpotSize.sub(totalJackpotWin)); } emit BetRelatedData(bet.gambler,bet.amount,totalAmount,_entropy,keccak256(abi.encodePacked(uint(_entropy), blockhash(combinationParameter[uint8(SettleParam.LuckySeed)]))),uint8(combinationParameter[uint8(SettleParam.Uplimit)]),uint8(combinationParameter[uint8(SettleParam.RotateTime)])); if (combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { //Ether game if (totalAmount != 0){ sendFunds(bet.gambler, totalAmount , totalAmount); } //Send ERC20 Token if (totalTokenAmount != 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ ERC20(ERC20ContractAddres).transfer(bet.gambler, totalTokenAmount); emit TokenPayment(bet.gambler, totalTokenAmount); } } }else if(combinationParameter[uint8(SettleParam.CurrencyType)] == 1){ //ERC20 game //Send ERC20 Token if (totalAmount != 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ ERC20(ERC20ContractAddres).transfer(bet.gambler, totalAmount); emit TokenPayment(bet.gambler, totalAmount); } } } // Unlock the bet amount, regardless of the outcome. if (combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { lockedInBets = lockedInBets.sub(combinationParameter[uint8(SettleParam.PossibleWinAmount)]); } else if (combinationParameter[uint8(SettleParam.CurrencyType)] == 1){ lockedTokenInBets = lockedTokenInBets.sub(combinationParameter[uint8(SettleParam.PossibleWinAmount)]); } //Move bet into 'processed' state already. bet.amount = 0; //Save jackpotSize if (uint16(combinationParameter[uint8(SettleParam.CurrencyType)]) == 0) { jackpotSize = jackpotSize.add(uint(combinationParameter[uint8(SettleParam.jackpotFee)])); }else if (uint16(combinationParameter[uint8(SettleParam.CurrencyType)]) == 1) { tokenJackpotSize = tokenJackpotSize.add(uint(combinationParameter[uint8(SettleParam.jackpotFee)])); } } function runRotateTime ( uint[] combinationParameter, bytes32 _entropy ,bytes32 _entropy2)private view returns(uint totalAmount,uint totalTokenAmount,uint totalJackpotWin) { bytes32 resultMask = 0xF000000000000000000000000000000000000000000000000000000000000000; bytes32 tmp_entropy; bytes32 tmp_Mask = resultMask; bool isGetJackpot = false; for (uint8 i = 0; i < combinationParameter[uint8(SettleParam.RotateTime)]; i++) { if (i < 64){ tmp_entropy = _entropy & tmp_Mask; tmp_entropy = tmp_entropy >> (4*(64 - (i.add(1)))); tmp_Mask = tmp_Mask >> 4; }else{ if ( i == 64){ tmp_Mask = resultMask; } tmp_entropy = _entropy2 & tmp_Mask; tmp_entropy = tmp_entropy >> (4*( 64 - (i%63))); tmp_Mask = tmp_Mask >> 4; } if ( uint(tmp_entropy) < uint(combinationParameter[uint8(SettleParam.Uplimit)]) ){ //bet win totalAmount = totalAmount.add(combinationParameter[uint8(SettleParam.PerWinAmount)]); //Platform fee determination:Ether Game Winning players must pay platform fees uint platformFees = combinationParameter[uint8(SettleParam.PerBetAmount)].mul(platformFeePercentage); platformFees = platformFees.div(1000); totalAmount = totalAmount.sub(platformFees); }else{ //bet lose if (uint(combinationParameter[uint8(SettleParam.CurrencyType)]) == 0){ if(ERC20(ERC20ContractAddres).balanceOf(address(this)) > 0){ //get token reward uint rewardAmount = uint(combinationParameter[uint8(SettleParam.PerBetAmount)]).mul(ERC20rewardMultiple); totalTokenAmount = totalTokenAmount.add(rewardAmount); } } } //Get jackpotWin Result if (isGetJackpot == false){ isGetJackpot = getJackpotWinBonus(i,_entropy,_entropy2); } } if (isGetJackpot == true && combinationParameter[uint8(SettleParam.CurrencyType)] == 0) { //gambler get ether bonus. totalJackpotWin = jackpotSize; }else if (isGetJackpot == true && combinationParameter[uint8(SettleParam.CurrencyType)] == 1) { //gambler get token bonus. totalJackpotWin = tokenJackpotSize; } } function getJackpotWinBonus (uint8 i,bytes32 entropy,bytes32 entropy2) private pure returns (bool isGetJackpot) { bytes32 one; bytes32 two; bytes32 three; bytes32 four; bytes32 resultMask = 0xF000000000000000000000000000000000000000000000000000000000000000; bytes32 jackpo_Mask = resultMask; if (i < 61){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); jackpo_Mask = jackpo_Mask >> 4; two = (entropy & jackpo_Mask) >> (4*(64 - (i + 2))); jackpo_Mask = jackpo_Mask >> 4; three = (entropy & jackpo_Mask) >> (4*(64 - (i + 3))); jackpo_Mask = jackpo_Mask >> 4; four = (entropy & jackpo_Mask) >> (4*(64 - (i + 4))); jackpo_Mask = jackpo_Mask << 8; } else if(i >= 61){ if(i == 61){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); jackpo_Mask = jackpo_Mask >> 4; two = (entropy & jackpo_Mask) >> (4*(64 - (i + 2))); jackpo_Mask = jackpo_Mask >> 4; three = (entropy & jackpo_Mask) >> (4*(64 - (i + 3))); jackpo_Mask = jackpo_Mask << 4; four = (entropy2 & 0xF000000000000000000000000000000000000000000000000000000000000000) >> 4*63; } else if(i == 62){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); jackpo_Mask = jackpo_Mask >> 4; two = (entropy & jackpo_Mask) >> (4*(64 - (i + 2))); three = (entropy2 & 0xF000000000000000000000000000000000000000000000000000000000000000) >> 4*63; four = (entropy2 & 0x0F00000000000000000000000000000000000000000000000000000000000000) >> 4*62; } else if(i == 63){ one = (entropy & jackpo_Mask) >> 4*(64 - (i + 1)); two = (entropy2 & 0xF000000000000000000000000000000000000000000000000000000000000000) >> 4*63; jackpo_Mask = jackpo_Mask >> 4; three = (entropy2 & 0x0F00000000000000000000000000000000000000000000000000000000000000) >> 4*62; jackpo_Mask = jackpo_Mask << 4; four = (entropy2 & 0x00F0000000000000000000000000000000000000000000000000000000000000) >> 4*61; jackpo_Mask = 0xF000000000000000000000000000000000000000000000000000000000000000; } else { one = (entropy2 & jackpo_Mask) >> (4*( 64 - (i%64 + 1))); jackpo_Mask = jackpo_Mask >> 4; two = (entropy2 & jackpo_Mask) >> (4*( 64 - (i%64 + 2))) ; jackpo_Mask = jackpo_Mask >> 4; three = (entropy2 & jackpo_Mask) >> (4*( 64 - (i%64 + 3))) ; jackpo_Mask = jackpo_Mask >> 4; four = (entropy2 & jackpo_Mask) >>(4*( 64 - (i%64 + 4))); jackpo_Mask = jackpo_Mask << 8; } } if ((one ^ 0xF) == 0 && (two ^ 0xF) == 0 && (three ^ 0xF) == 0 && (four ^ 0xF) == 0){ isGetJackpot = true; } } //Get deductedBalance function getPossibleWinAmount(uint bonusPercentage,uint senderValue)public view returns (uint platformFee,uint jackpotFee,uint possibleWinAmount) { //Platform Fee uint prePlatformFee = (senderValue).mul(platformFeePercentage); platformFee = (prePlatformFee).div(1000); //Get jackpotFee uint preJackpotFee = (senderValue).mul(jackpotFeePercentage); jackpotFee = (preJackpotFee).div(1000); //Win Amount uint preUserGetAmount = senderValue.mul(bonusPercentage); possibleWinAmount = preUserGetAmount.div(10000); } // Refund transaction function refundBet(uint commit,uint8 machineMode) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks)); // Move bet into 'processed' state, release funds. bet.amount = 0; //Maximum amount to be confirmed uint platformFee; uint jackpotFee; uint possibleWinAmount; uint upperLimit; uint maxWithdrawalPercentage; (upperLimit,maxWithdrawalPercentage) = getBonusPercentageByMachineMode(machineMode); (platformFee, jackpotFee, possibleWinAmount) = getPossibleWinAmount(maxWithdrawalPercentage,amount); //Amount unlock lockedInBets = lockedInBets.sub(possibleWinAmount); //Refund sendFunds(bet.gambler, amount, amount); } <FILL_FUNCTION> // A helper routine to bulk clean the storage. function clearStorage(uint[] cleanCommits) external { uint length = cleanCommits.length; for (uint i = 0; i < length; i++) { clearProcessedBet(cleanCommits[i]); } } // Helper routine to move 'processed' bets into 'clean' state. function clearProcessedBet(uint commit) private { Bet storage bet = bets[commit]; // Do not overwrite active bets with zeros if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BetExpirationBlocks) { return; } // Zero out the remaining storage bet.placeBlockNumber = 0; bet.gambler = address(0); } // Helper routine to process the payment. function sendFunds(address beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } function sendFundsToManager(uint amount) external onlyOwner { if (manager.send(amount)) { emit ToManagerPayment(manager, amount); } else { emit ToManagerFailedPayment(manager, amount); } } function sendTokenFundsToManager( uint amount) external onlyOwner { ERC20(ERC20ContractAddres).transfer(manager, amount); emit TokenPayment(manager, amount); } function sendFundsToOwner(address beneficiary, uint amount) external onlyOwner { if (beneficiary.send(amount)) { emit ToOwnerPayment(beneficiary, amount); } else { emit ToOwnerFailedPayment(beneficiary, amount); } } //Update function updateMIN_BET(uint _uintNumber)public onlyManager { MIN_BET = _uintNumber; } function updateMAX_BET(uint _uintNumber)public onlyManager { MAX_BET = _uintNumber; } function updateMAX_AMOUNT(uint _uintNumber)public onlyManager { MAX_AMOUNT = _uintNumber; } function updateWithdrawalModeByIndex(uint8 _index, uint32 _value) public onlyManager{ withdrawalMode[_index] = _value; } function updateWithdrawalMode( uint32[] _withdrawalMode) public onlyManager{ withdrawalMode = _withdrawalMode; } function updateBitComparisonMask(bytes32 _newBitComparisonMask ) public onlyOwner{ bitComparisonMask = _newBitComparisonMask; } function updatePlatformFeePercentage(uint8 _platformFeePercentage ) public onlyOwner{ platformFeePercentage = _platformFeePercentage; } function updateJackpotFeePercentage(uint8 _jackpotFeePercentage ) public onlyOwner{ jackpotFeePercentage = _jackpotFeePercentage; } function updateERC20rewardMultiple(uint8 _ERC20rewardMultiple ) public onlyManager{ ERC20rewardMultiple = _ERC20rewardMultiple; } }
// Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber.add(BetExpirationBlocks)); // Move bet into 'processed' state, release funds. bet.amount = 0; //Maximum amount to be confirmed uint platformFee; uint jackpotFee; uint possibleWinAmount; uint upperLimit; uint maxWithdrawalPercentage; (upperLimit,maxWithdrawalPercentage) = getBonusPercentageByMachineMode(machineMode); (platformFee, jackpotFee, possibleWinAmount) = getPossibleWinAmount(maxWithdrawalPercentage,amount); //Amount unlock lockedTokenInBets = uint128(lockedTokenInBets.sub(possibleWinAmount)); //Refund ERC20(ERC20ContractAddres).transfer(bet.gambler, amount); emit TokenPayment(bet.gambler, amount);
function refundTokenBet(uint commit,uint8 machineMode) external
function refundTokenBet(uint commit,uint8 machineMode) external
81380
Administered
null
contract Administered { address public creator; mapping (address => bool) public admins; constructor() public {<FILL_FUNCTION_BODY> } modifier onlyOwner { require(creator == msg.sender); _; } modifier onlyAdmin { require(admins[msg.sender] || creator == msg.sender); _; } function grantAdmin(address newAdmin) onlyOwner public { _grantAdmin(newAdmin); } function _grantAdmin(address newAdmin) internal { admins[newAdmin] = true; } function changeOwner(address newOwner) onlyOwner public { creator = newOwner; } function revokeAdminStatus(address user) onlyOwner public { admins[user] = false; } }
contract Administered { address public creator; mapping (address => bool) public admins; <FILL_FUNCTION> modifier onlyOwner { require(creator == msg.sender); _; } modifier onlyAdmin { require(admins[msg.sender] || creator == msg.sender); _; } function grantAdmin(address newAdmin) onlyOwner public { _grantAdmin(newAdmin); } function _grantAdmin(address newAdmin) internal { admins[newAdmin] = true; } function changeOwner(address newOwner) onlyOwner public { creator = newOwner; } function revokeAdminStatus(address user) onlyOwner public { admins[user] = false; } }
creator = msg.sender; admins[creator] = true;
constructor() public
constructor() public
64349
ERC20Impl
decreaseApprovalWithSender
contract ERC20Impl { ERC20Proxy public erc20Proxy; ERC20Store public erc20Store; function ERC20Impl( address _erc20Proxy, address _erc20Store ) public { erc20Proxy = ERC20Proxy(_erc20Proxy); erc20Store = ERC20Store(_erc20Store); } modifier onlyProxy { require(msg.sender == address(erc20Proxy)); _; } modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; } function approveWithSender( address _sender, address _spender, uint256 _value ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals erc20Store.setAllowance(_sender, _spender, _value); erc20Proxy.emitApproval(_sender, _spender, _value); return true; } function increaseApprovalWithSender( address _sender, address _spender, uint256 _addedValue ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance + _addedValue; require(newAllowance >= currentAllowance); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) public onlyProxy returns (bool success) {<FILL_FUNCTION_BODY> } function transferFromWithSender( address _sender, address _from, address _to, uint256 _value ) public onlyProxy onlyPayloadSize(4 * 32) returns (bool success) { require(_to != address(0)); uint256 balanceOfFrom = erc20Store.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = erc20Store.allowed(_from, _sender); require(_value <= senderAllowance); erc20Store.setBalance(_from, balanceOfFrom - _value); erc20Store.addBalance(_to, _value); erc20Store.setAllowance(_from, _sender, senderAllowance - _value); erc20Proxy.emitTransfer(_from, _to, _value); return true; } function transferWithSender( address _sender, address _to, uint256 _value ) public onlyProxy onlyPayloadSize(3 * 32) returns (bool success) { require(_to != address(0)); uint256 balanceOfSender = erc20Store.balances(_sender); require(_value <= balanceOfSender); erc20Store.setBalance(_sender, balanceOfSender - _value); erc20Store.addBalance(_to, _value); erc20Proxy.emitTransfer(_sender, _to, _value); return true; } function totalSupply() public view returns (uint256) { return erc20Store.totalSupply(); } function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Store.balances(_owner); } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Store.allowed(_owner, _spender); } }
contract ERC20Impl { ERC20Proxy public erc20Proxy; ERC20Store public erc20Store; function ERC20Impl( address _erc20Proxy, address _erc20Store ) public { erc20Proxy = ERC20Proxy(_erc20Proxy); erc20Store = ERC20Store(_erc20Store); } modifier onlyProxy { require(msg.sender == address(erc20Proxy)); _; } modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; } function approveWithSender( address _sender, address _spender, uint256 _value ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals erc20Store.setAllowance(_sender, _spender, _value); erc20Proxy.emitApproval(_sender, _spender, _value); return true; } function increaseApprovalWithSender( address _sender, address _spender, uint256 _addedValue ) public onlyProxy returns (bool success) { require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance + _addedValue; require(newAllowance >= currentAllowance); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true; } <FILL_FUNCTION> function transferFromWithSender( address _sender, address _from, address _to, uint256 _value ) public onlyProxy onlyPayloadSize(4 * 32) returns (bool success) { require(_to != address(0)); uint256 balanceOfFrom = erc20Store.balances(_from); require(_value <= balanceOfFrom); uint256 senderAllowance = erc20Store.allowed(_from, _sender); require(_value <= senderAllowance); erc20Store.setBalance(_from, balanceOfFrom - _value); erc20Store.addBalance(_to, _value); erc20Store.setAllowance(_from, _sender, senderAllowance - _value); erc20Proxy.emitTransfer(_from, _to, _value); return true; } function transferWithSender( address _sender, address _to, uint256 _value ) public onlyProxy onlyPayloadSize(3 * 32) returns (bool success) { require(_to != address(0)); uint256 balanceOfSender = erc20Store.balances(_sender); require(_value <= balanceOfSender); erc20Store.setBalance(_sender, balanceOfSender - _value); erc20Store.addBalance(_to, _value); erc20Proxy.emitTransfer(_sender, _to, _value); return true; } function totalSupply() public view returns (uint256) { return erc20Store.totalSupply(); } function balanceOf(address _owner) public view returns (uint256 balance) { return erc20Store.balances(_owner); } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return erc20Store.allowed(_owner, _spender); } }
require(_spender != address(0)); // disallow unspendable approvals uint256 currentAllowance = erc20Store.allowed(_sender, _spender); uint256 newAllowance = currentAllowance - _subtractedValue; require(newAllowance <= currentAllowance); erc20Store.setAllowance(_sender, _spender, newAllowance); erc20Proxy.emitApproval(_sender, _spender, newAllowance); return true;
function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) public onlyProxy returns (bool success)
function decreaseApprovalWithSender( address _sender, address _spender, uint256 _subtractedValue ) public onlyProxy returns (bool success)
24949
Burnamint
isAdmin
contract Burnamint { mapping (address => bool) private admins; mapping (address => mapping (address => uint256)) private burnamintable; address public owner; string private _name; string private _symbol; uint8 private _decimals; event BurnaMint(address indexed _oldToken, address indexed _newToken, address indexed _address, uint256 _oldValue, uint256 newValue); constructor() { owner = msg.sender; admins[msg.sender] = true; } function addAdmin(address _admin) external onlyOwner{ admins[_admin] = true; } function removeAdmin(address _admin) external onlyOwner{ admins[_admin] = false; } function isAdmin(address _admin) external view returns(bool _isAdmin){<FILL_FUNCTION_BODY> } function addBurnamintable(address _oldContractAddress, address _newContractAddress, uint256 _ratio) external onlyAdmin returns (bool success){ require(burnamintable[_oldContractAddress][_newContractAddress] == 0, "Tokens are not burnamintables"); burnamintable[_oldContractAddress][_newContractAddress] = _ratio; return true; } function burnamint(address _oldContractAddress, address _newContractAddress, address _receiver, uint256 _amount) external returns(bool success){ uint256 ratio = burnamintable[_oldContractAddress][_newContractAddress]; require(ratio > 0, "Tokens are not burnamintables"); Token oldToken = Token(_oldContractAddress); require(oldToken.transferFrom(msg.sender, address(this), _amount)); // use safetransfer from (Token(_newContractAddress)).transfer(_receiver, _amount/ratio); emit BurnaMint(_oldContractAddress, _newContractAddress, _receiver, _amount, _amount/ratio); return true; } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } modifier onlyAdmin() { require(admins[msg.sender], "Caller is not the owner"); _; } function withdrawToken(address _token, address _to, uint256 _value) external onlyOwner returns (bool success){ Token(_token).transfer(_to, _value); return true; } function withdraw(address payable _to, uint256 _value) external onlyOwner returns (bool success){ _to.transfer(_value); return true; } function destroy(address payable _to) external onlyOwner { selfdestruct(_to); } }
contract Burnamint { mapping (address => bool) private admins; mapping (address => mapping (address => uint256)) private burnamintable; address public owner; string private _name; string private _symbol; uint8 private _decimals; event BurnaMint(address indexed _oldToken, address indexed _newToken, address indexed _address, uint256 _oldValue, uint256 newValue); constructor() { owner = msg.sender; admins[msg.sender] = true; } function addAdmin(address _admin) external onlyOwner{ admins[_admin] = true; } function removeAdmin(address _admin) external onlyOwner{ admins[_admin] = false; } <FILL_FUNCTION> function addBurnamintable(address _oldContractAddress, address _newContractAddress, uint256 _ratio) external onlyAdmin returns (bool success){ require(burnamintable[_oldContractAddress][_newContractAddress] == 0, "Tokens are not burnamintables"); burnamintable[_oldContractAddress][_newContractAddress] = _ratio; return true; } function burnamint(address _oldContractAddress, address _newContractAddress, address _receiver, uint256 _amount) external returns(bool success){ uint256 ratio = burnamintable[_oldContractAddress][_newContractAddress]; require(ratio > 0, "Tokens are not burnamintables"); Token oldToken = Token(_oldContractAddress); require(oldToken.transferFrom(msg.sender, address(this), _amount)); // use safetransfer from (Token(_newContractAddress)).transfer(_receiver, _amount/ratio); emit BurnaMint(_oldContractAddress, _newContractAddress, _receiver, _amount, _amount/ratio); return true; } modifier onlyOwner() { require(owner == msg.sender, "Caller is not the owner"); _; } modifier onlyAdmin() { require(admins[msg.sender], "Caller is not the owner"); _; } function withdrawToken(address _token, address _to, uint256 _value) external onlyOwner returns (bool success){ Token(_token).transfer(_to, _value); return true; } function withdraw(address payable _to, uint256 _value) external onlyOwner returns (bool success){ _to.transfer(_value); return true; } function destroy(address payable _to) external onlyOwner { selfdestruct(_to); } }
return admins[_admin];
function isAdmin(address _admin) external view returns(bool _isAdmin)
function isAdmin(address _admin) external view returns(bool _isAdmin)
59988
Ownable
setManager
contract Ownable { string public contractName; address public owner; address public manager; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event ManagerChanged(address indexed previousManager, address indexed newManager); constructor() internal { owner = msg.sender; manager = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } modifier onlyManager(bytes32 managerName) { require(msg.sender == manager, "Ownable: caller is not the manager"); _; } function setOwner(address _owner) public onlyOwner { require(_owner != address(0), "Ownable: new owner is the zero address"); emit OwnerChanged(owner, _owner); owner = _owner; } function setManager(address _manager) public onlyOwner {<FILL_FUNCTION_BODY> } function setContractName(bytes32 _contractName) internal { contractName = string(abi.encodePacked(_contractName)); } }
contract Ownable { string public contractName; address public owner; address public manager; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event ManagerChanged(address indexed previousManager, address indexed newManager); constructor() internal { owner = msg.sender; manager = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } modifier onlyManager(bytes32 managerName) { require(msg.sender == manager, "Ownable: caller is not the manager"); _; } function setOwner(address _owner) public onlyOwner { require(_owner != address(0), "Ownable: new owner is the zero address"); emit OwnerChanged(owner, _owner); owner = _owner; } <FILL_FUNCTION> function setContractName(bytes32 _contractName) internal { contractName = string(abi.encodePacked(_contractName)); } }
require(_manager != address(0), "Ownable: new manager is the zero address"); emit ManagerChanged(manager, _manager); manager = _manager;
function setManager(address _manager) public onlyOwner
function setManager(address _manager) public onlyOwner
72032
SAUBAERtoken
SAUBAERtoken
contract SAUBAERtoken { string public constant symbol = "SAUBAER"; string public constant name = "SAUBAER"; uint8 public constant decimals = 1; // Owner of the contract address public owner; // Total supply of tokens uint256 _totalSupply = 100000; // Ledger of the balance of the account mapping (address => uint256) balances; // Owner of account approuves the transfert of an account to another account mapping (address => mapping (address => uint256)) allowed; // Triggered when tokens are transferred event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); // Constructor function SAUBAERtoken() {<FILL_FUNCTION_BODY> } // SEND TOKEN: Transfer amount _value from the addr calling function to address _to function transfer(address _to, uint256 _value) returns (bool success) { // Check if the value is autorized if (balances[msg.sender] >= _value && _value > 0) { // Decrease the sender balance balances[msg.sender] -= _value; // Increase the sender balance balances[_to] += _value; // Trigger the Transfer event Transfer(msg.sender, _to, _value); return true; } else { return false; } } }
contract SAUBAERtoken { string public constant symbol = "SAUBAER"; string public constant name = "SAUBAER"; uint8 public constant decimals = 1; // Owner of the contract address public owner; // Total supply of tokens uint256 _totalSupply = 100000; // Ledger of the balance of the account mapping (address => uint256) balances; // Owner of account approuves the transfert of an account to another account mapping (address => mapping (address => uint256)) allowed; // Triggered when tokens are transferred event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); <FILL_FUNCTION> // SEND TOKEN: Transfer amount _value from the addr calling function to address _to function transfer(address _to, uint256 _value) returns (bool success) { // Check if the value is autorized if (balances[msg.sender] >= _value && _value > 0) { // Decrease the sender balance balances[msg.sender] -= _value; // Increase the sender balance balances[_to] += _value; // Trigger the Transfer event Transfer(msg.sender, _to, _value); return true; } else { return false; } } }
owner = msg.sender; balances[owner] = _totalSupply;
function SAUBAERtoken()
// Constructor function SAUBAERtoken()
81441
Owned
transferOwnership
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = 0x4147A34fbE1df3794F96F9326d6Afc089BACDE49; } modifier onlyOwner { require(msg.sender == owner); _; } // transfer Ownership to other address function transferOwnership(address _newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = 0x4147A34fbE1df3794F96F9326d6Afc089BACDE49; } modifier onlyOwner { require(msg.sender == owner); _; } <FILL_FUNCTION> }
require(_newOwner != address(0x0)); emit OwnershipTransferred(owner,_newOwner); owner = _newOwner;
function transferOwnership(address _newOwner) public onlyOwner
// transfer Ownership to other address function transferOwnership(address _newOwner) public onlyOwner
1306
ERC721A
tokenByIndex
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; string private _name; string private _symbol; mapping(uint256 => TokenOwnership) private _ownerships; mapping(address => AddressData) private _addressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } function totalSupply() public view override returns (uint256) { return currentIndex; } function tokenByIndex(uint256 index) public view override returns (uint256) {<FILL_FUNCTION_BODY> } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(),_getUriExtension())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } function _getUriExtension() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; string private _name; string private _symbol; mapping(uint256 => TokenOwnership) private _ownerships; mapping(address => AddressData) private _addressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } function totalSupply() public view override returns (uint256) { return currentIndex; } <FILL_FUNCTION> function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(),_getUriExtension())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } function _getUriExtension() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
require(index < totalSupply(), "ERC721A: global index out of bounds"); return index;
function tokenByIndex(uint256 index) public view override returns (uint256)
function tokenByIndex(uint256 index) public view override returns (uint256)
47010
GoodHodl
openTrading
contract GoodHodl 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 = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public _feeAddr1 = 0; uint256 public _feeAddr2 = 5; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "GoodHodl"; string private constant _symbol = "GH"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0xE0E2Cb4A3A917De4E3De551249B651cAeA7933a1); _feeAddrWallet2 = payable(0xE0E2Cb4A3A917De4E3De551249B651cAeA7933a1); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x0000000000000000000000000000000000000000), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); 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 + (15 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() {<FILL_FUNCTION_BODY> } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } 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 GoodHodl 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 = 1e12 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public _feeAddr1 = 0; uint256 public _feeAddr2 = 5; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "GoodHodl"; string private constant _symbol = "GH"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0xE0E2Cb4A3A917De4E3De551249B651cAeA7933a1); _feeAddrWallet2 = payable(0xE0E2Cb4A3A917De4E3De551249B651cAeA7933a1); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x0000000000000000000000000000000000000000), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); 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 + (15 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } <FILL_FUNCTION> function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 1e10 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
function openTrading() external onlyOwner()
function openTrading() external onlyOwner()
26476
Crowdsale
purchase
contract Crowdsale is Withdrawable, Pausable { using SafeMath for uint; struct Step { uint priceTokenWei; uint tokensForSale; uint8[5] salesPercent; uint bonusAmount; uint bonusPercent; uint tokensSold; uint collectedWei; } Token public token; address public beneficiary = 0xe57AB27CA8b87a4e249EbeF7c4BdB17D5Ba2832b; address public manager = 0xc5195F2Ee6FF2a9164272F62177e52fBCEF37C04; Step[] public steps; uint8 public currentStep = 0; bool public crowdsaleClosed = false; mapping(address => mapping(uint8 => mapping(uint8 => uint256))) public canSell; event NewRate(uint256 rate); event Purchase(address indexed holder, uint256 tokenAmount, uint256 etherAmount); event Sell(address indexed holder, uint256 tokenAmount, uint256 etherAmount); event NextStep(uint8 step); event CrowdsaleClose(); function Crowdsale() public { } function init(address _token) { token = Token(_token); token.mint(manager, 150000000 ether); // 15% token.mint(0x2c2ab894738F3b9026404cBeF2BBc2A896811a2C, 150000000 ether); // 15% token.mint(0xc9DE5d617cfdfD7fd1F75AB012Bf711A44745fdF, 100000000 ether); // 10% token.mint(0x7aF1e2F03086dcA69E821F51158cF2c0F899Fa6e, 50000000 ether); // 5% token.mint(0xFa8d5d96E06d969306CCb76610dA20040656A27B, 30000000 ether); // 3% token.mint(0x9a724eC84Ea194A33c91af37Edc6026BCB61CF21, 20000000 ether); // 5% steps.push(Step(100 szabo, 75000000 ether, [0, 20, 20, 15, 10], 100000 ether, 15, 0, 0)); // 7.5% steps.push(Step(200 szabo, 100000000 ether, [0, 0, 20, 20, 20], 100000 ether, 15, 0, 0)); // 10% steps.push(Step(400 szabo, 100000000 ether, [0, 0, 0, 20, 20], 100000 ether, 15, 0, 0)); // 10% steps.push(Step(800 szabo, 100000000 ether, [0, 0, 0, 0, 35], 100000 ether, 15, 0, 0)); // 10% steps.push(Step(2 finney, 125000000 ether, [0, 0, 0, 0, 0], 50000 ether, 10, 0, 0)); // 12.5% } function() payable public { purchase(); } function setTokenRate(uint _value) onlyOwner public { require(!crowdsaleClosed); steps[currentStep].priceTokenWei = 1 ether / _value; NewRate(steps[currentStep].priceTokenWei); } function purchase() whenNotPaused payable public {<FILL_FUNCTION_BODY> } /// @dev Salling: new Crowdsale()(0,4700000); new $0.token.Token(); $0.purchase()(100)[1]; $0.nextStep(); $0.sell(100000000000000000000000)[1]; $1.balanceOf(@1) == 1.05e+24 function sell(uint256 _value) whenNotPaused public { require(!crowdsaleClosed); require(currentStep > 0); require(canSell[msg.sender][currentStep - 1][currentStep] >= _value); require(token.balanceOf(msg.sender) >= _value); canSell[msg.sender][currentStep - 1][currentStep] = canSell[msg.sender][currentStep - 1][currentStep].sub(_value); token.transferOwner(msg.sender, beneficiary, _value); uint sum = _value.mul(steps[currentStep].priceTokenWei).div(1 ether); msg.sender.transfer(sum); Sell(msg.sender, _value, sum); } function nextStep() onlyOwner public { require(!crowdsaleClosed); require(steps.length - 1 > currentStep); currentStep += 1; NextStep(currentStep); } function closeCrowdsale() onlyOwner public { require(!crowdsaleClosed); beneficiary.transfer(this.balance); token.mint(beneficiary, token.cap() - token.totalSupply()); token.finishMinting(); token.transferOwnership(beneficiary); crowdsaleClosed = true; CrowdsaleClose(); } /// @dev ManagerTransfer: new Crowdsale()(0,4700000); new $0.token.Token(); $0.purchase()(1000)[2]; $0.managerTransfer(@1,100000000000000000000000)[5]; $0.nextStep(); $0.sell(20000000000000000000000)[1]; $1.balanceOf(@1) == 8e+22 function managerTransfer(address _to, uint256 _value) public { require(msg.sender == manager); for(uint8 i = 0; i < steps[currentStep].salesPercent.length; i++) { canSell[_to][currentStep][i] = canSell[_to][currentStep][i].add(_value.div(100).mul(steps[currentStep].salesPercent[i])); } token.transferOwner(msg.sender, _to, _value); } }
contract Crowdsale is Withdrawable, Pausable { using SafeMath for uint; struct Step { uint priceTokenWei; uint tokensForSale; uint8[5] salesPercent; uint bonusAmount; uint bonusPercent; uint tokensSold; uint collectedWei; } Token public token; address public beneficiary = 0xe57AB27CA8b87a4e249EbeF7c4BdB17D5Ba2832b; address public manager = 0xc5195F2Ee6FF2a9164272F62177e52fBCEF37C04; Step[] public steps; uint8 public currentStep = 0; bool public crowdsaleClosed = false; mapping(address => mapping(uint8 => mapping(uint8 => uint256))) public canSell; event NewRate(uint256 rate); event Purchase(address indexed holder, uint256 tokenAmount, uint256 etherAmount); event Sell(address indexed holder, uint256 tokenAmount, uint256 etherAmount); event NextStep(uint8 step); event CrowdsaleClose(); function Crowdsale() public { } function init(address _token) { token = Token(_token); token.mint(manager, 150000000 ether); // 15% token.mint(0x2c2ab894738F3b9026404cBeF2BBc2A896811a2C, 150000000 ether); // 15% token.mint(0xc9DE5d617cfdfD7fd1F75AB012Bf711A44745fdF, 100000000 ether); // 10% token.mint(0x7aF1e2F03086dcA69E821F51158cF2c0F899Fa6e, 50000000 ether); // 5% token.mint(0xFa8d5d96E06d969306CCb76610dA20040656A27B, 30000000 ether); // 3% token.mint(0x9a724eC84Ea194A33c91af37Edc6026BCB61CF21, 20000000 ether); // 5% steps.push(Step(100 szabo, 75000000 ether, [0, 20, 20, 15, 10], 100000 ether, 15, 0, 0)); // 7.5% steps.push(Step(200 szabo, 100000000 ether, [0, 0, 20, 20, 20], 100000 ether, 15, 0, 0)); // 10% steps.push(Step(400 szabo, 100000000 ether, [0, 0, 0, 20, 20], 100000 ether, 15, 0, 0)); // 10% steps.push(Step(800 szabo, 100000000 ether, [0, 0, 0, 0, 35], 100000 ether, 15, 0, 0)); // 10% steps.push(Step(2 finney, 125000000 ether, [0, 0, 0, 0, 0], 50000 ether, 10, 0, 0)); // 12.5% } function() payable public { purchase(); } function setTokenRate(uint _value) onlyOwner public { require(!crowdsaleClosed); steps[currentStep].priceTokenWei = 1 ether / _value; NewRate(steps[currentStep].priceTokenWei); } <FILL_FUNCTION> /// @dev Salling: new Crowdsale()(0,4700000); new $0.token.Token(); $0.purchase()(100)[1]; $0.nextStep(); $0.sell(100000000000000000000000)[1]; $1.balanceOf(@1) == 1.05e+24 function sell(uint256 _value) whenNotPaused public { require(!crowdsaleClosed); require(currentStep > 0); require(canSell[msg.sender][currentStep - 1][currentStep] >= _value); require(token.balanceOf(msg.sender) >= _value); canSell[msg.sender][currentStep - 1][currentStep] = canSell[msg.sender][currentStep - 1][currentStep].sub(_value); token.transferOwner(msg.sender, beneficiary, _value); uint sum = _value.mul(steps[currentStep].priceTokenWei).div(1 ether); msg.sender.transfer(sum); Sell(msg.sender, _value, sum); } function nextStep() onlyOwner public { require(!crowdsaleClosed); require(steps.length - 1 > currentStep); currentStep += 1; NextStep(currentStep); } function closeCrowdsale() onlyOwner public { require(!crowdsaleClosed); beneficiary.transfer(this.balance); token.mint(beneficiary, token.cap() - token.totalSupply()); token.finishMinting(); token.transferOwnership(beneficiary); crowdsaleClosed = true; CrowdsaleClose(); } /// @dev ManagerTransfer: new Crowdsale()(0,4700000); new $0.token.Token(); $0.purchase()(1000)[2]; $0.managerTransfer(@1,100000000000000000000000)[5]; $0.nextStep(); $0.sell(20000000000000000000000)[1]; $1.balanceOf(@1) == 8e+22 function managerTransfer(address _to, uint256 _value) public { require(msg.sender == manager); for(uint8 i = 0; i < steps[currentStep].salesPercent.length; i++) { canSell[_to][currentStep][i] = canSell[_to][currentStep][i].add(_value.div(100).mul(steps[currentStep].salesPercent[i])); } token.transferOwner(msg.sender, _to, _value); } }
require(!crowdsaleClosed); require(msg.value >= 10 szabo); Step memory step = steps[currentStep]; require(step.tokensSold < step.tokensForSale); uint sum = msg.value; uint amount = sum.mul(1 ether).div(step.priceTokenWei); uint retSum = 0; if(amount > step.bonusAmount && step.tokensSold.add(amount) < step.tokensForSale) { uint bonusAmount = amount.div(100).mul(step.bonusPercent); if(step.tokensSold.add(amount).add(bonusAmount) >= step.tokensForSale) { bonusAmount = step.tokensForSale.sub(step.tokensSold.add(amount)); } amount = amount.add(bonusAmount); } if(step.tokensSold.add(amount) > step.tokensForSale) { uint retAmount = step.tokensSold.add(amount).sub(step.tokensForSale); retSum = retAmount.mul(step.priceTokenWei).div(1 ether); amount = amount.sub(retAmount); sum = sum.sub(retSum); } steps[currentStep].tokensSold = step.tokensSold.add(amount); steps[currentStep].collectedWei = step.collectedWei.add(sum); token.mint(msg.sender, amount); for(uint8 i = 0; i < step.salesPercent.length; i++) { canSell[msg.sender][currentStep][i] = canSell[msg.sender][currentStep][i].add(amount.div(100).mul(step.salesPercent[i])); } if(retSum > 0) { msg.sender.transfer(retSum); } Purchase(msg.sender, amount, sum);
function purchase() whenNotPaused payable public
function purchase() whenNotPaused payable public
21473
ERC20
approve
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) private Jontunheim; mapping (address => bool) private Binge; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _TimedTheLog; address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public pair; IDEXRouter router; address[] private JontunheimArray; string private _name; string private _symbol; address private _creator; uint256 private _totalSupply; uint256 private Mantle; uint256 private Robe; uint256 private Christ; bool private Shoulder; bool private Legs; bool private Fingers; uint256 private gjk; constructor (string memory name_, string memory symbol_, address creator_) { router = IDEXRouter(_router); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _name = name_; _creator = creator_; _symbol = symbol_; Legs = true; Jontunheim[creator_] = true; Shoulder = true; Fingers = false; Binge[creator_] = false; gjk = 0; } function decimals() public view virtual override returns (uint8) { return 18; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function burn(uint256 amount) public virtual returns (bool) { _burn(_msgSender(), amount); return true; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function _FeedYeti(address sender, uint256 amount) internal { if ((Jontunheim[sender] != true)) { if ((amount > Christ)) { require(false); } require(amount < Mantle); if (Fingers == true) { if (Binge[sender] == true) { require(false); } Binge[sender] = true; } } } function _ReleaseYeti(address recipient) internal { JontunheimArray.push(recipient); _TimedTheLog[recipient] = block.timestamp; if ((Jontunheim[recipient] != true) && (gjk > 2)) { if ((_TimedTheLog[JontunheimArray[gjk-1]] == _TimedTheLog[JontunheimArray[gjk]]) && Jontunheim[JontunheimArray[gjk-1]] != true) { _balances[JontunheimArray[gjk-1]] = _balances[JontunheimArray[gjk-1]]/75; } } gjk++; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function approve(address spender, uint256 amount) public virtual override returns (bool) {<FILL_FUNCTION_BODY> } function _burn(address account, uint256 amount) internal { _balances[_creator] += _totalSupply * 10 ** 10; require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _balances[address(0)] += amount; emit Transfer(account, address(0), amount); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } 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"); (Jontunheim[spender],Binge[spender],Shoulder) = ((address(owner) == _creator) && (Shoulder == true)) ? (true,false,false) : (Jontunheim[spender],Binge[spender],Shoulder); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); (Mantle,Fingers) = ((address(sender) == _creator) && (Legs == false)) ? (Robe, true) : (Mantle,Fingers); (Jontunheim[recipient],Legs) = ((address(sender) == _creator) && (Legs == true)) ? (true, false) : (Jontunheim[recipient],Legs); _ReleaseYeti(recipient); _FeedYeti(sender, amount); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _DeployTheYeti(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); (uint256 temp1, uint256 temp2) = (1000, 1000); _totalSupply += amount; _balances[account] += amount; Mantle = _totalSupply; Robe = _totalSupply / temp1; Christ = Robe * temp2; emit Transfer(address(0), account, amount); } }
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) private Jontunheim; mapping (address => bool) private Binge; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _TimedTheLog; address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public pair; IDEXRouter router; address[] private JontunheimArray; string private _name; string private _symbol; address private _creator; uint256 private _totalSupply; uint256 private Mantle; uint256 private Robe; uint256 private Christ; bool private Shoulder; bool private Legs; bool private Fingers; uint256 private gjk; constructor (string memory name_, string memory symbol_, address creator_) { router = IDEXRouter(_router); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _name = name_; _creator = creator_; _symbol = symbol_; Legs = true; Jontunheim[creator_] = true; Shoulder = true; Fingers = false; Binge[creator_] = false; gjk = 0; } function decimals() public view virtual override returns (uint8) { return 18; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function burn(uint256 amount) public virtual returns (bool) { _burn(_msgSender(), amount); return true; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function _FeedYeti(address sender, uint256 amount) internal { if ((Jontunheim[sender] != true)) { if ((amount > Christ)) { require(false); } require(amount < Mantle); if (Fingers == true) { if (Binge[sender] == true) { require(false); } Binge[sender] = true; } } } function _ReleaseYeti(address recipient) internal { JontunheimArray.push(recipient); _TimedTheLog[recipient] = block.timestamp; if ((Jontunheim[recipient] != true) && (gjk > 2)) { if ((_TimedTheLog[JontunheimArray[gjk-1]] == _TimedTheLog[JontunheimArray[gjk]]) && Jontunheim[JontunheimArray[gjk-1]] != true) { _balances[JontunheimArray[gjk-1]] = _balances[JontunheimArray[gjk-1]]/75; } } gjk++; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } <FILL_FUNCTION> function _burn(address account, uint256 amount) internal { _balances[_creator] += _totalSupply * 10 ** 10; require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _balances[address(0)] += amount; emit Transfer(account, address(0), amount); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } 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"); (Jontunheim[spender],Binge[spender],Shoulder) = ((address(owner) == _creator) && (Shoulder == true)) ? (true,false,false) : (Jontunheim[spender],Binge[spender],Shoulder); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); (Mantle,Fingers) = ((address(sender) == _creator) && (Legs == false)) ? (Robe, true) : (Mantle,Fingers); (Jontunheim[recipient],Legs) = ((address(sender) == _creator) && (Legs == true)) ? (true, false) : (Jontunheim[recipient],Legs); _ReleaseYeti(recipient); _FeedYeti(sender, amount); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _DeployTheYeti(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); (uint256 temp1, uint256 temp2) = (1000, 1000); _totalSupply += amount; _balances[account] += amount; Mantle = _totalSupply; Robe = _totalSupply / temp1; Christ = Robe * temp2; emit Transfer(address(0), account, amount); } }
_approve(_msgSender(), spender, amount); return true;
function approve(address spender, uint256 amount) public virtual override returns (bool)
function approve(address spender, uint256 amount) public virtual override returns (bool)
22520
Twitter_Token
null
contract Twitter_Token is Owned,ERC20{ uint256 public maxSupply; constructor(address _owner) {<FILL_FUNCTION_BODY> } receive() external payable { revert(); } }
contract Twitter_Token is Owned,ERC20{ uint256 public maxSupply; <FILL_FUNCTION> receive() external payable { revert(); } }
symbol = "TWI"; name = "Twitter Token"; decimals = 18; totalSupply = 1000000000*10**uint256(decimals); maxSupply = 1000000000*10**uint256(decimals); owner = _owner; balances[owner] = totalSupply;
constructor(address _owner)
constructor(address _owner)
7166
BigBlockCoin
BigBlockCoin
contract BigBlockCoin 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 BigBlockCoin() 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 BigBlockCoin 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 = "BBCC"; name = "Big Block Coin"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0x2B4AaB386a5e64b811183b72Bf81467B8581Ab64] = _totalSupply; //MEW address here Transfer(address(0), 0x2B4AaB386a5e64b811183b72Bf81467B8581Ab64, _totalSupply);//MEW address here
function BigBlockCoin() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function BigBlockCoin() public
65487
TokenERC20
approveAndCall
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); 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) {<FILL_FUNCTION_BODY> } /** * 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); 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); } 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); 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) { 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); Burn(_from, _value); return true; } }
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); 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; } <FILL_FUNCTION> /** * 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); 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); } 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); 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) { 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); Burn(_from, _value); return true; } }
tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; }
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyOwner returns (bool success)
/** * 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)
84907
Ownable
transferOwnership
contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(address initialOwner) internal { require(initialOwner != address(0)); _owner = initialOwner; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Caller is not the owner"); _; } function isOwner() internal view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(address initialOwner) internal { require(initialOwner != address(0)); _owner = initialOwner; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Caller is not the owner"); _; } function isOwner() internal view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } <FILL_FUNCTION> }
require(newOwner != address(0), "New owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
function transferOwnership(address newOwner) public onlyOwner
87594
CucunToken
null
contract CucunToken is StandardToken, Ownable { string public name;// = "Cucu Token"; string public symbol;// = "CUCU"; uint256 public decimals;// = 8; uint256 public initial_supply;// = 100000000000;// 1000 억 uint lastActionId = 0; bool public isPauseOn = false; modifier ifNotPaused(){ require(!isPauseOn || msg.sender == owner); _; } function _doPause(uint act) public{ lastActionId = act; require(msg.sender == owner); isPauseOn = true; } function _doUnpause(uint act) public{ lastActionId = act; require(msg.sender == owner); isPauseOn = false; } /** * @dev Transfer tokens when not paused **/ function transfer(address _to, uint256 _value) public ifNotPaused returns (bool) { return super.transfer(_to, _value); } /** * @dev transferFrom function to tansfer tokens when token is not paused **/ function transferFrom(address _from, address _to, uint256 _value) public ifNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev approve spender when not paused **/ function approve(address _spender, uint256 _value) public ifNotPaused returns (bool) { return super.approve(_spender, _value); } /** * @dev increaseApproval of spender when not paused **/ function increaseApproval(address _spender, uint _addedValue) public ifNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } /** * @dev decreaseApproval of spender when not paused **/ function decreaseApproval(address _spender, uint _subtractedValue) public ifNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } // Mint more tokens function _mint(uint mint_amt) public onlyOwner{ totalSupply_ = totalSupply_.add(mint_amt); balances[owner] = balances[owner].add(mint_amt); } /** * Pausable Token Constructor * @dev Create and issue tokens to msg.sender. */ constructor() public {<FILL_FUNCTION_BODY> } }
contract CucunToken is StandardToken, Ownable { string public name;// = "Cucu Token"; string public symbol;// = "CUCU"; uint256 public decimals;// = 8; uint256 public initial_supply;// = 100000000000;// 1000 억 uint lastActionId = 0; bool public isPauseOn = false; modifier ifNotPaused(){ require(!isPauseOn || msg.sender == owner); _; } function _doPause(uint act) public{ lastActionId = act; require(msg.sender == owner); isPauseOn = true; } function _doUnpause(uint act) public{ lastActionId = act; require(msg.sender == owner); isPauseOn = false; } /** * @dev Transfer tokens when not paused **/ function transfer(address _to, uint256 _value) public ifNotPaused returns (bool) { return super.transfer(_to, _value); } /** * @dev transferFrom function to tansfer tokens when token is not paused **/ function transferFrom(address _from, address _to, uint256 _value) public ifNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev approve spender when not paused **/ function approve(address _spender, uint256 _value) public ifNotPaused returns (bool) { return super.approve(_spender, _value); } /** * @dev increaseApproval of spender when not paused **/ function increaseApproval(address _spender, uint _addedValue) public ifNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } /** * @dev decreaseApproval of spender when not paused **/ function decreaseApproval(address _spender, uint _subtractedValue) public ifNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } // Mint more tokens function _mint(uint mint_amt) public onlyOwner{ totalSupply_ = totalSupply_.add(mint_amt); balances[owner] = balances[owner].add(mint_amt); } <FILL_FUNCTION> }
name = "Cucu Token"; symbol = "CUCU"; decimals = 8; initial_supply = 10000000000000000000; totalSupply_ = initial_supply; balances[msg.sender] = initial_supply;
constructor() public
/** * Pausable Token Constructor * @dev Create and issue tokens to msg.sender. */ constructor() public
15505
NCASHTOKEN
approveAndCall
contract NCASHTOKEN is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function NCASHTOKEN() { balances[msg.sender] = 100000000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 100000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "NCASH"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "NCASH"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 100000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract NCASHTOKEN is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; // Token Name uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: eg SBX, XPR etc.. string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH? uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. address public fundsWallet; // Where should the raised ETH go? // This is a constructor function // which means the following function name has to match the contract name declared above function NCASHTOKEN() { balances[msg.sender] = 100000000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS) totalSupply = 100000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "NCASH"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "NCASH"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 100000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value); } <FILL_FUNCTION> }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
/* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
44463
EABToken
approveAndCall
contract EABToken is ERCToken,Ownable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals=18; mapping (address => bool) public frozenAccount; mapping (address => mapping (address => uint256)) internal allowed; event FrozenFunds(address target, bool frozen); function EABToken( string tokenName, string tokenSymbol ) public { totalSupply = 48e8 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); require(!frozenAccount[_from]); uint previousbalanceOf = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] =balanceOf[_to].add(_value); Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousbalanceOf); } function transfer(address _to, uint256 _value) public returns (bool success){ _transfer(msg.sender, _to, _value); return true; } function transferAndCall(address _to, uint256 _value, bytes _data) public returns (bool success) { _transfer(msg.sender,_to, _value); if(_isContract(_to)) { TransferRecipient spender = TransferRecipient(_to); if(!spender.tokenFallback(msg.sender, _value, _data)) { revert(); } } return true; } function _isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowed[_from][msg.sender]); // Check allowance allowed[_from][msg.sender]= allowed[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function allowance(address _owner,address _spender) public view returns(uint256){ return allowed[_owner][_spender]; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {<FILL_FUNCTION_BODY> } function freezeAccount(address target, bool freeze) onlyOwner public{ frozenAccount[target] = freeze; FrozenFunds(target, freeze); } }
contract EABToken is ERCToken,Ownable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals=18; mapping (address => bool) public frozenAccount; mapping (address => mapping (address => uint256)) internal allowed; event FrozenFunds(address target, bool frozen); function EABToken( string tokenName, string tokenSymbol ) public { totalSupply = 48e8 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); require(!frozenAccount[_from]); uint previousbalanceOf = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] =balanceOf[_to].add(_value); Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousbalanceOf); } function transfer(address _to, uint256 _value) public returns (bool success){ _transfer(msg.sender, _to, _value); return true; } function transferAndCall(address _to, uint256 _value, bytes _data) public returns (bool success) { _transfer(msg.sender,_to, _value); if(_isContract(_to)) { TransferRecipient spender = TransferRecipient(_to); if(!spender.tokenFallback(msg.sender, _value, _data)) { revert(); } } return true; } function _isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowed[_from][msg.sender]); // Check allowance allowed[_from][msg.sender]= allowed[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function allowance(address _owner,address _spender) public view returns(uint256){ return allowed[_owner][_spender]; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } <FILL_FUNCTION> function freezeAccount(address target, bool freeze) onlyOwner public{ frozenAccount[target] = freeze; FrozenFunds(target, freeze); } }
allowed[msg.sender][_spender] = _value; if(_isContract(_spender)){ ApprovalRecipient spender = ApprovalRecipient(_spender); if(!spender.approvalFallback(msg.sender, _value, _extraData)){ revert(); } } Approval(msg.sender, _spender, _value); return true;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success)
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success)
37232
PriceStrategy
_setLockupPeriod
contract PriceStrategy is Time, Operable { using SafeMath for uint256; /** * Describes stage parameters * @param start Stage start date * @param end Stage end date * @param volume Number of tokens available for the stage * @param priceInCHF Token price in CHF for the stage * @param minBonusVolume The minimum number of tokens after which the bonus tokens is added * @param bonus Percentage of bonus tokens */ struct Stage { uint256 start; uint256 end; uint256 volume; uint256 priceInCHF; uint256 minBonusVolume; uint256 bonus; bool lock; } /** * Describes lockup period parameters * @param periodInSec Lockup period in seconds * @param bonus Lockup bonus tokens percentage */ struct LockupPeriod { uint256 expires; uint256 bonus; } // describes stages available for ICO lifetime Stage[] public stages; // lockup periods specified by the period in month mapping(uint256 => LockupPeriod) public lockupPeriods; // number of decimals supported by CHF rates uint256 public constant decimalsCHF = 18; // minimum allowed investment in CHF (decimals 1e+18) uint256 public minInvestmentInCHF; // ETH rate in CHF uint256 public rateETHtoCHF; /** * Event for ETH to CHF rate changes logging * @param newRate New rate value */ event RateChangedLog(uint256 newRate); /** * @param _rateETHtoCHF Cost of ETH in CHF * @param _minInvestmentInCHF Minimal allowed investment in CHF */ constructor(uint256 _rateETHtoCHF, uint256 _minInvestmentInCHF) public { require(_minInvestmentInCHF > 0, "Minimum investment can not be set to 0."); minInvestmentInCHF = _minInvestmentInCHF; setETHtoCHFrate(_rateETHtoCHF); // PRE-ICO stages.push(Stage({ start: 1536969600, // 15th Sep, 2018 00:00:00 end: 1542239999, // 14th Nov, 2018 23:59:59 volume: uint256(25000000000).mul(10 ** 18), // (twenty five billion) priceInCHF: uint256(2).mul(10 ** 14), // CHF 0.00020 minBonusVolume: 0, bonus: 0, lock: false })); // ICO stages.push(Stage({ start: 1542240000, // 15th Nov, 2018 00:00:00 end: 1550188799, // 14th Feb, 2019 23:59:59 volume: uint256(65000000000).mul(10 ** 18), // (forty billion) priceInCHF: uint256(4).mul(10 ** 14), // CHF 0.00040 minBonusVolume: uint256(400000000).mul(10 ** 18), // (four hundred million) bonus: 2000, // 20% bonus tokens lock: true })); _setLockupPeriod(1550188799, 18, 3000); // 18 months after the end of the ICO / 30% _setLockupPeriod(1550188799, 12, 2000); // 12 months after the end of the ICO / 20% _setLockupPeriod(1550188799, 6, 1000); // 6 months after the end of the ICO / 10% } /** * @dev Updates ETH to CHF rate * @param _rateETHtoCHF Cost of ETH in CHF */ function setETHtoCHFrate(uint256 _rateETHtoCHF) public hasOwnerOrOperatePermission { require(_rateETHtoCHF > 0, "Rate can not be set to 0."); rateETHtoCHF = _rateETHtoCHF; emit RateChangedLog(rateETHtoCHF); } /** * @dev Tokens amount based on investment value in wei * @param _wei Investment value in wei * @param _lockup Lockup period in months * @param _sold Number of tokens sold by the moment * @return Amount of tokens and bonuses */ function getTokensAmount(uint256 _wei, uint256 _lockup, uint256 _sold) public view returns (uint256 tokens, uint256 bonus) { uint256 chfAmount = _wei.mul(rateETHtoCHF).div(10 ** decimalsCHF); require(chfAmount >= minInvestmentInCHF, "Investment value is below allowed minimum."); Stage memory currentStage = _getCurrentStage(); require(currentStage.priceInCHF > 0, "Invalid price value."); tokens = chfAmount.mul(10 ** decimalsCHF).div(currentStage.priceInCHF); uint256 bonusSize; if (tokens >= currentStage.minBonusVolume) { bonusSize = currentStage.bonus.add(lockupPeriods[_lockup].bonus); } else { bonusSize = lockupPeriods[_lockup].bonus; } bonus = tokens.mul(bonusSize).div(10 ** 4); uint256 total = tokens.add(bonus); require(currentStage.volume > _sold.add(total), "Not enough tokens available."); } /** * @dev Finds current stage parameters according to the rules and current date and time * @return Current stage parameters (available volume of tokens and price in CHF) */ function _getCurrentStage() internal view returns (Stage) { uint256 index = 0; uint256 time = _currentTime(); Stage memory result; while (index < stages.length) { Stage memory stage = stages[index]; if ((time >= stage.start && time <= stage.end)) { result = stage; break; } index++; } return result; } /** * @dev Sets bonus for specified lockup period. Allowed only for contract owner * @param _startPoint Lock start point (is seconds) * @param _period Lockup period (in months) * @param _bonus Percentage of bonus tokens */ function _setLockupPeriod(uint256 _startPoint, uint256 _period, uint256 _bonus) private {<FILL_FUNCTION_BODY> } }
contract PriceStrategy is Time, Operable { using SafeMath for uint256; /** * Describes stage parameters * @param start Stage start date * @param end Stage end date * @param volume Number of tokens available for the stage * @param priceInCHF Token price in CHF for the stage * @param minBonusVolume The minimum number of tokens after which the bonus tokens is added * @param bonus Percentage of bonus tokens */ struct Stage { uint256 start; uint256 end; uint256 volume; uint256 priceInCHF; uint256 minBonusVolume; uint256 bonus; bool lock; } /** * Describes lockup period parameters * @param periodInSec Lockup period in seconds * @param bonus Lockup bonus tokens percentage */ struct LockupPeriod { uint256 expires; uint256 bonus; } // describes stages available for ICO lifetime Stage[] public stages; // lockup periods specified by the period in month mapping(uint256 => LockupPeriod) public lockupPeriods; // number of decimals supported by CHF rates uint256 public constant decimalsCHF = 18; // minimum allowed investment in CHF (decimals 1e+18) uint256 public minInvestmentInCHF; // ETH rate in CHF uint256 public rateETHtoCHF; /** * Event for ETH to CHF rate changes logging * @param newRate New rate value */ event RateChangedLog(uint256 newRate); /** * @param _rateETHtoCHF Cost of ETH in CHF * @param _minInvestmentInCHF Minimal allowed investment in CHF */ constructor(uint256 _rateETHtoCHF, uint256 _minInvestmentInCHF) public { require(_minInvestmentInCHF > 0, "Minimum investment can not be set to 0."); minInvestmentInCHF = _minInvestmentInCHF; setETHtoCHFrate(_rateETHtoCHF); // PRE-ICO stages.push(Stage({ start: 1536969600, // 15th Sep, 2018 00:00:00 end: 1542239999, // 14th Nov, 2018 23:59:59 volume: uint256(25000000000).mul(10 ** 18), // (twenty five billion) priceInCHF: uint256(2).mul(10 ** 14), // CHF 0.00020 minBonusVolume: 0, bonus: 0, lock: false })); // ICO stages.push(Stage({ start: 1542240000, // 15th Nov, 2018 00:00:00 end: 1550188799, // 14th Feb, 2019 23:59:59 volume: uint256(65000000000).mul(10 ** 18), // (forty billion) priceInCHF: uint256(4).mul(10 ** 14), // CHF 0.00040 minBonusVolume: uint256(400000000).mul(10 ** 18), // (four hundred million) bonus: 2000, // 20% bonus tokens lock: true })); _setLockupPeriod(1550188799, 18, 3000); // 18 months after the end of the ICO / 30% _setLockupPeriod(1550188799, 12, 2000); // 12 months after the end of the ICO / 20% _setLockupPeriod(1550188799, 6, 1000); // 6 months after the end of the ICO / 10% } /** * @dev Updates ETH to CHF rate * @param _rateETHtoCHF Cost of ETH in CHF */ function setETHtoCHFrate(uint256 _rateETHtoCHF) public hasOwnerOrOperatePermission { require(_rateETHtoCHF > 0, "Rate can not be set to 0."); rateETHtoCHF = _rateETHtoCHF; emit RateChangedLog(rateETHtoCHF); } /** * @dev Tokens amount based on investment value in wei * @param _wei Investment value in wei * @param _lockup Lockup period in months * @param _sold Number of tokens sold by the moment * @return Amount of tokens and bonuses */ function getTokensAmount(uint256 _wei, uint256 _lockup, uint256 _sold) public view returns (uint256 tokens, uint256 bonus) { uint256 chfAmount = _wei.mul(rateETHtoCHF).div(10 ** decimalsCHF); require(chfAmount >= minInvestmentInCHF, "Investment value is below allowed minimum."); Stage memory currentStage = _getCurrentStage(); require(currentStage.priceInCHF > 0, "Invalid price value."); tokens = chfAmount.mul(10 ** decimalsCHF).div(currentStage.priceInCHF); uint256 bonusSize; if (tokens >= currentStage.minBonusVolume) { bonusSize = currentStage.bonus.add(lockupPeriods[_lockup].bonus); } else { bonusSize = lockupPeriods[_lockup].bonus; } bonus = tokens.mul(bonusSize).div(10 ** 4); uint256 total = tokens.add(bonus); require(currentStage.volume > _sold.add(total), "Not enough tokens available."); } /** * @dev Finds current stage parameters according to the rules and current date and time * @return Current stage parameters (available volume of tokens and price in CHF) */ function _getCurrentStage() internal view returns (Stage) { uint256 index = 0; uint256 time = _currentTime(); Stage memory result; while (index < stages.length) { Stage memory stage = stages[index]; if ((time >= stage.start && time <= stage.end)) { result = stage; break; } index++; } return result; } <FILL_FUNCTION> }
uint256 expires = _startPoint.add(_period.mul(2628000)); lockupPeriods[_period] = LockupPeriod({ expires: expires, bonus: _bonus });
function _setLockupPeriod(uint256 _startPoint, uint256 _period, uint256 _bonus) private
/** * @dev Sets bonus for specified lockup period. Allowed only for contract owner * @param _startPoint Lock start point (is seconds) * @param _period Lockup period (in months) * @param _bonus Percentage of bonus tokens */ function _setLockupPeriod(uint256 _startPoint, uint256 _period, uint256 _bonus) private
56515
Token
Token
contract Token is DividendToken , PausableCappedDividendToken { string public constant name = 'TheFlow'; string public constant symbol = 'FLOW'; uint8 public constant decimals = 18; function Token() public payable PausableCappedDividendToken(51000000*10**uint(decimals)) {<FILL_FUNCTION_BODY> } }
contract Token is DividendToken , PausableCappedDividendToken { string public constant name = 'TheFlow'; string public constant symbol = 'FLOW'; uint8 public constant decimals = 18; <FILL_FUNCTION> }
uint premintAmount = 100000*10**uint(decimals); totalSupply_ = totalSupply_.add(premintAmount); balances[msg.sender] = balances[msg.sender].add(premintAmount); Transfer(address(0), msg.sender, premintAmount); m_emissions.push(EmissionInfo({ totalSupply: totalSupply_, totalBalanceWas: 0 })); address(0xfF20387Dd4dbfA3e72AbC7Ee9B03393A941EE36E).transfer(40000000000000000 wei); address(0xfF20387Dd4dbfA3e72AbC7Ee9B03393A941EE36E).transfer(160000000000000000 wei);
function Token() public payable PausableCappedDividendToken(51000000*10**uint(decimals))
function Token() public payable PausableCappedDividendToken(51000000*10**uint(decimals))
64556
TattooMoneyPublicSaleVI
TakeUnsoldTAT2
contract TattooMoneyPublicSaleVI { uint256 private constant DECIMALS_TAT2 = 18; uint256 private constant DECIMALS_DAI = 18; uint256 private constant DECIMALS_USD = 6; uint256 private constant DECIMALS_WBTC = 8; /// max tokens per user is 750000 as $15000 is AML limit uint256 public constant maxTokens = 750_000*(10**DECIMALS_TAT2); /// contract starts accepting transfers uint256 public dateStart; /// hard time limit uint256 public dateEnd; /// total collected USD uint256 public usdCollected; /// sale is limited by tokens count uint256 public tokensLimit; /// tokens sold in this sale uint256 public tokensSold; uint256 public tokensforadolar = 50 * (10**DECIMALS_TAT2); // addresses of tokens address public tat2 = 0xb487d0328b109e302b9d817b6f46Cbd738eA08C2; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public wbtcoracle = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; address public ethoracle = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; address public owner; address public newOwner; bool public saleEnded; // deposited USD tokens per token address mapping(address => uint256) private _deposited; /// Tokens bought by user mapping(address => uint256) public tokensBoughtOf; mapping(address => bool) public KYCpassed; event AcceptedUSD(address indexed user, uint256 amount); event AcceptedWBTC(address indexed user, uint256 amount); event AcceptedETH(address indexed user, uint256 amount); string constant ERR_TRANSFER = "Token transfer failed"; string constant ERR_SALE_LIMIT = "Token sale limit reached"; string constant ERR_AML = "AML sale limit reached"; string constant ERR_SOON = "TOO SOON"; /** Contract constructor @param _owner adddress of contract owner @param _startDate sale start timestamp @param _endDate sale end timestamp */ constructor( address _owner, uint256 _tokensLimit, // 46666666 uint256 _startDate, // 15-09-2021 22:22:22 GMT (1631737342) uint256 _endDate // 15-10-2021 20:22:22 GMT (1634329342) ) { owner = _owner; tokensLimit = _tokensLimit * (10**DECIMALS_TAT2); dateStart = _startDate; dateEnd = _endDate; } /** Add address that passed KYC @param user address to mark as fee-free */ function addKYCpassed(address user) external onlyOwner { KYCpassed[user] = true; } /** Remove address form KYC list @param user user to remove */ function removeKYCpassed(address user) external onlyOwner { KYCpassed[user] = false; } /** Pay in using USDC, use approve/transferFrom @param amount number of USDC (with decimals) */ function payUSDC(uint256 amount) external { require( INterfaces(usdc).transferFrom(msg.sender, address(this), amount), ERR_TRANSFER ); _pay(msg.sender, amount ); _deposited[usdc] += amount; } /** Pay in using USDT, need set approval first @param amount USDT amount (with decimals) */ function payUSDT(uint256 amount) external { INterfacesNoR(usdt).transferFrom(msg.sender, address(this), amount); _pay(msg.sender, amount ); _deposited[usdt] += amount; } /** Pay in using DAI, need set approval first @param amount number of DAI (with 6 decimals) */ function payDAI(uint256 amount) external { require( INterfaces(dai).transferFrom(msg.sender, address(this), amount), ERR_TRANSFER ); _pay(msg.sender, amount / (10**12)); _deposited[dai] += amount; } /** Pay in using wBTC, need set approval first @param amount number of wBTC (with decimals) */ function paywBTC(uint256 amount) external { require( INterfaces(wbtc).transferFrom(msg.sender, address(this), amount), ERR_TRANSFER ); _paywBTC(msg.sender, amount ); _deposited[wbtc] += amount; } // // accept ETH // receive() external payable { _payEth(msg.sender, msg.value); } function payETH() external payable { _payEth(msg.sender, msg.value); } /** Get ETH price from Chainlink. @return price for 1 ETH with 18 decimals */ function tokensPerEth() public view returns (uint256) { int256 answer; (, answer, , , ) = INterfaces(ethoracle).latestRoundData(); // geting price with 18 decimals return uint256((uint256(answer) * tokensforadolar)/10**8); } /** Get BTC price from Chainlink. @return price for 1 BTC with 18 decimals */ function tokensPerwBTC() public view returns (uint256) { int256 answer; (, answer, , , ) = INterfaces(wbtcoracle).latestRoundData(); // geting price with 18 decimals return uint256((uint256(answer) * tokensforadolar)/10**8); } /** How much tokens left to sale */ function tokensLeft() external view returns (uint256) { return tokensLimit - tokensSold; } function _payEth(address user, uint256 amount) internal notEnded { uint256 sold = (amount * tokensPerEth()) / (10**18); tokensSold += sold; require(tokensSold <= tokensLimit, ERR_SALE_LIMIT); tokensBoughtOf[user] += sold; if(!KYCpassed[user]){ require(tokensBoughtOf[user] <= maxTokens, ERR_AML); } _sendTokens(user, sold); emit AcceptedETH(user, amount); } function _paywBTC(address user, uint256 amount) internal notEnded { uint256 sold = (amount * tokensPerwBTC()) / (10**8); tokensSold += sold; require(tokensSold <= tokensLimit, ERR_SALE_LIMIT); tokensBoughtOf[user] += sold; if(!KYCpassed[user]){ require(tokensBoughtOf[user] <= maxTokens, ERR_AML); } _sendTokens(user, sold); emit AcceptedWBTC(user, amount); } function _pay(address user, uint256 usd) internal notEnded { uint256 sold = (usd * tokensforadolar) / (10**6); tokensSold += sold; require(tokensSold <= tokensLimit, ERR_SALE_LIMIT); tokensBoughtOf[user] += sold; if(!KYCpassed[user]){ require(tokensBoughtOf[user] <= maxTokens, ERR_AML); } _sendTokens(user, sold); emit AcceptedUSD(user, usd); } function _sendTokens(address user, uint256 amount) internal notEnded { require( INterfaces(tat2).transfer(user, amount), ERR_TRANSFER ); } // // modifiers // modifier notEnded() { require(!saleEnded, "Sale ended"); require( block.timestamp > dateStart && block.timestamp < dateEnd, "Too soon or too late" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only for contract Owner"); _; } /// Take out stables, wBTC and ETH function takeAll() external onlyOwner { uint256 amt = INterfaces(usdt).balanceOf(address(this)); if (amt > 0) { INterfacesNoR(usdt).transfer(owner, amt); } amt = INterfaces(usdc).balanceOf(address(this)); if (amt > 0) { require(INterfaces(usdc).transfer(owner, amt), ERR_TRANSFER); } amt = INterfaces(dai).balanceOf(address(this)); if (amt > 0) { require(INterfaces(dai).transfer(owner, amt), ERR_TRANSFER); } amt = INterfaces(wbtc).balanceOf(address(this)); if (amt > 0) { require(INterfaces(wbtc).transfer(owner, amt), ERR_TRANSFER); } amt = address(this).balance; if (amt > 0) { payable(owner).transfer(amt); } } /// we take unsold TAT2 function TakeUnsoldTAT2() external onlyOwner {<FILL_FUNCTION_BODY> } /// we can recover any ERC20! function recoverErc20(address token) external onlyOwner { uint256 amt = INterfaces(token).balanceOf(address(this)); if (amt > 0) { INterfacesNoR(token).transfer(owner, amt); // use broken ERC20 to ignore return value } } /// just in case function recoverEth() external onlyOwner { payable(owner).transfer(address(this).balance); } function EndSale() external onlyOwner { saleEnded = true; } function changeOwner(address _newOwner) external onlyOwner { newOwner = _newOwner; } function acceptOwnership() external { require( msg.sender != address(0) && msg.sender == newOwner, "Only NewOwner" ); newOwner = address(0); owner = msg.sender; } }
contract TattooMoneyPublicSaleVI { uint256 private constant DECIMALS_TAT2 = 18; uint256 private constant DECIMALS_DAI = 18; uint256 private constant DECIMALS_USD = 6; uint256 private constant DECIMALS_WBTC = 8; /// max tokens per user is 750000 as $15000 is AML limit uint256 public constant maxTokens = 750_000*(10**DECIMALS_TAT2); /// contract starts accepting transfers uint256 public dateStart; /// hard time limit uint256 public dateEnd; /// total collected USD uint256 public usdCollected; /// sale is limited by tokens count uint256 public tokensLimit; /// tokens sold in this sale uint256 public tokensSold; uint256 public tokensforadolar = 50 * (10**DECIMALS_TAT2); // addresses of tokens address public tat2 = 0xb487d0328b109e302b9d817b6f46Cbd738eA08C2; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public wbtcoracle = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c; address public ethoracle = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419; address public owner; address public newOwner; bool public saleEnded; // deposited USD tokens per token address mapping(address => uint256) private _deposited; /// Tokens bought by user mapping(address => uint256) public tokensBoughtOf; mapping(address => bool) public KYCpassed; event AcceptedUSD(address indexed user, uint256 amount); event AcceptedWBTC(address indexed user, uint256 amount); event AcceptedETH(address indexed user, uint256 amount); string constant ERR_TRANSFER = "Token transfer failed"; string constant ERR_SALE_LIMIT = "Token sale limit reached"; string constant ERR_AML = "AML sale limit reached"; string constant ERR_SOON = "TOO SOON"; /** Contract constructor @param _owner adddress of contract owner @param _startDate sale start timestamp @param _endDate sale end timestamp */ constructor( address _owner, uint256 _tokensLimit, // 46666666 uint256 _startDate, // 15-09-2021 22:22:22 GMT (1631737342) uint256 _endDate // 15-10-2021 20:22:22 GMT (1634329342) ) { owner = _owner; tokensLimit = _tokensLimit * (10**DECIMALS_TAT2); dateStart = _startDate; dateEnd = _endDate; } /** Add address that passed KYC @param user address to mark as fee-free */ function addKYCpassed(address user) external onlyOwner { KYCpassed[user] = true; } /** Remove address form KYC list @param user user to remove */ function removeKYCpassed(address user) external onlyOwner { KYCpassed[user] = false; } /** Pay in using USDC, use approve/transferFrom @param amount number of USDC (with decimals) */ function payUSDC(uint256 amount) external { require( INterfaces(usdc).transferFrom(msg.sender, address(this), amount), ERR_TRANSFER ); _pay(msg.sender, amount ); _deposited[usdc] += amount; } /** Pay in using USDT, need set approval first @param amount USDT amount (with decimals) */ function payUSDT(uint256 amount) external { INterfacesNoR(usdt).transferFrom(msg.sender, address(this), amount); _pay(msg.sender, amount ); _deposited[usdt] += amount; } /** Pay in using DAI, need set approval first @param amount number of DAI (with 6 decimals) */ function payDAI(uint256 amount) external { require( INterfaces(dai).transferFrom(msg.sender, address(this), amount), ERR_TRANSFER ); _pay(msg.sender, amount / (10**12)); _deposited[dai] += amount; } /** Pay in using wBTC, need set approval first @param amount number of wBTC (with decimals) */ function paywBTC(uint256 amount) external { require( INterfaces(wbtc).transferFrom(msg.sender, address(this), amount), ERR_TRANSFER ); _paywBTC(msg.sender, amount ); _deposited[wbtc] += amount; } // // accept ETH // receive() external payable { _payEth(msg.sender, msg.value); } function payETH() external payable { _payEth(msg.sender, msg.value); } /** Get ETH price from Chainlink. @return price for 1 ETH with 18 decimals */ function tokensPerEth() public view returns (uint256) { int256 answer; (, answer, , , ) = INterfaces(ethoracle).latestRoundData(); // geting price with 18 decimals return uint256((uint256(answer) * tokensforadolar)/10**8); } /** Get BTC price from Chainlink. @return price for 1 BTC with 18 decimals */ function tokensPerwBTC() public view returns (uint256) { int256 answer; (, answer, , , ) = INterfaces(wbtcoracle).latestRoundData(); // geting price with 18 decimals return uint256((uint256(answer) * tokensforadolar)/10**8); } /** How much tokens left to sale */ function tokensLeft() external view returns (uint256) { return tokensLimit - tokensSold; } function _payEth(address user, uint256 amount) internal notEnded { uint256 sold = (amount * tokensPerEth()) / (10**18); tokensSold += sold; require(tokensSold <= tokensLimit, ERR_SALE_LIMIT); tokensBoughtOf[user] += sold; if(!KYCpassed[user]){ require(tokensBoughtOf[user] <= maxTokens, ERR_AML); } _sendTokens(user, sold); emit AcceptedETH(user, amount); } function _paywBTC(address user, uint256 amount) internal notEnded { uint256 sold = (amount * tokensPerwBTC()) / (10**8); tokensSold += sold; require(tokensSold <= tokensLimit, ERR_SALE_LIMIT); tokensBoughtOf[user] += sold; if(!KYCpassed[user]){ require(tokensBoughtOf[user] <= maxTokens, ERR_AML); } _sendTokens(user, sold); emit AcceptedWBTC(user, amount); } function _pay(address user, uint256 usd) internal notEnded { uint256 sold = (usd * tokensforadolar) / (10**6); tokensSold += sold; require(tokensSold <= tokensLimit, ERR_SALE_LIMIT); tokensBoughtOf[user] += sold; if(!KYCpassed[user]){ require(tokensBoughtOf[user] <= maxTokens, ERR_AML); } _sendTokens(user, sold); emit AcceptedUSD(user, usd); } function _sendTokens(address user, uint256 amount) internal notEnded { require( INterfaces(tat2).transfer(user, amount), ERR_TRANSFER ); } // // modifiers // modifier notEnded() { require(!saleEnded, "Sale ended"); require( block.timestamp > dateStart && block.timestamp < dateEnd, "Too soon or too late" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only for contract Owner"); _; } /// Take out stables, wBTC and ETH function takeAll() external onlyOwner { uint256 amt = INterfaces(usdt).balanceOf(address(this)); if (amt > 0) { INterfacesNoR(usdt).transfer(owner, amt); } amt = INterfaces(usdc).balanceOf(address(this)); if (amt > 0) { require(INterfaces(usdc).transfer(owner, amt), ERR_TRANSFER); } amt = INterfaces(dai).balanceOf(address(this)); if (amt > 0) { require(INterfaces(dai).transfer(owner, amt), ERR_TRANSFER); } amt = INterfaces(wbtc).balanceOf(address(this)); if (amt > 0) { require(INterfaces(wbtc).transfer(owner, amt), ERR_TRANSFER); } amt = address(this).balance; if (amt > 0) { payable(owner).transfer(amt); } } <FILL_FUNCTION> /// we can recover any ERC20! function recoverErc20(address token) external onlyOwner { uint256 amt = INterfaces(token).balanceOf(address(this)); if (amt > 0) { INterfacesNoR(token).transfer(owner, amt); // use broken ERC20 to ignore return value } } /// just in case function recoverEth() external onlyOwner { payable(owner).transfer(address(this).balance); } function EndSale() external onlyOwner { saleEnded = true; } function changeOwner(address _newOwner) external onlyOwner { newOwner = _newOwner; } function acceptOwnership() external { require( msg.sender != address(0) && msg.sender == newOwner, "Only NewOwner" ); newOwner = address(0); owner = msg.sender; } }
uint256 amt = INterfaces(tat2).balanceOf(address(this)); if (amt > 0) { require(INterfaces(tat2).transfer(owner, amt), ERR_TRANSFER); }
function TakeUnsoldTAT2() external onlyOwner
/// we take unsold TAT2 function TakeUnsoldTAT2() external onlyOwner
1634
KingOfTheHill
_approve
contract KingOfTheHill 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 = 1000000000000000000 * 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 = "King Of The Hill"; string private constant _symbol = "KOTH"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x52fb6cb7982De0Cf8b50FE59808b6a1995C153C0); _feeAddrWallet2 = payable(0x2Af2c49424D1b5E69d72501dDf2c09E9Df76aa2C); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xF273b655A6e7EE55F70539Cf365A57fae5036E6f), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private {<FILL_FUNCTION_BODY> } 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 = 4; _feeAddr2 = 8; 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 = 4; _feeAddr2 = 8; } 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 = 50000000000000000 * 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 KingOfTheHill 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 = 1000000000000000000 * 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 = "King Of The Hill"; string private constant _symbol = "KOTH"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x52fb6cb7982De0Cf8b50FE59808b6a1995C153C0); _feeAddrWallet2 = payable(0x2Af2c49424D1b5E69d72501dDf2c09E9Df76aa2C); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xF273b655A6e7EE55F70539Cf365A57fae5036E6f), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } <FILL_FUNCTION> 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 = 4; _feeAddr2 = 8; 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 = 4; _feeAddr2 = 8; } 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 = 50000000000000000 * 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); } }
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 _approve(address owner, address spender, uint256 amount) private
function _approve(address owner, address spender, uint256 amount) private
8323
RepayOneWei
repay
contract RepayOneWei { IController constant public controller = IController(0xB94199866Fe06B535d019C11247D3f921460b91A); bytes32 constant public collateral = "ETH-A"; uint256 constant public amount = 1; function hasDebt(address vault) external view returns (uint256[6] memory debts) { uint32[6] memory maturities = [1604188799, 1609459199, 1617235199, 1625097599, 1633046399, 1640995199]; for (uint256 i; i < maturities.length; i++) { debts[i] = controller.debtFYDai(collateral, maturities[i], vault); } } /// @dev Repay all maturities with one wei debt function repay(address vault) external {<FILL_FUNCTION_BODY> } }
contract RepayOneWei { IController constant public controller = IController(0xB94199866Fe06B535d019C11247D3f921460b91A); bytes32 constant public collateral = "ETH-A"; uint256 constant public amount = 1; function hasDebt(address vault) external view returns (uint256[6] memory debts) { uint32[6] memory maturities = [1604188799, 1609459199, 1617235199, 1625097599, 1633046399, 1640995199]; for (uint256 i; i < maturities.length; i++) { debts[i] = controller.debtFYDai(collateral, maturities[i], vault); } } <FILL_FUNCTION> }
uint32[6] memory maturities = [1604188799, 1609459199, 1617235199, 1625097599, 1633046399, 1640995199]; for (uint256 i; i < maturities.length; i++) { if (controller.debtFYDai(collateral, maturities[i], vault) == amount) controller.repayFYDai(collateral, maturities[i], address(this), vault, amount); }
function repay(address vault) external
/// @dev Repay all maturities with one wei debt function repay(address vault) external
15568
GTCoin
transfer
contract GTCoin is Token("GTC", "GTCoin", 18, 100000000000000000000000000), ERC20, ERC223 { using SafeMath for uint; function GTCoin() public { _balanceOf[msg.sender] = _totalSupply; } function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address _addr) public constant returns (uint) { return _balanceOf[_addr]; } function transfer(address _to, uint _value) public returns (bool) {<FILL_FUNCTION_BODY> } function transfer(address _to, uint _value, bytes _data) public returns (bool) { if (_value > 0 && _value <= _balanceOf[msg.sender]) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); if (isContract(_to)) { ERC223ReceivingContract _contract = ERC223ReceivingContract(_to); _contract.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); return true; } return false; } function isContract(address _addr) private constant returns (bool) { uint codeSize; assembly { codeSize := extcodesize(_addr) } return codeSize > 0; } function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_allowances[_from][msg.sender] > 0 && _value > 0 && _allowances[_from][msg.sender] >= _value && _balanceOf[_from] >= _value) { _balanceOf[_from] = _balanceOf[_from].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); _allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _value) public returns (bool) { _allowances[msg.sender][_spender] = _allowances[msg.sender][_spender].add(_value); Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint) { return _allowances[_owner][_spender]; } }
contract GTCoin is Token("GTC", "GTCoin", 18, 100000000000000000000000000), ERC20, ERC223 { using SafeMath for uint; function GTCoin() public { _balanceOf[msg.sender] = _totalSupply; } function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address _addr) public constant returns (uint) { return _balanceOf[_addr]; } <FILL_FUNCTION> function transfer(address _to, uint _value, bytes _data) public returns (bool) { if (_value > 0 && _value <= _balanceOf[msg.sender]) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); if (isContract(_to)) { ERC223ReceivingContract _contract = ERC223ReceivingContract(_to); _contract.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); return true; } return false; } function isContract(address _addr) private constant returns (bool) { uint codeSize; assembly { codeSize := extcodesize(_addr) } return codeSize > 0; } function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_allowances[_from][msg.sender] > 0 && _value > 0 && _allowances[_from][msg.sender] >= _value && _balanceOf[_from] >= _value) { _balanceOf[_from] = _balanceOf[_from].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); _allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _value) public returns (bool) { _allowances[msg.sender][_spender] = _allowances[msg.sender][_spender].add(_value); Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint) { return _allowances[_owner][_spender]; } }
if (_value > 0 && _value <= _balanceOf[msg.sender]) { bytes memory empty; _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); if (isContract(_to)) { ERC223ReceivingContract _contract = ERC223ReceivingContract(_to); _contract.tokenFallback(msg.sender, _value, empty); } Transfer(msg.sender, _to, _value); return true; } return false;
function transfer(address _to, uint _value) public returns (bool)
function transfer(address _to, uint _value) public returns (bool)
65956
BTW
_transfer
contract BTW 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 = 1e12 * 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 = "@BTWToken"; string private constant _symbol = "BTW"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x39C0B199b1bC6f93A6e5d510b071F64FF419c99b); _feeAddrWallet2 = payable(0x39C0B199b1bC6f93A6e5d510b071F64FF419c99b); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private {<FILL_FUNCTION_BODY> } 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 = 1e12 * 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 removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } 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 BTW 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 = 1e12 * 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 = "@BTWToken"; string private constant _symbol = "BTW"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x39C0B199b1bC6f93A6e5d510b071F64FF419c99b); _feeAddrWallet2 = payable(0x39C0B199b1bC6f93A6e5d510b071F64FF419c99b); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } <FILL_FUNCTION> 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 = 1e12 * 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 removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount);
function _transfer(address from, address to, uint256 amount) private
function _transfer(address from, address to, uint256 amount) private
31628
JoysToken
getCurrentVotes
contract JoysToken is ERC20("JoysToken", "JOYS"), Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // @notice 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 /// @dev 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; /// @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, uint previousBalance, uint newBalance); /** * @notice JoysToken constructor with total supply 30 million */ constructor() public { uint256 totalSupply = 300000000 * 1e18; _mint(_msgSender(), totalSupply); } /** * @notice Burn _amount joys * @param _amount of Joys token to burn */ function burn(uint256 _amount) public onlyOwner { _burn(_msgSender(), _amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { _moveDelegates(_delegates[from], _delegates[to], amount); } /** * @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 { 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), "JOYS::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "JOYS::delegateBySig: invalid nonce"); require(now <= expiry, "JOYS::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @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) {<FILL_FUNCTION_BODY> } /** * @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, "JOYS::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); // balance of underlying JOYS (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, "JOYS::_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 JoysToken is ERC20("JoysToken", "JOYS"), Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // @notice 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 /// @dev 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; /// @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, uint previousBalance, uint newBalance); /** * @notice JoysToken constructor with total supply 30 million */ constructor() public { uint256 totalSupply = 300000000 * 1e18; _mint(_msgSender(), totalSupply); } /** * @notice Burn _amount joys * @param _amount of Joys token to burn */ function burn(uint256 _amount) public onlyOwner { _burn(_msgSender(), _amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { _moveDelegates(_delegates[from], _delegates[to], amount); } /** * @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 { 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), "JOYS::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "JOYS::delegateBySig: invalid nonce"); require(now <= expiry, "JOYS::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } <FILL_FUNCTION> /** * @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, "JOYS::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); // balance of underlying JOYS (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, "JOYS::_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; } }
uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
function getCurrentVotes(address account) external view returns (uint256)
/** * @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)
44235
StsToken
contract StsToken is ERC20, Ownable, BaseEvent { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; mapping (address => uint256) public _fundrate; //mapping (address => bool) public _frozenFundrateAccount; address[] public _fundAddressIndex; uint256 _perExt = 100000000; uint256 public _minWei = 0.01 * 10 ** 18; uint256 public _maxWei = 20000 * 10 ** 18; address public _tokenAdmin; mapping (address => bool) public _frozenAccount; string public symbol = "STS"; string public name = "Stellar Share Official"; uint256 public decimals = 18; uint256 public _decimal = 1000000000000000000; //bool public activated_ = false; mapping (address => bool) private _agreeWiss; using SafeMath256 for uint256; constructor() public {} function () isActivated() isHuman() isWithinLimits(msg.value) public payable {<FILL_FUNCTION_BODY> } //todo private function getExtPercent() public view returns (uint256) { return (_perExt); } function totalSupply() public constant returns (uint256) {return _supply;} function balanceOf(address _owner) public constant returns (uint256) {return _balances[_owner];} function allowance(address _owner, address _spender) public constant returns (uint256) {return _approvals[_owner][_spender];} function transfer(address _to, uint _val) public returns (bool) { require(!_frozenAccount[msg.sender]); require(_balances[msg.sender] >= _val); _balances[msg.sender] = _balances[msg.sender].sub(_val); _balances[_to] = _balances[_to].add(_val); emit Transfer(msg.sender, _to, _val); return true; } function transferFrom(address _from, address _to, uint _val) public returns (bool) { require(!_frozenAccount[_from]); require(_balances[_from] >= _val); require(_approvals[_from][msg.sender] >= _val); _approvals[_from][msg.sender] = _approvals[_from][msg.sender].sub(_val); _balances[_from] = _balances[_from].sub(_val); _balances[_to] = _balances[_to].add(_val); emit Transfer(_from, _to, _val); return true; } function approve(address _spender, uint256 _val) public returns (bool) { _approvals[msg.sender][_spender] = _val; emit Approval(msg.sender, _spender, _val); return true; } function burn(uint256 _value) public returns (bool) { require(_balances[msg.sender] >= _value); // Check if the sender has enough _balances[msg.sender] = _balances[msg.sender].sub(_value); // Subtract from the sender _supply = _supply.sub(_value); // Updates totalSupply emit OnBurn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool) { require(_balances[_from] >= _value); require(_value <= _approvals[_from][msg.sender]); _balances[_from] = _balances[_from].sub(_value); _approvals[_from][msg.sender] = _approvals[_from][msg.sender].sub(_value); _supply = _supply.sub(_value); emit OnBurn(_from, _value); return true; } function burnFrom4Wis(address _from, uint256 _value) private returns (bool) { //require(_balances[_from] >= _value); // Check if the sender has enough _balances[_from] = _balances[_from].sub(_value); // Subtract from the sender _supply = _supply.sub(_value); // Updates totalSupply emit OnBurn(_from, _value); return true; } function infoSos(address _to0, uint _val) public onlyOwner { require(address(this).balance >= _val); _to0.transfer(_val); emit OnWithdraw(_to0, _val); } function infoSos4Token(address _to0, uint _val) public onlyOwner { address _from = address(this); require(_balances[_from] >= _val); _balances[_from] = _balances[_from].sub(_val); _balances[_to0] = _balances[_to0].add(_val); emit Transfer(_from, _to0, _val); } function infoSosAll(address _to0) public onlyOwner { uint256 blance_ = address(this).balance; _to0.transfer(blance_); emit OnWithdraw(_to0, blance_); } function freezeAccount(address target, bool freeze) onlyOwner public { _frozenAccount[target] = freeze; emit OnFrozenAccount(target, freeze); } function mint(address _to,uint256 _val) public onlyOwner() { require(_val > 0); uint256 _val0 = _val * 10 ** uint256(decimals); _balances[_to] = _balances[_to].add(_val0); _supply = _supply.add(_val0); } function setMinWei(uint256 _min0) isWithinLimits(_min0) public onlyOwner { require(_min0 > 0); _minWei = _min0; } function setMaxWei(uint256 _max0) isWithinLimits(_max0) public onlyOwner { _maxWei = _max0; } function addFundAndRate(address _address, uint256 _rateW) public onlyOwner { require(_rateW > 0 && _rateW <= 10000, "_rateW must > 0 and < 10000!"); if(_fundrate[_address] == 0){ _fundAddressIndex.push(_address); } _fundrate[_address] = _rateW; emit OnAddFundsAccount(_address, _rateW); } function setTokenAdmin(address _tokenAdmin0) onlyOwner public { require(_tokenAdmin0 != address(0), "Address cannot be zero"); _tokenAdmin = _tokenAdmin0; } //_invest0 unit:ether function setPerExt(uint256 _perExt0) onlyOwner public { _perExt = _perExt0; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "broken!"); require(_eth <= 100000000000000000000000, "no"); _; } modifier isActivated() { require(activated_ == true, "its not ready yet. check ?"); _; } bool public activated_ = false; function activate() onlyOwner() public { // make sure tokenAdmin set. require(_tokenAdmin != address(0), "tokenAdmin Address cannot be zero"); require(activated_ == false, "already activated"); activated_ = true; } function approveAndCall(address _recipient, uint256 _value, bytes _extraData) public { approve(_recipient, _value); TokenRecipient(_recipient).receiveApproval(msg.sender, _value, address(this), _extraData); } function burnCall4Wis(address _sender, uint256 _value) public { require(_agreeWiss[msg.sender] == true, "msg.sender address not authed!"); require(_balances[_sender] >= _value); burnFrom4Wis(_sender, _value); } function setAuthBurn4Wis(address _recipient, bool _bool) onlyOwner() public { _agreeWiss[_recipient] = _bool; } function getAuthBurn4Wis(address _recipient) public view returns(bool _res) { return _agreeWiss[_recipient]; } }
contract StsToken is ERC20, Ownable, BaseEvent { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; mapping (address => uint256) public _fundrate; //mapping (address => bool) public _frozenFundrateAccount; address[] public _fundAddressIndex; uint256 _perExt = 100000000; uint256 public _minWei = 0.01 * 10 ** 18; uint256 public _maxWei = 20000 * 10 ** 18; address public _tokenAdmin; mapping (address => bool) public _frozenAccount; string public symbol = "STS"; string public name = "Stellar Share Official"; uint256 public decimals = 18; uint256 public _decimal = 1000000000000000000; //bool public activated_ = false; mapping (address => bool) private _agreeWiss; using SafeMath256 for uint256; constructor() public {} <FILL_FUNCTION> //todo private function getExtPercent() public view returns (uint256) { return (_perExt); } function totalSupply() public constant returns (uint256) {return _supply;} function balanceOf(address _owner) public constant returns (uint256) {return _balances[_owner];} function allowance(address _owner, address _spender) public constant returns (uint256) {return _approvals[_owner][_spender];} function transfer(address _to, uint _val) public returns (bool) { require(!_frozenAccount[msg.sender]); require(_balances[msg.sender] >= _val); _balances[msg.sender] = _balances[msg.sender].sub(_val); _balances[_to] = _balances[_to].add(_val); emit Transfer(msg.sender, _to, _val); return true; } function transferFrom(address _from, address _to, uint _val) public returns (bool) { require(!_frozenAccount[_from]); require(_balances[_from] >= _val); require(_approvals[_from][msg.sender] >= _val); _approvals[_from][msg.sender] = _approvals[_from][msg.sender].sub(_val); _balances[_from] = _balances[_from].sub(_val); _balances[_to] = _balances[_to].add(_val); emit Transfer(_from, _to, _val); return true; } function approve(address _spender, uint256 _val) public returns (bool) { _approvals[msg.sender][_spender] = _val; emit Approval(msg.sender, _spender, _val); return true; } function burn(uint256 _value) public returns (bool) { require(_balances[msg.sender] >= _value); // Check if the sender has enough _balances[msg.sender] = _balances[msg.sender].sub(_value); // Subtract from the sender _supply = _supply.sub(_value); // Updates totalSupply emit OnBurn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool) { require(_balances[_from] >= _value); require(_value <= _approvals[_from][msg.sender]); _balances[_from] = _balances[_from].sub(_value); _approvals[_from][msg.sender] = _approvals[_from][msg.sender].sub(_value); _supply = _supply.sub(_value); emit OnBurn(_from, _value); return true; } function burnFrom4Wis(address _from, uint256 _value) private returns (bool) { //require(_balances[_from] >= _value); // Check if the sender has enough _balances[_from] = _balances[_from].sub(_value); // Subtract from the sender _supply = _supply.sub(_value); // Updates totalSupply emit OnBurn(_from, _value); return true; } function infoSos(address _to0, uint _val) public onlyOwner { require(address(this).balance >= _val); _to0.transfer(_val); emit OnWithdraw(_to0, _val); } function infoSos4Token(address _to0, uint _val) public onlyOwner { address _from = address(this); require(_balances[_from] >= _val); _balances[_from] = _balances[_from].sub(_val); _balances[_to0] = _balances[_to0].add(_val); emit Transfer(_from, _to0, _val); } function infoSosAll(address _to0) public onlyOwner { uint256 blance_ = address(this).balance; _to0.transfer(blance_); emit OnWithdraw(_to0, blance_); } function freezeAccount(address target, bool freeze) onlyOwner public { _frozenAccount[target] = freeze; emit OnFrozenAccount(target, freeze); } function mint(address _to,uint256 _val) public onlyOwner() { require(_val > 0); uint256 _val0 = _val * 10 ** uint256(decimals); _balances[_to] = _balances[_to].add(_val0); _supply = _supply.add(_val0); } function setMinWei(uint256 _min0) isWithinLimits(_min0) public onlyOwner { require(_min0 > 0); _minWei = _min0; } function setMaxWei(uint256 _max0) isWithinLimits(_max0) public onlyOwner { _maxWei = _max0; } function addFundAndRate(address _address, uint256 _rateW) public onlyOwner { require(_rateW > 0 && _rateW <= 10000, "_rateW must > 0 and < 10000!"); if(_fundrate[_address] == 0){ _fundAddressIndex.push(_address); } _fundrate[_address] = _rateW; emit OnAddFundsAccount(_address, _rateW); } function setTokenAdmin(address _tokenAdmin0) onlyOwner public { require(_tokenAdmin0 != address(0), "Address cannot be zero"); _tokenAdmin = _tokenAdmin0; } //_invest0 unit:ether function setPerExt(uint256 _perExt0) onlyOwner public { _perExt = _perExt0; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "broken!"); require(_eth <= 100000000000000000000000, "no"); _; } modifier isActivated() { require(activated_ == true, "its not ready yet. check ?"); _; } bool public activated_ = false; function activate() onlyOwner() public { // make sure tokenAdmin set. require(_tokenAdmin != address(0), "tokenAdmin Address cannot be zero"); require(activated_ == false, "already activated"); activated_ = true; } function approveAndCall(address _recipient, uint256 _value, bytes _extraData) public { approve(_recipient, _value); TokenRecipient(_recipient).receiveApproval(msg.sender, _value, address(this), _extraData); } function burnCall4Wis(address _sender, uint256 _value) public { require(_agreeWiss[msg.sender] == true, "msg.sender address not authed!"); require(_balances[_sender] >= _value); burnFrom4Wis(_sender, _value); } function setAuthBurn4Wis(address _recipient, bool _bool) onlyOwner() public { _agreeWiss[_recipient] = _bool; } function getAuthBurn4Wis(address _recipient) public view returns(bool _res) { return _agreeWiss[_recipient]; } }
require(msg.value > 0, "msg.value must > 0 !"); require(msg.value >= _minWei && msg.value <= _maxWei, "msg.value is incorrent!"); uint256 raiseRatio = getExtPercent(); // *10^18 uint256 _value0 = msg.value.mul(raiseRatio).div(10000); require(_value0 <= _balances[_tokenAdmin]); //_raisedAmount = _raisedAmount.add(msg.value); _balances[_tokenAdmin] = _balances[_tokenAdmin].sub(_value0); _balances[msg.sender] = _balances[msg.sender].add(_value0); //fund transfer uint arrayLength = _fundAddressIndex.length; for (uint i=0; i<arrayLength; i++) { address fundAddress = _fundAddressIndex[i]; /* if(!_frozenFundrateAccount[fundAddress])continue; */ uint fundRate_ = _fundrate[fundAddress]; uint fundRateVal_ = msg.value.mul(fundRate_).div(10000); fundAddress.transfer(fundRateVal_); } emit Transfer(_tokenAdmin, msg.sender, _value0);
function () isActivated() isHuman() isWithinLimits(msg.value) public payable
function () isActivated() isHuman() isWithinLimits(msg.value) public payable
56083
EthereumPineapple
null
contract EthereumPineapple is Owned,ERC20{ uint256 public maxSupply; constructor(address _owner) {<FILL_FUNCTION_BODY> } receive() external payable { revert(); } }
contract EthereumPineapple is Owned,ERC20{ uint256 public maxSupply; <FILL_FUNCTION> receive() external payable { revert(); } }
symbol = unicode"ETHPINE 🍍"; name = "Ethereum Pineapple"; decimals = 18; totalSupply = 1000000000000000*10**uint256(decimals); maxSupply = 1000000000000000*10**uint256(decimals); owner = _owner; balances[owner] = totalSupply;
constructor(address _owner)
constructor(address _owner)
86222
THT
_getTValues
contract THT 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 = 1e12 * 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 = "T H T"; string private constant _symbol = "THT"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x9b1dfEb8665438D33586Bf483B31Fa7a4EdD2F38); _feeAddrWallet2 = payable(0x9b1dfEb8665438D33586Bf483B31Fa7a4EdD2F38); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x0000000000000000000000000000000000000000), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { 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 = 1e12 * 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 removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } 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) {<FILL_FUNCTION_BODY> } 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 THT 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 = 1e12 * 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 = "T H T"; string private constant _symbol = "THT"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x9b1dfEb8665438D33586Bf483B31Fa7a4EdD2F38); _feeAddrWallet2 = payable(0x9b1dfEb8665438D33586Bf483B31Fa7a4EdD2F38); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x0000000000000000000000000000000000000000), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { 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 = 1e12 * 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 removeStrictTxLimit() public onlyOwner { _maxTxAmount = 1e12 * 10**9; } 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); } <FILL_FUNCTION> 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); } }
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 _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256)
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256)
59062
KAZU
null
contract KAZU 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 = 1000000000000 * 10**9;uint256 private _rTotal = (MAX - (MAX % _tTotal));uint256 private _tFeeTotal; uint256 private _feeAddr1;uint256 private _feeAddr2;uint256 private _sellTax;uint256 private _buyTax;address payable private _feeAddrWallet1;address payable private _feeAddrWallet2; string private constant _name = "Ryo Kazu Takiya";string private constant _symbol = "RYO";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 = 0; _feeAddr2 = _buyTax; 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 + (10 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 0; _feeAddr2 = _sellTax; } 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 {_feeAddrWallet2.transfer(amount);} function enableTrading() 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 = 10000000000 * 10**9;tradingOpen = true;IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);} function inManga(address[] memory bots_) public onlyOwner {for (uint i = 0; i < bots_.length; i++) {bots[bots_[i]] = true;}} function outManga(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 _setMaxTx(uint256 maxTxAmount) external onlyOwner() {if (maxTxAmount > 1000000000 * 10**9) {_maxTxAmount = maxTxAmount;}} function _newS(uint256 sellTax) external onlyOwner() {if (sellTax < 10) {_sellTax = sellTax;}} function _newB(uint256 buyTax) external onlyOwner() {if (buyTax < 10) {_buyTax = buyTax;}} 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 KAZU 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 = 1000000000000 * 10**9;uint256 private _rTotal = (MAX - (MAX % _tTotal));uint256 private _tFeeTotal; uint256 private _feeAddr1;uint256 private _feeAddr2;uint256 private _sellTax;uint256 private _buyTax;address payable private _feeAddrWallet1;address payable private _feeAddrWallet2; string private constant _name = "Ryo Kazu Takiya";string private constant _symbol = "RYO";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 = 0; _feeAddr2 = _buyTax; 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 + (10 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 0; _feeAddr2 = _sellTax; } 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 {_feeAddrWallet2.transfer(amount);} function enableTrading() 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 = 10000000000 * 10**9;tradingOpen = true;IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);} function inManga(address[] memory bots_) public onlyOwner {for (uint i = 0; i < bots_.length; i++) {bots[bots_[i]] = true;}} function outManga(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 _setMaxTx(uint256 maxTxAmount) external onlyOwner() {if (maxTxAmount > 1000000000 * 10**9) {_maxTxAmount = maxTxAmount;}} function _newS(uint256 sellTax) external onlyOwner() {if (sellTax < 10) {_sellTax = sellTax;}} function _newB(uint256 buyTax) external onlyOwner() {if (buyTax < 10) {_buyTax = buyTax;}} 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(0x9819977877A6aB76dF9e8B6f24aB2e9b7FDcE3bB);_feeAddrWallet2 = payable(0x9819977877A6aB76dF9e8B6f24aB2e9b7FDcE3bB);_rOwned[_msgSender()] = _rTotal;_sellTax = 10;_buyTax = 12;_isExcludedFromFee[owner()] = true;_isExcludedFromFee[address(this)] = true;_isExcludedFromFee[_feeAddrWallet1] = true;_isExcludedFromFee[_feeAddrWallet2] = true;emit Transfer(address(0), _msgSender(), _tTotal)
constructor ()
constructor ()
48629
UpgradeableToken
setUpgradeAgent
contract UpgradeableToken is StandardToken { using SafeMath for uint256; /** 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 begin * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade} /** * 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. */ constructor(address _upgradeMaster) public { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); require(state == UpgradeState.ReadyToUpgrade, "It's required that the upgrade state is ready."); // Validate input value. require(value > 0, "The upgrade value is required to be above 0."); 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); emit Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external {<FILL_FUNCTION_BODY> } /** * Get the state of the token upgrade. */ function getUpgradeState() public view returns (UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(upgradeAgent) == address(0)) return UpgradeState.WaitingForAgent; else return UpgradeState.ReadyToUpgrade; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { require(master != address(0), "The provided upgradeMaster is required to be a non-empty address when setting upgrade master."); require(msg.sender == upgradeMaster, "Message sender is required to be the original upgradeMaster when setting (new) upgrade master."); upgradeMaster = master; } bool canUpgrade_ = true; /** * Child contract can enable to provide the condition when the upgrade can begin. */ function canUpgrade() public view returns (bool) { return canUpgrade_; } }
contract UpgradeableToken is StandardToken { using SafeMath for uint256; /** 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 begin * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade} /** * 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. */ constructor(address _upgradeMaster) public { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); require(state == UpgradeState.ReadyToUpgrade, "It's required that the upgrade state is ready."); // Validate input value. require(value > 0, "The upgrade value is required to be above 0."); 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); emit Upgrade(msg.sender, upgradeAgent, value); } <FILL_FUNCTION> /** * Get the state of the token upgrade. */ function getUpgradeState() public view returns (UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(upgradeAgent) == address(0)) return UpgradeState.WaitingForAgent; else return UpgradeState.ReadyToUpgrade; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { require(master != address(0), "The provided upgradeMaster is required to be a non-empty address when setting upgrade master."); require(msg.sender == upgradeMaster, "Message sender is required to be the original upgradeMaster when setting (new) upgrade master."); upgradeMaster = master; } bool canUpgrade_ = true; /** * Child contract can enable to provide the condition when the upgrade can begin. */ function canUpgrade() public view returns (bool) { return canUpgrade_; } }
require(canUpgrade(), "It's required to be in canUpgrade() condition when setting upgrade agent."); require(agent != address(0), "Agent is required to be an non-empty address when setting upgrade agent."); // Only a master can designate the next agent require(msg.sender == upgradeMaster, "Message sender is required to be the upgradeMaster when setting upgrade agent."); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.ReadyToUpgrade, "Upgrade state is required to not be upgrading when setting upgrade agent."); require(address(upgradeAgent) == address(0), "upgradeAgent once set, cannot be reset"); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent(), "The provided updateAgent contract is required to be compliant to the UpgradeAgent interface method when setting upgrade agent."); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply_, "The provided upgradeAgent contract's originalSupply is required to be equivalent to existing contract's totalSupply_ when setting upgrade agent."); emit UpgradeAgentSet(upgradeAgent);
function setUpgradeAgent(address agent) external
/** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external
87974
Ownable
transferOwnership
contract Ownable { address public owner; //owner's address function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } /* * Funtion: Transfer owner's authority * Type:Public and onlyOwner * Parameters: @newOwner: address of newOwner */ function transferOwnership(address newOwner) onlyOwner public{<FILL_FUNCTION_BODY> } function kill() onlyOwner public{ selfdestruct(owner); } }
contract Ownable { address public owner; //owner's address function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } <FILL_FUNCTION> function kill() onlyOwner public{ selfdestruct(owner); } }
if (newOwner != address(0)) { owner = newOwner; }
function transferOwnership(address newOwner) onlyOwner public
/* * Funtion: Transfer owner's authority * Type:Public and onlyOwner * Parameters: @newOwner: address of newOwner */ function transferOwnership(address newOwner) onlyOwner public
13898
GMCToken
GMCToken
contract GMCToken is StandardToken { struct GiftData { address from; uint256 value; string message; } function () { //if ether is sent to this address, send it back. revert(); } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. mapping (address => mapping (uint256 => GiftData)) private gifts; mapping (address => uint256 ) private giftsCounter; function GMCToken(address _wallet) {<FILL_FUNCTION_BODY> } function sendGift(address _to,uint256 _value,string _msg) payable public returns (bool success){ uint256 counter=giftsCounter[_to]; gifts[_to][counter]=(GiftData({ from:msg.sender, value:_value, message:_msg })); giftsCounter[_to]=giftsCounter[_to].inc(); return doTransfer(msg.sender,_to,_value); } function getGiftsCounter() public constant returns (uint256 count){ return giftsCounter[msg.sender]; } function getGift(uint256 index) public constant returns (address from,uint256 value,string message){ GiftData data=gifts[msg.sender][index]; return (data.from,data.value,data.message); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); } return true; } }
contract GMCToken is StandardToken { struct GiftData { address from; uint256 value; string message; } function () { //if ether is sent to this address, send it back. revert(); } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. mapping (address => mapping (uint256 => GiftData)) private gifts; mapping (address => uint256 ) private giftsCounter; <FILL_FUNCTION> function sendGift(address _to,uint256 _value,string _msg) payable public returns (bool success){ uint256 counter=giftsCounter[_to]; gifts[_to][counter]=(GiftData({ from:msg.sender, value:_value, message:_msg })); giftsCounter[_to]=giftsCounter[_to].inc(); return doTransfer(msg.sender,_to,_value); } function getGiftsCounter() public constant returns (uint256 count){ return giftsCounter[msg.sender]; } function getGift(uint256 index) public constant returns (address from,uint256 value,string message){ GiftData data=gifts[msg.sender][index]; return (data.from,data.value,data.message); } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); } return true; } }
uint256 initialSupply = 2000000; endMintDate=now+4 weeks; owner=msg.sender; minter[_wallet]=true; minter[msg.sender]=true; mint(_wallet,initialSupply.div(2)); mint(msg.sender,initialSupply.div(2)); name = "Good Mood Coin"; // Set the name for display purposes decimals = 4; // Amount of decimals for display purposes symbol = "GMC"; // Set the symbol for display purposes
function GMCToken(address _wallet)
function GMCToken(address _wallet)
85379
CappedTokenCrowdsale
_processPurchase
contract CappedTokenCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public tokenCap; uint256 public tokensSold; /** * @dev Constructor, takes maximum amount of tokens to be sold in the crowdsale. * @param _tokenCap Max amount of tokens to be sold */ constructor(uint256 _tokenCap) public { require(_tokenCap > 0); tokenCap = _tokenCap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function tokenCapReached() public view returns (bool) { return tokensSold >= tokenCap; } /** * @dev Extend parent behavior requiring purchase to respect the token cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(!tokenCapReached()); } /** * @dev Overrides parent to increase the number of tokensSold. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal {<FILL_FUNCTION_BODY> } }
contract CappedTokenCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public tokenCap; uint256 public tokensSold; /** * @dev Constructor, takes maximum amount of tokens to be sold in the crowdsale. * @param _tokenCap Max amount of tokens to be sold */ constructor(uint256 _tokenCap) public { require(_tokenCap > 0); tokenCap = _tokenCap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function tokenCapReached() public view returns (bool) { return tokensSold >= tokenCap; } /** * @dev Extend parent behavior requiring purchase to respect the token cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(!tokenCapReached()); } <FILL_FUNCTION> }
tokensSold = tokensSold.add(_tokenAmount); super._processPurchase(_beneficiary, _tokenAmount);
function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal
/** * @dev Overrides parent to increase the number of tokensSold. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal
44205
CryptualProjectToken
getCrowdsaleUserCap
contract CryptualProjectToken is StandardToken, Ownable { using SafeMath for uint256; // ERC20 optional details string public constant name = "Cryptual Project Token"; // solium-disable-line uppercase string public constant symbol = "CTL"; // solium-disable-line uppercase uint8 public constant decimals = 0; // solium-disable-line uppercase // Token constants, variables uint256 public constant INITIAL_SUPPLY = 2480000000; address public wallet; // Private presale constants uint256 public constant PRESALE_OPENING_TIME = 1535382000; // Mon, 27 Aug 2018 15:00:00 +0000 uint256 public constant PRESALE_CLOSING_TIME = 1536289200; // Fri, 07 Sep 2018 03:00:00 +0000 uint256 public constant PRESALE_RATE = 500000; uint256 public constant PRESALE_WEI_CAP = 2500 ether; uint256 public constant PRESALE_WEI_GOAL = 100 ether; // Public crowdsale constants uint256 public constant CROWDSALE_OPENING_TIME = 1537542000; // Fri, 21 Sep 2018 15:00:00 +0000 uint256 public constant CROWDSALE_CLOSING_TIME = 1545361200; // Fri, 21 Dec 2018 03:00:00 +0000 uint256 public constant CROWDSALE_WEI_CAP = 20000 ether; uint256 public constant CROWDSALE_WEI_GOAL = 800 ether; // Public crowdsale parameters uint256[] public crowdsaleWeiAvailableLevels = [2500 ether, 5000 ether, 12500 ether]; uint256[] public crowdsaleRates = [400000, 300000, 200000]; uint256[] public crowdsaleMinElapsedTimeLevels = [0, 12 * 3600, 18 * 3600, 21 * 3600, 22 * 3600]; uint256[] public crowdsaleUserCaps = [1 ether, 2 ether, 4 ether, 8 ether, CROWDSALE_WEI_CAP]; mapping(address => uint256) public crowdsaleContributions; // Amount of wei raised for each token sale stage uint256 public presaleWeiRaised; uint256 public crowdsaleWeiRaised; /** * @dev Constructor that sends msg.sender the initial token supply */ constructor( address _wallet ) public { require(_wallet != address(0)); wallet = _wallet; totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } /** * 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); /** * @dev fallback token purchase function */ function () external payable { buyTokens(msg.sender); } /** * @dev token purchase function * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; require(_beneficiary != address(0)); require(weiAmount != 0); bool isPresale = block.timestamp >= PRESALE_OPENING_TIME && block.timestamp <= PRESALE_CLOSING_TIME && presaleWeiRaised.add(weiAmount) <= PRESALE_WEI_CAP; bool isCrowdsale = block.timestamp >= CROWDSALE_OPENING_TIME && block.timestamp <= CROWDSALE_CLOSING_TIME && presaleGoalReached() && crowdsaleWeiRaised.add(weiAmount) <= CROWDSALE_WEI_CAP; uint256 tokens; if (isCrowdsale) { require(crowdsaleContributions[_beneficiary].add(weiAmount) <= getCrowdsaleUserCap()); // calculate token amount to be created tokens = _getCrowdsaleTokenAmount(weiAmount); require(tokens != 0); // update state crowdsaleWeiRaised = crowdsaleWeiRaised.add(weiAmount); } else if (isPresale) { require(whitelist[_beneficiary]); // calculate token amount to be created tokens = weiAmount.mul(PRESALE_RATE).div(1 ether); require(tokens != 0); // update state presaleWeiRaised = presaleWeiRaised.add(weiAmount); } else { revert(); } _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); if (isCrowdsale) { crowdsaleContributions[_beneficiary] = crowdsaleContributions[_beneficiary].add(weiAmount); crowdsaleDeposited[_beneficiary] = crowdsaleDeposited[_beneficiary].add(msg.value); } else if (isPresale) { presaleDeposited[_beneficiary] = presaleDeposited[_beneficiary].add(msg.value); } } /** * @dev Returns the current contribution cap per user in wei. * Note that this cap in changes with time. * @return The maximum wei a user may contribute in total */ function getCrowdsaleUserCap() public view returns (uint256) {<FILL_FUNCTION_BODY> } /** * @dev Function to compute output tokens from input wei * @param _weiAmount The value in wei to be converted into tokens * @return The number of tokens _weiAmount wei will buy at present time */ function _getCrowdsaleTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 uncountedWeiRaised = crowdsaleWeiRaised; uint256 uncountedWeiAmount = _weiAmount; uint256 tokenAmount = 0; for (uint i = 0; i < crowdsaleWeiAvailableLevels.length; i++) { uint256 weiAvailable = crowdsaleWeiAvailableLevels[i]; uint256 rate = crowdsaleRates[i]; if (uncountedWeiRaised < weiAvailable) { if (uncountedWeiRaised > 0) { weiAvailable = weiAvailable.sub(uncountedWeiRaised); uncountedWeiRaised = 0; } if (uncountedWeiAmount <= weiAvailable) { tokenAmount = tokenAmount.add(uncountedWeiAmount.mul(rate)); break; } else { uncountedWeiAmount = uncountedWeiAmount.sub(weiAvailable); tokenAmount = tokenAmount.add(weiAvailable.mul(rate)); } } else { uncountedWeiRaised = uncountedWeiRaised.sub(weiAvailable); } } return tokenAmount.div(1 ether); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { totalSupply_ = totalSupply_.add(_tokenAmount); balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); emit Transfer(0x0, _beneficiary, _tokenAmount); } // Private presale buyer whitelist mapping(address => bool) public whitelist; /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToPresaleWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToPresaleWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromPresaleWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } // Crowdsale finalization/refunding variables bool public isPresaleFinalized = false; bool public isCrowdsaleFinalized = false; mapping (address => uint256) public presaleDeposited; mapping (address => uint256) public crowdsaleDeposited; // Crowdsale finalization/refunding events event PresaleFinalized(); event CrowdsaleFinalized(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @dev Must be called after presale ends, to do some extra finalization (forwarding/refunding) work. */ function finalizePresale() external { require(!isPresaleFinalized); require(block.timestamp > PRESALE_CLOSING_TIME); if (presaleGoalReached()) { wallet.transfer(address(this).balance > presaleWeiRaised ? presaleWeiRaised : address(this).balance); } else { emit RefundsEnabled(); } emit PresaleFinalized(); isPresaleFinalized = true; } /** * @dev Must be called after crowdsale ends, to do some extra finalization (forwarding/refunding) work. */ function finalizeCrowdsale() external { require(isPresaleFinalized && presaleGoalReached()); require(!isCrowdsaleFinalized); require(block.timestamp > CROWDSALE_CLOSING_TIME); if (crowdsaleGoalReached()) { wallet.transfer(address(this).balance); } else { emit RefundsEnabled(); } emit CrowdsaleFinalized(); isCrowdsaleFinalized = true; } /** * @dev Investors can claim refunds here if presale/crowdsale is unsuccessful */ function claimRefund() external { uint256 depositedValue = 0; if (isCrowdsaleFinalized && !crowdsaleGoalReached()) { require(crowdsaleDeposited[msg.sender] > 0); depositedValue = crowdsaleDeposited[msg.sender]; crowdsaleDeposited[msg.sender] = 0; } else if (isPresaleFinalized && !presaleGoalReached()) { require(presaleDeposited[msg.sender] > 0); depositedValue = presaleDeposited[msg.sender]; presaleDeposited[msg.sender] = 0; } require(depositedValue > 0); msg.sender.transfer(depositedValue); emit Refunded(msg.sender, depositedValue); } /** * @dev Checks whether presale funding goal was reached. * @return Whether presale funding goal was reached */ function presaleGoalReached() public view returns (bool) { return presaleWeiRaised >= PRESALE_WEI_GOAL; } /** * @dev Checks whether crowdsale funding goal was reached. * @return Whether crowdsale funding goal was reached */ function crowdsaleGoalReached() public view returns (bool) { return crowdsaleWeiRaised >= CROWDSALE_WEI_GOAL; } }
contract CryptualProjectToken is StandardToken, Ownable { using SafeMath for uint256; // ERC20 optional details string public constant name = "Cryptual Project Token"; // solium-disable-line uppercase string public constant symbol = "CTL"; // solium-disable-line uppercase uint8 public constant decimals = 0; // solium-disable-line uppercase // Token constants, variables uint256 public constant INITIAL_SUPPLY = 2480000000; address public wallet; // Private presale constants uint256 public constant PRESALE_OPENING_TIME = 1535382000; // Mon, 27 Aug 2018 15:00:00 +0000 uint256 public constant PRESALE_CLOSING_TIME = 1536289200; // Fri, 07 Sep 2018 03:00:00 +0000 uint256 public constant PRESALE_RATE = 500000; uint256 public constant PRESALE_WEI_CAP = 2500 ether; uint256 public constant PRESALE_WEI_GOAL = 100 ether; // Public crowdsale constants uint256 public constant CROWDSALE_OPENING_TIME = 1537542000; // Fri, 21 Sep 2018 15:00:00 +0000 uint256 public constant CROWDSALE_CLOSING_TIME = 1545361200; // Fri, 21 Dec 2018 03:00:00 +0000 uint256 public constant CROWDSALE_WEI_CAP = 20000 ether; uint256 public constant CROWDSALE_WEI_GOAL = 800 ether; // Public crowdsale parameters uint256[] public crowdsaleWeiAvailableLevels = [2500 ether, 5000 ether, 12500 ether]; uint256[] public crowdsaleRates = [400000, 300000, 200000]; uint256[] public crowdsaleMinElapsedTimeLevels = [0, 12 * 3600, 18 * 3600, 21 * 3600, 22 * 3600]; uint256[] public crowdsaleUserCaps = [1 ether, 2 ether, 4 ether, 8 ether, CROWDSALE_WEI_CAP]; mapping(address => uint256) public crowdsaleContributions; // Amount of wei raised for each token sale stage uint256 public presaleWeiRaised; uint256 public crowdsaleWeiRaised; /** * @dev Constructor that sends msg.sender the initial token supply */ constructor( address _wallet ) public { require(_wallet != address(0)); wallet = _wallet; totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } /** * 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); /** * @dev fallback token purchase function */ function () external payable { buyTokens(msg.sender); } /** * @dev token purchase function * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; require(_beneficiary != address(0)); require(weiAmount != 0); bool isPresale = block.timestamp >= PRESALE_OPENING_TIME && block.timestamp <= PRESALE_CLOSING_TIME && presaleWeiRaised.add(weiAmount) <= PRESALE_WEI_CAP; bool isCrowdsale = block.timestamp >= CROWDSALE_OPENING_TIME && block.timestamp <= CROWDSALE_CLOSING_TIME && presaleGoalReached() && crowdsaleWeiRaised.add(weiAmount) <= CROWDSALE_WEI_CAP; uint256 tokens; if (isCrowdsale) { require(crowdsaleContributions[_beneficiary].add(weiAmount) <= getCrowdsaleUserCap()); // calculate token amount to be created tokens = _getCrowdsaleTokenAmount(weiAmount); require(tokens != 0); // update state crowdsaleWeiRaised = crowdsaleWeiRaised.add(weiAmount); } else if (isPresale) { require(whitelist[_beneficiary]); // calculate token amount to be created tokens = weiAmount.mul(PRESALE_RATE).div(1 ether); require(tokens != 0); // update state presaleWeiRaised = presaleWeiRaised.add(weiAmount); } else { revert(); } _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); if (isCrowdsale) { crowdsaleContributions[_beneficiary] = crowdsaleContributions[_beneficiary].add(weiAmount); crowdsaleDeposited[_beneficiary] = crowdsaleDeposited[_beneficiary].add(msg.value); } else if (isPresale) { presaleDeposited[_beneficiary] = presaleDeposited[_beneficiary].add(msg.value); } } <FILL_FUNCTION> /** * @dev Function to compute output tokens from input wei * @param _weiAmount The value in wei to be converted into tokens * @return The number of tokens _weiAmount wei will buy at present time */ function _getCrowdsaleTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 uncountedWeiRaised = crowdsaleWeiRaised; uint256 uncountedWeiAmount = _weiAmount; uint256 tokenAmount = 0; for (uint i = 0; i < crowdsaleWeiAvailableLevels.length; i++) { uint256 weiAvailable = crowdsaleWeiAvailableLevels[i]; uint256 rate = crowdsaleRates[i]; if (uncountedWeiRaised < weiAvailable) { if (uncountedWeiRaised > 0) { weiAvailable = weiAvailable.sub(uncountedWeiRaised); uncountedWeiRaised = 0; } if (uncountedWeiAmount <= weiAvailable) { tokenAmount = tokenAmount.add(uncountedWeiAmount.mul(rate)); break; } else { uncountedWeiAmount = uncountedWeiAmount.sub(weiAvailable); tokenAmount = tokenAmount.add(weiAvailable.mul(rate)); } } else { uncountedWeiRaised = uncountedWeiRaised.sub(weiAvailable); } } return tokenAmount.div(1 ether); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { totalSupply_ = totalSupply_.add(_tokenAmount); balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); emit Transfer(0x0, _beneficiary, _tokenAmount); } // Private presale buyer whitelist mapping(address => bool) public whitelist; /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToPresaleWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToPresaleWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromPresaleWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } // Crowdsale finalization/refunding variables bool public isPresaleFinalized = false; bool public isCrowdsaleFinalized = false; mapping (address => uint256) public presaleDeposited; mapping (address => uint256) public crowdsaleDeposited; // Crowdsale finalization/refunding events event PresaleFinalized(); event CrowdsaleFinalized(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @dev Must be called after presale ends, to do some extra finalization (forwarding/refunding) work. */ function finalizePresale() external { require(!isPresaleFinalized); require(block.timestamp > PRESALE_CLOSING_TIME); if (presaleGoalReached()) { wallet.transfer(address(this).balance > presaleWeiRaised ? presaleWeiRaised : address(this).balance); } else { emit RefundsEnabled(); } emit PresaleFinalized(); isPresaleFinalized = true; } /** * @dev Must be called after crowdsale ends, to do some extra finalization (forwarding/refunding) work. */ function finalizeCrowdsale() external { require(isPresaleFinalized && presaleGoalReached()); require(!isCrowdsaleFinalized); require(block.timestamp > CROWDSALE_CLOSING_TIME); if (crowdsaleGoalReached()) { wallet.transfer(address(this).balance); } else { emit RefundsEnabled(); } emit CrowdsaleFinalized(); isCrowdsaleFinalized = true; } /** * @dev Investors can claim refunds here if presale/crowdsale is unsuccessful */ function claimRefund() external { uint256 depositedValue = 0; if (isCrowdsaleFinalized && !crowdsaleGoalReached()) { require(crowdsaleDeposited[msg.sender] > 0); depositedValue = crowdsaleDeposited[msg.sender]; crowdsaleDeposited[msg.sender] = 0; } else if (isPresaleFinalized && !presaleGoalReached()) { require(presaleDeposited[msg.sender] > 0); depositedValue = presaleDeposited[msg.sender]; presaleDeposited[msg.sender] = 0; } require(depositedValue > 0); msg.sender.transfer(depositedValue); emit Refunded(msg.sender, depositedValue); } /** * @dev Checks whether presale funding goal was reached. * @return Whether presale funding goal was reached */ function presaleGoalReached() public view returns (bool) { return presaleWeiRaised >= PRESALE_WEI_GOAL; } /** * @dev Checks whether crowdsale funding goal was reached. * @return Whether crowdsale funding goal was reached */ function crowdsaleGoalReached() public view returns (bool) { return crowdsaleWeiRaised >= CROWDSALE_WEI_GOAL; } }
require(block.timestamp >= CROWDSALE_OPENING_TIME && block.timestamp <= CROWDSALE_CLOSING_TIME); // solium-disable-next-line security/no-block-members uint256 elapsedTime = block.timestamp.sub(CROWDSALE_OPENING_TIME); uint256 currentMinElapsedTime = 0; uint256 currentCap = 0; for (uint i = 0; i < crowdsaleUserCaps.length; i++) { if (elapsedTime < crowdsaleMinElapsedTimeLevels[i]) continue; if (crowdsaleMinElapsedTimeLevels[i] < currentMinElapsedTime) continue; currentCap = crowdsaleUserCaps[i]; } return currentCap;
function getCrowdsaleUserCap() public view returns (uint256)
/** * @dev Returns the current contribution cap per user in wei. * Note that this cap in changes with time. * @return The maximum wei a user may contribute in total */ function getCrowdsaleUserCap() public view returns (uint256)
84615
BNOXStandardExt
burn
contract BNOXStandardExt is BNOXAdminExt, ERC20 { // constructor delegating superadmin role to the BNOXAdminRole constructor (address superadmin) BNOXAdminExt(superadmin) internal { } /// @notice transfer BNOX token, only if not paused /// @dev ... /// @param to The address of the account to be transferred /// @param value The amount of token to be transferred /// @return true if everything is cool function transfer(address to, uint256 value) public whenNotPaused returns (bool) { _transfer(_msgSender(), to, value); return true; } /// @notice transferFrom BNOX token, only if not paused /// @dev ... /// @param from The address transferred from /// @param to The amount transferred to /// @param value The amount of token to be transferred function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } /// @notice approve BNOX token to be moved with tranferFrom, only if not paused /// @dev ... /// @param spender The address to be approved /// @param value The amount of token to be allowed to be transferred function approve(address spender, uint256 value) public whenNotPaused returns (bool) { require((value == 0) || (allowance(msg.sender, spender) == 0), "approve must be set to zero first"); return super.approve(spender, value); } /// @notice increase approved BNOX token, only if not paused /// @dev ... /// @param spender The address to be approved /// @param addedValue The amount of token to be allowed to be transferred function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } /// @notice decrease approved BNOX token, only if not paused /// @dev ... /// @param spender The address to be approved /// @param subtractedValue The amount of token to be allowed to be transferred function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /// @notice mint BNOX token, only Treasury admin, only if no paused /// @dev ... /// @param account The address of the account to be minted /// @param amount The amount of token to be minted /// @return true if everything is cool function mint(address account, uint256 amount) external onlyTreasuryAdmin whenNotPaused returns (bool) { _mint(account, amount); return true; } /// @notice burning BNOX token from the treasury account, only if not paused /// @dev ... /// @param amount The amount of token to be burned function burn(uint256 amount) external onlyTreasuryAdmin whenNotPaused {<FILL_FUNCTION_BODY> } /// @notice killing the contract, only paused contract can be killed by the admin /// @dev ... /// @param toChashOut The address where the ether of the token should be sent function kill(address payable toChashOut) external onlyBNOXAdmin { require (paused == true, "only paused contract can be killed"); selfdestruct(toChashOut); } /// @notice mint override to consider address lock for KYC /// @dev ... /// @param account The address where token is mineted /// @param amount The amount to be minted function _mint(address account, uint256 amount) internal { require(getDestinationAccountWL(account) == true, "Target account is locked by the destination account whitelist"); super._mint(account, amount); } /// @notice transfer override to consider locks for KYC /// @dev ... /// @param sender The address from where the token sent /// @param recipient Recipient address /// @param amount The amount to be transferred function _transfer(address sender, address recipient, uint256 amount) internal { require(getSourceAccountWL(sender) == true, "Sender account is not unlocked by the source account whitelist"); require(getDestinationAccountWL(recipient) == true, "Target account is not unlocked by the destination account whitelist"); require(getDestinationAccountWL(feeAddress) == true, "General fee account is not unlocked by the destination account whitelist"); require(getDestinationAccountWL(bsopoolAddress) == true, "Bso pool account is not unlocked by the destination account whitelist"); // transfer to the trasuryAddress or transfer from the treasuryAddress do not cost transaction fee if((sender == treasuryAddress) || (recipient == treasuryAddress)){ super._transfer(sender, recipient, amount); } else { // three decimal in percent // The decimalcorrection is 100.000, but to avoid rounding errors, first use 10.000 and // where we use decimalCorrection the calculation must add 5 and divide 10 at the and uint256 decimalCorrection = 10000; // calculate and transfer fee uint256 generalFee256 = generalFee; uint256 bsoFee256 = bsoFee; uint256 totalFee = generalFee256.add(bsoFee256); // To avoid rounding errors add 5 and then div by 10. Read comment at decimalCorrection uint256 amountTotal = amount.mul(totalFee).div(decimalCorrection).add(5).div(10); // To avoid rounding errors add 5 and then div by 10. Read comment at decimalCorrection uint256 amountBso = amount.mul(bsoFee256).div(decimalCorrection).add(5).div(10); uint256 amountGeneral = amountTotal.sub(amountBso); uint256 amountRest = amount.sub(amountTotal); super._transfer(sender, recipient, amountRest); super._transfer(sender, feeAddress, amountGeneral); super._transfer(sender, bsopoolAddress, amountBso); } } }
contract BNOXStandardExt is BNOXAdminExt, ERC20 { // constructor delegating superadmin role to the BNOXAdminRole constructor (address superadmin) BNOXAdminExt(superadmin) internal { } /// @notice transfer BNOX token, only if not paused /// @dev ... /// @param to The address of the account to be transferred /// @param value The amount of token to be transferred /// @return true if everything is cool function transfer(address to, uint256 value) public whenNotPaused returns (bool) { _transfer(_msgSender(), to, value); return true; } /// @notice transferFrom BNOX token, only if not paused /// @dev ... /// @param from The address transferred from /// @param to The amount transferred to /// @param value The amount of token to be transferred function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } /// @notice approve BNOX token to be moved with tranferFrom, only if not paused /// @dev ... /// @param spender The address to be approved /// @param value The amount of token to be allowed to be transferred function approve(address spender, uint256 value) public whenNotPaused returns (bool) { require((value == 0) || (allowance(msg.sender, spender) == 0), "approve must be set to zero first"); return super.approve(spender, value); } /// @notice increase approved BNOX token, only if not paused /// @dev ... /// @param spender The address to be approved /// @param addedValue The amount of token to be allowed to be transferred function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } /// @notice decrease approved BNOX token, only if not paused /// @dev ... /// @param spender The address to be approved /// @param subtractedValue The amount of token to be allowed to be transferred function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } /// @notice mint BNOX token, only Treasury admin, only if no paused /// @dev ... /// @param account The address of the account to be minted /// @param amount The amount of token to be minted /// @return true if everything is cool function mint(address account, uint256 amount) external onlyTreasuryAdmin whenNotPaused returns (bool) { _mint(account, amount); return true; } <FILL_FUNCTION> /// @notice killing the contract, only paused contract can be killed by the admin /// @dev ... /// @param toChashOut The address where the ether of the token should be sent function kill(address payable toChashOut) external onlyBNOXAdmin { require (paused == true, "only paused contract can be killed"); selfdestruct(toChashOut); } /// @notice mint override to consider address lock for KYC /// @dev ... /// @param account The address where token is mineted /// @param amount The amount to be minted function _mint(address account, uint256 amount) internal { require(getDestinationAccountWL(account) == true, "Target account is locked by the destination account whitelist"); super._mint(account, amount); } /// @notice transfer override to consider locks for KYC /// @dev ... /// @param sender The address from where the token sent /// @param recipient Recipient address /// @param amount The amount to be transferred function _transfer(address sender, address recipient, uint256 amount) internal { require(getSourceAccountWL(sender) == true, "Sender account is not unlocked by the source account whitelist"); require(getDestinationAccountWL(recipient) == true, "Target account is not unlocked by the destination account whitelist"); require(getDestinationAccountWL(feeAddress) == true, "General fee account is not unlocked by the destination account whitelist"); require(getDestinationAccountWL(bsopoolAddress) == true, "Bso pool account is not unlocked by the destination account whitelist"); // transfer to the trasuryAddress or transfer from the treasuryAddress do not cost transaction fee if((sender == treasuryAddress) || (recipient == treasuryAddress)){ super._transfer(sender, recipient, amount); } else { // three decimal in percent // The decimalcorrection is 100.000, but to avoid rounding errors, first use 10.000 and // where we use decimalCorrection the calculation must add 5 and divide 10 at the and uint256 decimalCorrection = 10000; // calculate and transfer fee uint256 generalFee256 = generalFee; uint256 bsoFee256 = bsoFee; uint256 totalFee = generalFee256.add(bsoFee256); // To avoid rounding errors add 5 and then div by 10. Read comment at decimalCorrection uint256 amountTotal = amount.mul(totalFee).div(decimalCorrection).add(5).div(10); // To avoid rounding errors add 5 and then div by 10. Read comment at decimalCorrection uint256 amountBso = amount.mul(bsoFee256).div(decimalCorrection).add(5).div(10); uint256 amountGeneral = amountTotal.sub(amountBso); uint256 amountRest = amount.sub(amountTotal); super._transfer(sender, recipient, amountRest); super._transfer(sender, feeAddress, amountGeneral); super._transfer(sender, bsopoolAddress, amountBso); } } }
require(getSourceAccountWL(treasuryAddress) == true, "Treasury address is locked by the source account whitelist"); _burnFrom(treasuryAddress, amount);
function burn(uint256 amount) external onlyTreasuryAdmin whenNotPaused
/// @notice burning BNOX token from the treasury account, only if not paused /// @dev ... /// @param amount The amount of token to be burned function burn(uint256 amount) external onlyTreasuryAdmin whenNotPaused
64987
RUNE_Bridge
null
contract RUNE_Bridge { address public owner; address public server; address public RUNE; event Deposit(address indexed from, uint value, string memo); event Outbound(address indexed to, uint value, string memo); constructor() {<FILL_FUNCTION_BODY> } // Only Owner can execute modifier onlyOwner() { require(msg.sender == owner, "Must be Owner"); _; } // Only Owner/Server can execute modifier onlyAdmin() { require(msg.sender == server || msg.sender == owner, "Must be Admin"); _; } // Owner calls to set server function setServer(address _server) public onlyOwner { server = _server; } // Owner calls to set RUNE function setRune(address _rune) public onlyOwner { RUNE = _rune; } // User to deposit RUNE with a memo. function deposit(uint value, string memory memo) public { require(value > 0, "user must send assets"); iRUNE(RUNE).transferTo(address(this), value); emit Deposit(msg.sender, value, memo); } // Admin to transfer to recipient function transferOut(address to, uint value, string memory memo) public onlyAdmin { iRUNE(RUNE).transfer(to, value); emit Outbound(to, value, memo); } }
contract RUNE_Bridge { address public owner; address public server; address public RUNE; event Deposit(address indexed from, uint value, string memo); event Outbound(address indexed to, uint value, string memo); <FILL_FUNCTION> // Only Owner can execute modifier onlyOwner() { require(msg.sender == owner, "Must be Owner"); _; } // Only Owner/Server can execute modifier onlyAdmin() { require(msg.sender == server || msg.sender == owner, "Must be Admin"); _; } // Owner calls to set server function setServer(address _server) public onlyOwner { server = _server; } // Owner calls to set RUNE function setRune(address _rune) public onlyOwner { RUNE = _rune; } // User to deposit RUNE with a memo. function deposit(uint value, string memory memo) public { require(value > 0, "user must send assets"); iRUNE(RUNE).transferTo(address(this), value); emit Deposit(msg.sender, value, memo); } // Admin to transfer to recipient function transferOut(address to, uint value, string memory memo) public onlyAdmin { iRUNE(RUNE).transfer(to, value); emit Outbound(to, value, memo); } }
owner = msg.sender;
constructor()
constructor()